Download as pdf or txt
Download as pdf or txt
You are on page 1of 4171

Tell us about your PDF experience.

CimCmdlets
Reference

Contains cmdlets that interact with Common Information Model (CIM) Servers like the
Windows
Management Instrumentation (WMI) service.

CimCmdlets
Export-BinaryMiLog Creates a binary encoded representation of an object or objects
and stores it in a file.

Get-CimAssociatedInstance Retrieves the CIM instances that are connected to a specific CIM
instance by an association.

Get-CimClass Gets a list of CIM classes in a specific namespace.

Get-CimInstance Gets the CIM instances of a class from a CIM server.

Get-CimSession Gets the CIM session objects from the current session.

Import-BinaryMiLog Used to re-create the saved objects based on the contents of an


export file.

Invoke-CimMethod Invokes a method of a CIM class.

New-CimInstance Creates a CIM instance.

New-CimSession Creates a CIM session.

New-CimSessionOption Specifies advanced options for the New-CimSession cmdlet.

Register-CimIndicationEvent Subscribes to indications using a filter expression or a query


expression.

Remove-CimInstance Removes a CIM instance from a computer.

Remove-CimSession Removes one or more CIM sessions.

Set-CimInstance Modifies a CIM instance on a CIM server by calling the


ModifyInstance method of the CIM class.
Export-BinaryMiLog
Reference
Module: CimCmdlets

Creates a binary encoded representation of an object or objects and stores it in a file.

Syntax
PowerShell

Export-BinaryMiLog

[-InputObject <CimInstance>]

[-Path] <String>

[<CommonParameters>]

Description
The Export-BinaryMILog cmdlet creates a binary-based representation of an object or
objects and
stores it in a file. You can then use the Import-BinaryMiLog cmdlet to re-
create the saved object
based on the contents of that file.

This cmdlet is similar to Import-Clixml , except that Export-BinaryMILog stores the


resulting
object in a binary encoded file.

Examples

Example 1 - Create a binary representation of


CimInstances
PowerShell

Get-CimInstance Win32_Process | Export-BinaryMiLog -Path "Processes.bmil"

This command exports CimInstances to a binary MI log file specified by the Path
parameter. See
the example for Import-BinaryMiLog to see how to recreate the
CimInstances by importing this
file.
Parameters
-InputObject

Specifies the input to this cmdlet. You can use this parameter, or you can pipe the
input to this
cmdlet.

Type: CimInstance

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Path

Specifies the path of the file in which to store the binary representation of the object.
The
Path parameter supports wildcards and relative paths. This cmdlet generates an
error if the
path resolves to more than one file.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

Inputs
CimInstance

Outputs
Object

Related Links
Get-CimInstance
Import-BinaryMiLog
Import-Clixml
Get-CimAssociatedInstance
Reference
Module: CimCmdlets

Retrieves the CIM instances that are connected to a specific CIM instance by an
association.

Syntax
PowerShell

Get-CimAssociatedInstance

[[-Association] <String>]

[-ResultClassName <String>]

[-InputObject] <CimInstance>

[-Namespace <String>]

[-OperationTimeoutSec <UInt32>]

[-ResourceUri <Uri>]

[-ComputerName <String[]>]

[-KeyOnly]

[<CommonParameters>]

PowerShell

Get-CimAssociatedInstance

[[-Association] <String>]

[-ResultClassName <String>]

[-InputObject] <CimInstance>

[-Namespace <String>]

[-OperationTimeoutSec <UInt32>]

[-ResourceUri <Uri>]

-CimSession <CimSession[]>

[-KeyOnly]

[<CommonParameters>]

Description
The Get-CimAssociatedInstance cmdlet retrieves the CIM instances connected to a
specific CIM
instance, called the source instance, by an association.

In an association, each CIM instance has a named role and the same CIM instance can
participate in
an association in different roles.
If the InputObject parameter is not specified, the cmdlet works in one of the following
ways:

If neither the ComputerName parameter nor the CimSession parameter is


specified, then this
cmdlet works on local Windows Management Instrumentation
(WMI) using a Component Object Model
(COM) session.
If either the ComputerName parameter or the CimSession parameter is specified,
then this
cmdlet works against the CIM server specified by either the
ComputerName parameter or the
CimSession parameter.

Examples

Example 1: Get all the associated instances of a specific


instance
PowerShell

$disk = Get-CimInstance -ClassName Win32_LogicalDisk -KeyOnly

Get-CimAssociatedInstance -InputObject $disk[1]

This set of commands retrieves the instances of the class named Win32_LogicalDisk and
stores the
information in a variable named $disk using the Get-CimInstance cmdlet.
The first logical disk
instance in the variable is then used as the input object for the Get-
CimAssociatedInstance cmdlet
to get all the associated CIM instances of the specified
CIM instance.

Example 2: Get all the associated instances of a specific


type
PowerShell

$disk = Get-CimInstance -ClassName Win32_LogicalDisk -KeyOnly

Get-CimAssociatedInstance -InputObject $disk[1] -ResultClass


Win32_DiskPartition

This set of commands retrieves all the instances of the Win32_LogicalDisk class and
stores
them in a variable named $disk . The first logical disk instance in the variable is
then used as the
input object for the Get-CimAssociatedInstance cmdlet to get all the
associated instances that are
associated through the specified association class
Win32_DiskPartition.
Example 3: Get all the associated instances through
qualifier of a specific class
PowerShell

$s = Get-CimInstance -Query "Select * from Win32_Service where name like


'Winmgmt'"

Get-CimClass -ClassName *Service* -Qualifier "Association"

$c.CimClasName

Win32_LoadOrderGroupServiceDependencies

Win32_DependentService

Win32_SystemServices

Win32_LoadOrderGroupServiceMembers

Win32_ServiceSpecificationService

Get-CimAssociatedInstance -InputObject $s -Association


Win32_DependentService

This set of commands retrieves the services that depend on WMI service and stores
them in a variable
named $s . The association class name for the
Win32_DependentService is retrieved using the
Get-CimClass cmdlet by specifying
Association as the qualifier and is then passed with $s to
the Get-CimAssociatedInstance
cmdlet to get all the associated instances of the retrieved
association class.

Parameters
-Association

Specifies the name of the association class. If you do not specify this parameter, the
cmdlet
returns all existing association objects of any type.

For example, if class A is associated with class B through two associations, AB1 and
AB2, then this
parameter can be used to specify the type of association, either AB1
or AB2.

Type: String

Position: 2

Default value: None

Accept pipeline input: True

Accept wildcard characters: False


-CimSession

Runs the command using the specified CIM session. Enter a variable that contains
the CIM session, or
a command that creates or gets the CIM session, such as New-
CimSession or Get-CimSession . For
more information, see about_CimSession.

Type: CimSession[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-ComputerName

Specifies the name of the computer on which you want to run the CIM operation.
You can specify a
fully qualified domain name (FQDN) or a NetBIOS name.

If you specify this parameter, the cmdlet creates a temporary session to the specified
computer
using the WsMan protocol.

If you do not specify this parameter, the cmdlet performs the operation on the local
computer using
Component Object Model (COM).

If multiple operations are being performed on the same computer, connecting using
a CIM session
gives better performance.

Type: String[]

Aliases: CN, ServerName

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies the input to this cmdlet. You can use this parameter, or you can pipe the
input to this
cmdlet.
The InputObject parameter doesn't enumerate over collections. If a collection is
passed, an
error is thrown. When working with collections, pipe the input to
enumerate the values.

Type: CimInstance

Aliases: CimInstance

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-KeyOnly

Returns objects with only key properties populated. This reduces the amount of data
that is
transferred over the network.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Namespace

Specifies the namespace for the CIM operation. The default namespace is
root/cimv2.

7 Note

You can use tab completion to browse the list of namespaces, because
PowerShell gets a
list of namespaces from the local WMI server to provide the
list of namespaces.

Type: String

Position: Named

Default value: None


Accept pipeline input: True

Accept wildcard characters: False

-OperationTimeoutSec

Specifies the amount of time that the cmdlet waits for a response from the
computer. By default, the
value of this parameter is 0, which means that the cmdlet
uses the default timeout value for the
server.

If the OperationTimeoutSec parameter is set to a value less than the robust


connection retry
timeout of 3 minutes, network failures that last more than the value
of the OperationTimeoutSec
parameter are not recoverable, because the operation
on the server times out before the client can
reconnect.

Type: UInt32

Aliases: OT

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-ResourceUri

Specifies the resource 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://intel.com/wbem/wscim/1/amt-schema/1/AMT_GeneralSettings

By default, if you do not specify this parameter, the DMTF standard resource URI
http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/ is used and the class name is

appended to it.

ResourceURI can only be used with CIM sessions created using the WSMan protocol,
or when
specifying the ComputerName parameter, which creates a CIM session
using WSMan. If you specify
this parameter without specifying the ComputerName
parameter, or if you specify a CIM session
created using DCOM protocol, you get an
error, because the DCOM protocol does not support the
ResourceURI parameter.

If both the ResourceUri parameter and the Filter parameter are specified, the Filter
parameter is ignored.

Type: Uri

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ResultClassName

Specifies the class name of the associated instances. A CIM instance can be
associated with one or
more CIM instances. All associated CIM instances are returned
if you do not specify the result class
name.

By default, the value of this parameter is null, and all associated CIM instances are
returned.

You can filter the association results to match a specific class name. Filtering happens
on the
server. If this parameter is not specified, Get-CIMAssociatedInstance returns
all existing
associations. For example, if class A is associated with classes B, C and D,
then this parameter can
be used to restrict the output to a specific type (B, C or D).

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.


Outputs
CimInstance

This cmdlet returns a CIM instance object.

Related Links
Get-CimClass
Get-CimInstance
Get-CimClass
Reference
Module: CimCmdlets

Gets a list of CIM classes in a specific namespace.

Syntax
PowerShell

Get-CimClass

[[-ClassName] <String>]

[[-Namespace] <String>]

[-OperationTimeoutSec <UInt32>]

[-ComputerName <String[]>]

[-MethodName <String>]

[-PropertyName <String>]

[-QualifierName <String>]

[<CommonParameters>]

PowerShell

Get-CimClass

[[-ClassName] <String>]

[[-Namespace] <String>]

[-OperationTimeoutSec <UInt32>]

-CimSession <CimSession[]>

[-MethodName <String>]

[-PropertyName <String>]

[-QualifierName <String>]

[<CommonParameters>]

Description
The Get-CimClass cmdlet retrieves a list of CIM classes in a specific namespace. If there
is no
class name supplied, then the cmdlet returns all the classes in the namespace.
Unlike a CIM
instance, CIM classes do not contain the CIM session or computer name
from which they are retrieved.

Examples
Example 1: Get all the class definitions
This example gets all the class definitions under the namespace root/cimv2.

PowerShell

Get-CimClass

Example 2: Get the classes with a specific name


This example gets the classes that contain the word disk in their names.

PowerShell

Get-CimClass -ClassName *disk*

Example 3: Get the classes with a specific method name


This example gets the classes that start with the name Win32 and have a method name
that starts
with Term.

PowerShell

Get-CimClass -ClassName Win32* -MethodName Term*

Example 4: Get the classes with a specific property name


This example gets the classes that start with the name Win32 and have a property
named
Handle.

PowerShell

Get-CimClass -ClassName Win32* -PropertyName Handle

Example 5: Get the classes with a specific qualifier name


This example gets the classes that start with the name Win32, contain the word Disk in
their
names and have the specified qualifier Association.

PowerShell
Get-CimClass -ClassName Win32*Disk* -QualifierName Association

Example 6: Get the class definitions from a specific


namespace
This example gets the class definitions that contain the word Net in their names from
the
specified namespace root/standardCimv2.

PowerShell

Get-CimClass -Namespace root/standardCimv2 -ClassName *Net*

Example 7: Get the class definitions from a remote server


This example gets the class definitions that contain the word disk in their names from
the
specified remote servers Server01 and Server02.

PowerShell

Get-CimClass -ClassName *disk* -ComputerName Server01, Server02

Example 8: Get the classes by using a CIM session


PowerShell

$s = New-CimSession -ComputerName Server01, Server02

Get-CimClass -ClassName *disk* -CimSession $s

This set of commands creates a session with multiple computers and stores it into a
variable $s
using the New-CimSession cmdlet, and then gets the classes using the Get-
CimClass cmdlet.

Parameters
-CimSession

Runs the cmdlet in a remote session or on a remote computer. Enter a computer


name or a session
object, such as the output of a New-CimSession or Get-CimSession
cmdlet. The default is the
current session on the local computer.
Type: CimSession[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-ClassName

Specifies the name of the CIM class for which to perform the operation. You can use
tab completion
to browse the list of classes, because PowerShell gets a list of classes
from the local WMI server
to provide a list of class names.

Type: String

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-ComputerName

Specifies the computer on which you want to run the CIM operation. You can specify
a fully qualified
domain name (FQDN) a NetBIOS name, or an IP address.

If you specify this parameter, the cmdlet creates a temporary session to the specified
computer
using the WsMan protocol.

If you do not specify this parameter, the cmdlet performs the operation on the local
computer using
Component Object Model (COM).

If multiple operations are being performed on the same computer, using a CIM
session gives better
performance.

Type: String[]

Aliases: CN, ServerName

Position: Named

Default value: None


Accept pipeline input: True

Accept wildcard characters: False

-MethodName

Finds the classes that have a method matching this name. You can use wildcard
characters with this
parameter.

Type: String

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-Namespace

Specifies the namespace for CIM operation. The default namespace is root/cimv2.
You can use tab
completion to browse the list of namespaces, because PowerShell
gets a list of namespaces from the
local WMI server to provide the list of
namespaces.

Type: String

Position: 2

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-OperationTimeoutSec

Specifies the amount of time that the cmdlet waits for a response from the
computer. By default, the
value of this parameter is 0, which means that the cmdlet
uses the default timeout value for the
server.

If the OperationTimeoutSec parameter is set to a value less than the robust


connection retry
timeout of 3 minutes, network failures that last more than the value
of the OperationTimeoutSec
parameter are not recoverable, because the operation
on the server times out before the client can
reconnect.
Type: UInt32

Aliases: OT

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-PropertyName

Finds the classes which have a property matching this name. You can use wildcard
characters with
this parameter.

Type: String

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-QualifierName

Filters the classes by class level qualifier name. You can use wildcard characters with
this
parameter.

Type: String

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

Inputs
None

You can't pipe objects to this cmdlet.


Outputs
CimClass

This cmdlet returns a CIM class object.

Related Links
New-CimSession
Get-CimInstance
Reference
Module: CimCmdlets

Gets the CIM instances of a class from a CIM server.

Syntax
PowerShell

Get-CimInstance

[-ClassName] <String>

[-ComputerName <String[]>]

[-KeyOnly]

[-Namespace <String>]

[-OperationTimeoutSec <UInt32>]

[-QueryDialect <String>]

[-Shallow]

[-Filter <String>]

[-Property <String[]>]

[<CommonParameters>]

PowerShell

Get-CimInstance

-CimSession <CimSession[]>

-ResourceUri <Uri>

[-KeyOnly]

[-Namespace <String>]

[-OperationTimeoutSec <UInt32>]

[-Shallow]

[-Filter <String>]

[-Property <String[]>]

[<CommonParameters>]

PowerShell

Get-CimInstance

-CimSession <CimSession[]>

[-ResourceUri <Uri>]

[-Namespace <String>]

[-OperationTimeoutSec <UInt32>]

-Query <String>

[-QueryDialect <String>]

[-Shallow]

[<CommonParameters>]
PowerShell

Get-CimInstance

-CimSession <CimSession[]>

[-ClassName] <String>

[-KeyOnly]

[-Namespace <String>]

[-OperationTimeoutSec <UInt32>]

[-QueryDialect <String>]

[-Shallow]

[-Filter <String>]

[-Property <String[]>]

[<CommonParameters>]

PowerShell

Get-CimInstance

-CimSession <CimSession[]>

[-ResourceUri <Uri>]

[-OperationTimeoutSec <UInt32>]

[-InputObject] <CimInstance>

[<CommonParameters>]

PowerShell

Get-CimInstance

[-ResourceUri <Uri>]

[-ComputerName <String[]>]

[-OperationTimeoutSec <UInt32>]

[-InputObject] <CimInstance>

[<CommonParameters>]

PowerShell

Get-CimInstance

-ResourceUri <Uri>

[-ComputerName <String[]>]

[-KeyOnly]

[-Namespace <String>]

[-OperationTimeoutSec <UInt32>]

[-Shallow]

[-Filter <String>]

[-Property <String[]>]

[<CommonParameters>]

PowerShell

Get-CimInstance

[-ResourceUri <Uri>]

[-ComputerName <String[]>]

[-Namespace <String>]

[-OperationTimeoutSec <UInt32>]

-Query <String>

[-QueryDialect <String>]

[-Shallow]

[<CommonParameters>]

Description
The Get-CimInstance cmdlet gets the CIM instances of a class from a CIM server. You
can specify
either the class name or a query for this cmdlet. This cmdlet returns one or
more CIM instance
objects representing a snapshot of the CIM instances present on the
CIM server.

If the InputObject parameter is not specified, the cmdlet works in one of the following
ways:

If neither the ComputerName parameter nor the CimSession parameter is


specified, then this
cmdlet works on local Windows Management Instrumentation
(WMI) using a Component Object Model
(COM) session.
If either the ComputerName parameter or the CimSession parameter is specified,
then this
cmdlet works against the CIM server specified by either the
ComputerName parameter or the
CimSession parameter.

If the InputObject parameter is specified, the cmdlet works in one of the following ways:

If neither the ComputerName parameter nor the CimSession parameter is


specified, then this
cmdlet uses the CIM session or computer name from the input
object.
If the either the ComputerName parameter or the CimSession parameter is
specified, then
this cmdlet uses the either the CimSession parameter value or
ComputerName parameter value.

Examples

Example 1: Get the CIM instances of a specified class


This example retrieves the CIM instances of a class named Win32_Process.

PowerShell

Get-CimInstance -ClassName Win32_Process


Example 2: Get a list of namespaces from a WMI server
This example retrieves a list of namespaces under the Root namespace on a WMI server.

PowerShell

Get-CimInstance -Namespace root -ClassName __Namespace

Example 3: Get instances of a class filtered by using a


query
This example retrieves all the CIM instances that start with the letter P of a class named
Win32_Process using the query specified by a Query parameter.

PowerShell

Get-CimInstance -Query "SELECT * from Win32_Process WHERE name LIKE 'P%'"

Example 4: Get instances of a class filtered by using a


class name and a filter expression
This example retrieves all the CIM instances that start with the letter P of a class named
Win32_Process using the Filter parameter.

PowerShell

Get-CimInstance -ClassName Win32_Process -Filter "Name like 'P%'"

Example 5: Get the CIM instances with only key


properties filled in
This example creates a new CIM instance in memory for a class named Win32_Process
with
the key property @{ "Handle"=0 } and stores it in a variable named $x . The
variable is passed as
a CIM instance to the Get-CimInstance cmdlet to get a particular
instance.

PowerShell
$x = New-CimInstance -ClassName Win32_Process -Namespace root\cimv2 -
Property @{ "Handle"=0 } -Key Handle -ClientOnly

Get-CimInstance -CimInstance $x

Example 6: Retrieve CIM instances and reuse them


This example gets the CIM instances of a class named Win32_Process and stores them
in
the variables $x and $y . The variable $x is then formatted in a table containing only
the
Name and KernelModeTime properties, the table set to AutoSize.

PowerShell

$x,$y = Get-CimInstance -ClassName Win32_Process

$x | Format-Table -Property Name,KernelModeTime -AutoSize

Name KernelModeTime

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

System Idle Process 157238797968750

Example 7: Get CIM instances from remote computer


This example retrieves the CIM instances of a class named Win32_ComputerSystem
from the remote
computers named Server01 and Server02.

PowerShell

Get-CimInstance -ClassName Win32_ComputerSystem -ComputerName


Server01,Server02

Example 8: Getting only the key properties, instead of all


properties
This example retrieves only the key properties, which reduces the size of the object and
network
traffic.

PowerShell

$x = Get-CimInstance -Class Win32_Process -KeyOnly

$x | Invoke-CimMethod -MethodName GetOwner


Example 9: Getting only a subset of properties, instead of
all properties
This example retrieves only a subset of properties, which reduces the size of the object
and network
traffic.

PowerShell

Get-CimInstance -Class Win32_Process -Property Name,KernelModeTime

$x = Get-CimInstance -Class Win32_Process -Property Name,KernelModeTime

$x | Invoke-CimMethod -MethodName GetOwner

The instance retrieved with the Property parameter can be used to perform other CIM
operations,
for example Set-CimInstance or Invoke-CimMethod .

Example 10: Get the CIM instance using CIM session


This example creates a CIM session on the computers named Server01 and Server02
using the
New-CimSession cmdlet and stores the session information in a variable named
$s . The contents of
the variable are then passed to Get-CimInstance by using the

CimSession parameter, to get the


CIM instances of the class named
Win32_ComputerSystem.

PowerShell

$s = New-CimSession -ComputerName Server01,Server02

Get-CimInstance -ClassName Win32_ComputerSystem -CimSession $s

Parameters
-CimSession

Specifies the CIM session to use for this cmdlet. Enter a variable that contains the
CIM session or
a command that creates or gets the CIM session, such as the New-
CimSession or Get-CimSession
cmdlets. For more information, see about_CimSession.

Type: CimSession[]

Position: Named

Default value: None

Accept pipeline input: True


Accept wildcard characters: False

-ClassName

Specifies the name of the CIM class for which to retrieve the CIM instances. You can
use tab
completion to browse the list of classes, because PowerShell gets a list of
classes from the local
WMI server to provide a list of class names.

Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-ComputerName

Specifies computer on which you want to run the CIM operation. You can specify a
fully qualified
domain name (FQDN), a NetBIOS name, or an IP address. If you do not
specify this parameter, the
cmdlet performs the operation on the local computer
using Component Object Model (COM).

If you specify this parameter, the cmdlet creates a temporary session to the specified
computer
using the WsMan protocol.

If multiple operations are being performed on the same computer, connect using a
CIM session for
better performance.

Type: String[]

Aliases: CN, ServerName

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Filter
Specifies a where clause to use as a filter. Specify the clause in either the WQL or the
CQL
query language. Do not include the WHERE keyword in the value of the
parameter.

Type: String

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-InputObject

Specifies a CIM instance object to use as input.

If you are already working with a CIM instance object, you can use this parameter to
pass the CIM
instance object in order to get the latest snapshot from the CIM server.
When you pass a CIM
instance object as an input, Get-CimInstance returns the
object from server using a get CIM
operation, instead of an enumerate or query
operation. Using a get CIM operation is more efficient
than retrieving all instances
and then filtering them.

The InputObject parameter doesn't enumerate over collections. If a collection is


passed, an
error is thrown. When working with collections, pipe the input to
enumerate the values.

If the CIM class does not implement the get operation, then specifying the
InputObject parameter
returns an error.

Type: CimInstance

Aliases: CimInstance

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-KeyOnly
Indicates that only objects with key properties populated are returned. Specifying
the KeyOnly
parameter reduces the amount of data transferred over the network.

Use the KeyOnly parameter to return only a small portion of the object, which can be
used for other
operations, such as the Set-CimInstance or Get-
CimAssociatedInstance cmdlets.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Namespace

Specifies the namespace of CIM class.

The default namespace is root/cimv2. You can use tab completion to browse the list
of
namespaces, because PowerShell gets a list of namespaces from the local WMI
server to provide the
list of namespaces.

Type: String

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-OperationTimeoutSec

Specifies the amount of time that the cmdlet waits for a response from the
computer. By default, the
value of this parameter is 0, which means that the cmdlet
uses the default timeout value for the
server.

If the OperationTimeoutSec parameter is set to a value less than the robust


connection retry
timeout of 3 minutes, network failures that last more than the value
of the OperationTimeoutSec
parameter are not recoverable, because the operation
on the server times out before the client can
reconnect.

Type: UInt32
Aliases: OT

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Property

Specifies a set of instance properties to retrieve. Use this parameter when you need
to reduce the
size of the object returned, either in memory or over the network. The
object returned also contains
the key properties even if you have not listed them
using the Property parameter. Other
properties of the class are present but they are
not populated.

Type: String[]

Aliases: SelectProperties

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Query

Specifies a query to run on the CIM server. If the value specified contains double
quotes " ,
single quotes ' , or a backslash \ , you must escape those characters by
prefixing them with the
backslash character. If the value specified uses the WQL LIKE
operator, then you must escape
the following characters by enclosing them in
square brackets [] : percent % , underscore _ ,
or opening square bracket [ .

You cannot use a metadata query to retrieve a list of classes or an event query. To
retrieve a list
of classes, use the Get-CimClass cmdlet. To retrieve an event query, use
the
Register-CimIndicationEvent cmdlet.

You can specify the query dialect using the QueryDialect parameter.

Type: String
Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-QueryDialect

Specifies the query language used for the Query parameter. The acceptable values
for this parameter
are: WQL or CQL. The default value is WQL.

Type: String

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-ResourceUri

Specifies the resource 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://intel.com/wbem/wscim/1/amt-schema/1/AMT_GeneralSettings

By default, if you do not specify this parameter, the DMTF standard resource URI
http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/ is used and the class name is

appended to it.

ResourceURI can only be used with CIM sessions created using the WSMan protocol,
or when
specifying the ComputerName parameter, which creates a CIM session
using WSMan. If you specify
this parameter without specifying the ComputerName
parameter, or if you specify a CIM session
created using DCOM protocol, you will get
an error, because the DCOM protocol does not support the
ResourceURI parameter.

If both the ResourceUri parameter and the Filter parameter are specified, the Filter
parameter is ignored.
Type: Uri

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Shallow

Indicates that the instances of a class are returned without including the instances of
any child
classes. By default, the cmdlet returns the instances of a class and its child
classes.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
CimInstance

You can pipe a CIM instance object to this cmdlet.

Outputs
CimInstance

This cmdlet returns one or more CIM instance objects representing a snapshot of the
CIM instances on
the CIM server.

Related Links
Format-Table
Get-CimAssociatedInstance
Get-CimClass
Invoke-CimMethod
New-CimInstance
Register-CimIndicationEvent
Remove-CimInstance
Set-CimInstance
Get-CimSession
Reference
Module: CimCmdlets

Gets the CIM session objects from the current session.

Syntax
PowerShell

Get-CimSession

[[-ComputerName] <String[]>]

[<CommonParameters>]

PowerShell

Get-CimSession

[-Id] <UInt32[]>

[<CommonParameters>]

PowerShell

Get-CimSession

-InstanceId <Guid[]>

[<CommonParameters>]

PowerShell

Get-CimSession

-Name <String[]>

[<CommonParameters>]

Description
By default, the cmdlet gets all of the CIM sessions created in the current PowerShell
session. You
can use the parameters of Get-CimSession to get the sessions that are for
particular computers, or
you can identify sessions by their names or other identifiers.
Get-CimSession does not get CIM
sessions that were created in other PowerShell

sessions or that were created on other computers.


For more information about CIM sessions, see about_CimSession.

Examples

Example 1: Get CIM sessions from the current PowerShell


session
This example creates CIM sessions using New-CimSession, and then gets the CIM
sessions using Get-CimSession .

PowerShell

New-CimSession -ComputerName Server01,Server02

Get-CimSession

Id : 1

Name : CimSession1

InstanceId : d1413bc3-162a-4cb8-9aec-4d2c61253d59

ComputerName : Server01

Protocol : WSMAN

Id : 2

Name : CimSession2

InstanceId : c0095981-52c5-4e7f-a5bb-c4c680541710

ComputerName : Server02

Protocol : WSMAN

Example 2: Get the CIM sessions to a specific computer


This example gets the CIM sessions that are connected to the computer named
Server02.

PowerShell

Get-CimSession -ComputerName Server02

Id : 2

Name : CimSession2

InstanceId : c0095981-52c5-4e7f-a5bb-c4c680541710

ComputerName : Server02

Protocol : WSMAN

Example 3: Get a list of CIM sessions and then format the


list
This example gets all CIM sessions in the current PowerShell session and displays a table
containing
only the ComputerName and InstanceID properties.

PowerShell

Get-CimSession | Format-Table -Property ComputerName,InstanceId

ComputerName InstanceId

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

Server01 d1413bc3-162a-4cb8-9aec-4d2c61253d59

Server02 c0095981-52c5-4e7f-a5bb-c4c680541710

Example 4: Get all the CIM sessions that have specific


names
This example gets all CIM sessions that have names that begin with serv.

PowerShell

Get-CimSession -ComputerName Serv*

Id : 1

Name : CimSession1

InstanceId : d1413bc-162a-4cb8-9aec-4d2c61253d59

ComputerName : Server01

Protocol : WSMAN

Id : 2

Name : CimSession2

InstanceId : c0095981-52c5-4e7f-a5bb-c4c680541710

ComputerName : Server02

Protocol : WSMAN

Example 5: Get a specific CIM session


This example gets the CIM session that has an Id of 2.

PowerShell

Get-CimSession -ID 2

Id : 2

Name : CimSession2

InstanceId : c0095981-52c5-4e7f-a5bb-c4c680541710

ComputerName : Server02

Protocol : WSMAN
Parameters
-ComputerName

Specifies the name of the computer to get CIM sessions connected to. Wildcard
characters are
permitted.

Type: String[]

Aliases: CN, ServerName

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-Id

Specifies the identifier of the CIM session to get. For multiple IDs, use commas to
separate the IDs
or use the range operator ( .. ) to specify a range of IDs. An Id is an
integer that uniquely
identifies the CIM session within the current PowerShell
session.

For more information about the range operator, see about_Operators.

Type: UInt32[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-InstanceId

Specifies the instance IDs of the CIM session to get.

InstanceId is a globally-unique identifier (GUID) that uniquely identifies a CIM


session. The
InstanceId is unique, even when you have multiple sessions running in
PowerShell.
The InstanceId is stored in the InstanceId property of the object that represents a
CIM
session.

Type: Guid[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Gets one or more CIM sessions which contain the specified friendly names. Wildcard
characters are
permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
CimSession

This cmdlet returns a CIM session object.

Related Links
Format-Table
New-CimSession
Remove-CimSession
about_CimSession
Import-BinaryMiLog
Reference
Module: CimCmdlets

Used to re-create the saved objects based on the contents of an export file.

Syntax
PowerShell

Import-BinaryMiLog

[-Path] <String>

[<CommonParameters>]

Description
Use this cmdlet to re-create saved objects based on the contents of an export file
created by
Export-BinaryMILog . This cmdlet is similar to Import-Clixml , except that
Export-BinaryMILog
stores the resulting object in a binary encoded file.

Examples

Example 1 - Restore objects exported to a file


PowerShell

Import-BinaryMiLog -Path "Processes.bmil"

Parameters
-Path

Specifies the path of the file in which to store the binary representation of the object.
The
Path parameter supports wildcards and relative paths. This cmdlet generates an
error if the path
resolves to more than one file.

Type: String
Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
Object
Invoke-CimMethod
Reference
Module: CimCmdlets

Invokes a method of a CIM class.

Syntax
PowerShell

Invoke-CimMethod

[-ClassName] <String>

[-ComputerName <String[]>]

[[-Arguments] <IDictionary>]

[-MethodName] <String>

[-Namespace <String>]

[-OperationTimeoutSec <UInt32>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Invoke-CimMethod

[-ClassName] <String>

-CimSession <CimSession[]>

[[-Arguments] <IDictionary>]

[-MethodName] <String>

[-Namespace <String>]

[-OperationTimeoutSec <UInt32>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Invoke-CimMethod

-ResourceUri <Uri>

[-ComputerName <String[]>]

[[-Arguments] <IDictionary>]

[-MethodName] <String>

[-Namespace <String>]

[-OperationTimeoutSec <UInt32>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]
PowerShell

Invoke-CimMethod

[-ResourceUri <Uri>]

[-InputObject] <CimInstance>

-CimSession <CimSession[]>

[[-Arguments] <IDictionary>]

[-MethodName] <String>

[-OperationTimeoutSec <UInt32>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Invoke-CimMethod

[-ResourceUri <Uri>]

[-InputObject] <CimInstance>

[-ComputerName <String[]>]

[[-Arguments] <IDictionary>]

[-MethodName] <String>

[-OperationTimeoutSec <UInt32>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Invoke-CimMethod

-ResourceUri <Uri>

-CimSession <CimSession[]>

[[-Arguments] <IDictionary>]

[-MethodName] <String>

[-Namespace <String>]

[-OperationTimeoutSec <UInt32>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Invoke-CimMethod

[-CimClass] <CimClass>

[-ComputerName <String[]>]

[[-Arguments] <IDictionary>]

[-MethodName] <String>

[-OperationTimeoutSec <UInt32>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]
PowerShell

Invoke-CimMethod

[-CimClass] <CimClass>

-CimSession <CimSession[]>

[[-Arguments] <IDictionary>]

[-MethodName] <String>

[-OperationTimeoutSec <UInt32>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Invoke-CimMethod

-Query <String>

[-QueryDialect <String>]

[-ComputerName <String[]>]

[[-Arguments] <IDictionary>]

[-MethodName] <String>

[-Namespace <String>]

[-OperationTimeoutSec <UInt32>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Invoke-CimMethod

-Query <String>

[-QueryDialect <String>]

-CimSession <CimSession[]>

[[-Arguments] <IDictionary>]

[-MethodName] <String>

[-Namespace <String>]

[-OperationTimeoutSec <UInt32>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Invoke-CimMethod cmdlet invokes a method of a CIM class or CIM instance using the
name-value
pairs specified by the Arguments parameter.
If the InputObject parameter is not specified, the cmdlet works in one of the following
ways:

If neither the ComputerName parameter nor the CimSession parameter is


specified, then this
cmdlet works on local Windows Management Instrumentation
(WMI) using a Component Object Model
(COM) session.
If either the ComputerName parameter or the CimSession parameter is specified,
then this
cmdlet works against the CIM server specified by either the
ComputerName parameter or the
CimSession parameter.

If the InputObject parameter is specified, the cmdlet works in one of the following ways:

If neither the ComputerName parameter nor the CimSession parameter is


specified, then this
cmdlet uses the CIM session or computer name from the input
object.
If the either the ComputerName parameter or the CimSession parameter is
specified, then
this cmdlet uses the either the CimSession parameter value or
ComputerName parameter
value. This is not a common scenario.

Examples

Example 1: Invoke a method


This example invokes the Terminate method of the Win32_Process class.

PowerShell

Invoke-CimMethod -Query 'select * from Win32_Process where name like


"notepad%"' -MethodName "Terminate"

Example 2: Invoke a method using CIM instance object


This example retrieves the CIM instance object and stores it in a variable named $x
using the
Get-CimInstance cmdlet. The contents of the variable are then used as the
InputObject for the
Invoke-CimMethod cmdlet. The GetOwner method is invoked for the
CimInstance.

PowerShell

$x = Get-CimInstance -Query 'Select * from Win32_Process where name like


"notepad%"'

Invoke-CimMethod -InputObject $x -MethodName GetOwner


Example 3: Invoke a static method using arguments
This example invokes the Create method named using the Arguments parameter.

PowerShell

Invoke-CimMethod -ClassName Win32_Process -MethodName "Create" -Arguments @{

CommandLine = 'notepad.exe'; CurrentDirectory = "C:\windows\system32"

Example 4: Client-side validation


This example performs client-side validation for the xyz method by passing a CimClass
object
to Invoke-CimMethod .

PowerShell

$c = Get-CimClass -ClassName Win32_Process

Invoke-CimMethod -CimClass $c -MethodName "xyz" -Arguments @{ CommandLine =


'notepad.exe' }

Parameters
-Arguments

Specifies the parameters to pass to the called method. Specify the values for this
parameter as
name-value pairs, stored in a hash table. The order of the values
entered isn't important.

Type: IDictionary

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-CimClass
Specifies a CIM class object that represents a CIM class definition on the server. Use
this
parameter when invoking a static method of a class.

You can use the Get-CimClass cmdlet to retrieve a class definition from the server.

Using this parameter results in better client side schema validations.

Type: CimClass

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-CimSession

Runs the command using the specified CIM session. Enter a variable that contains
the CIM session, or
a command that creates or gets the CIM session, such as the
New-CimSession or Get-CimSession
cmdlets. For more information, see

about_CimSession.

Type: CimSession[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-ClassName

Specifies the name of the CIM class for which to perform the operation. This
parameter is only used
for static methods. You can use tab completion to browse the
list of classes, because PowerShell
gets a list of classes from the local WMI server to
provide a list of class names.

Type: String

Aliases: Class

Position: 0

Default value: None


Accept pipeline input: True

Accept wildcard characters: False

-ComputerName

Specifies the name of the computer on which you want to run the CIM operation.
You can specify a
fully qualified domain name (FQDN), a NetBIOS name, or an IP
address.

When using this parameter, the cmdlet creates a temporary session to the specified
computer using
the WsMan protocol. Otherwise, the cmdlet performs the operation
on the local computer using
Component Object Model (COM).

Connect using a CIM session for better performance when multiple operations are
being performed on
the same computer.

Type: String[]

Aliases: CN, ServerName

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-InputObject
Specifies a CIM instance object to use as input to invoke a method. This parameter
can only be used
to invoke instance methods. To invoke class static methods, use the
Class parameter or the
CimClass parameter.

Type: CimInstance

Aliases: CimInstance

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-MethodName

Specifies the name of the CIM method to invoke. This parameter is mandatory and
cannot be null or
empty. To invoke static method of a CIM class use the ClassName
or the CimClass parameter.

Type: String

Aliases: Name

Position: 2

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Namespace

Specifies the namespace for the CIM operation. The default namespace is
root/cimv2. You can use
tab completion to browse the list of namespaces, because
PowerShell gets a list of namespaces from
the local WMI server to provide the list of
namespaces.

Type: String

Position: Named

Default value: None

Accept pipeline input: True


Accept wildcard characters: False

-OperationTimeoutSec

Specifies the amount of time that the cmdlet waits for a response from the
computer. By default, the
value is 0, which means that the cmdlet uses the default
timeout value for the server.

If the OperationTimeoutSec parameter is set to a value less than the default


connection retry
timeout of 3 minutes, network failures that last more than the value
of the OperationTimeoutSec
parameter are not recoverable.

Type: UInt32

Aliases: OT

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Query

Specifies a query to run on the CIM server. A method is invoked on the instances
received as a
result of the query. You can specify the query dialect using the
QueryDialect parameter.

If the value specified contains double quotes ( " ), single quotes ( ' ), or a backslash
( \ ), you
must escape those characters by prefixing them with the backslash ( \ )
character. If the value
specified uses the WQL LIKE operator, then you must escape
the following characters by enclosing
them in square brackets ( [] ): percent ( % ),
underscore ( _ ), or opening square bracket ( [ ).

Type: String

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False


-QueryDialect

Specifies the query language used for the Query parameter. The acceptable values
for this parameter
are: WQL or CQL.

The default value is WQL.

Type: String

Position: Named

Default value: WQL

Accept pipeline input: True

Accept wildcard characters: False

-ResourceUri

Specifies the resource 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://intel.com/wbem/wscim/1/amt-schema/1/AMT_GeneralSettings

By default, if you do not specify this parameter, the DMTF standard resource URI
http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/ is used and the class name is
appended to it.

ResourceURI can only be used with CIM sessions created using the WSMan protocol,
or when
specifying the ComputerName parameter, which creates a CIM session
using WSMan.

When you specify this parameter without specifying the ComputerName parameter,
or when you
specify a CIM session created using DCOM protocol, you get an error.
The DCOM protocol does not
support the ResourceURI parameter.

If both the ResourceUri parameter and the Filter parameter are specified, the Filter
parameter is ignored.

Type: Uri

Position: Named
Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
CimClass

You can pipe a CIM class to this cmdlet.

CimInstance

You can pipe a CIM instance to this cmdlet.

Outputs
PSCustomObject

This cmdlet returns an object.

Related Links
Get-CimClass
Get-CimInstance
Get-CimSession
New-CimSession
New-CimInstance
Reference
Module: CimCmdlets

Creates a CIM instance.

Syntax
PowerShell

New-CimInstance

[-ClassName] <String>

[-Key <String[]>]

[[-Property] <IDictionary>]

[-Namespace <String>]

[-OperationTimeoutSec <UInt32>]

[-ComputerName <String[]>]

[-ClientOnly]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

New-CimInstance

[-ClassName] <String>

[-Key <String[]>]

[[-Property] <IDictionary>]

[-Namespace <String>]

[-OperationTimeoutSec <UInt32>]

-CimSession <CimSession[]>

[-ClientOnly]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

New-CimInstance

-ResourceUri <Uri>

[-Key <String[]>]

[[-Property] <IDictionary>]

[-Namespace <String>]

[-OperationTimeoutSec <UInt32>]

-CimSession <CimSession[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

New-CimInstance

-ResourceUri <Uri>

[-Key <String[]>]

[[-Property] <IDictionary>]

[-Namespace <String>]

[-OperationTimeoutSec <UInt32>]

[-ComputerName <String[]>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

New-CimInstance

[-CimClass] <CimClass>

[[-Property] <IDictionary>]

[-OperationTimeoutSec <UInt32>]

-CimSession <CimSession[]>

[-ClientOnly]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

New-CimInstance

[-CimClass] <CimClass>

[[-Property] <IDictionary>]

[-OperationTimeoutSec <UInt32>]

[-ComputerName <String[]>]

[-ClientOnly]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The New-CimInstance cmdlet creates an instance of a CIM class based on the class
definition on
either the local computer or a remote computer. By default, the New-
CimInstance cmdlet creates an
instance on the local computer.
Examples

Example 1: Create an instance of a CIM class


This example creates an instance of a CIM Class named win32_environment in the
root/cimv2 namespace
on the computer.

PowerShell

New-CimInstance -ClassName Win32_Environment -Property


@{Name="testvar";VariableValue="testvalue";UserName="domain\user"}

No client side validation is performed if the class does not exist, the properties are
wrong, or if
the server rejects the call. If the instance is created successfully, the cmdlet
outputs the newly
created instance.

Example 2: Create an instance of a CIM class using a class


schema
This example retrieves a CIM class object and stores it in a variable named $class . The
contents
of the variable are then passed to the New-CimInstance cmdlet.

PowerShell

$class = Get-CimClass -ClassName Win32_Environment

New-CimInstance -CimClass $class -Property


@{Name="testvar";VariableValue="testvalue";UserName="Contoso\User1"}

Example 3: Create a dynamic instance on the client


This example creates a dynamic instance of a CIM class named Win32_Process on the
client
computer without getting the instance from the server. The new instance is stored
in the variable
$a . This dynamic instance can be used to perform operations if the
instance with this key exists
on the server.

PowerShell

$a = New-CimInstance -ClassName Win32_Process -Property @{Handle=0} -Key


Handle -ClientOnly

Get-CimInstance -CimInstance $a

Invoke-CimMethod -CimInstance $a -MethodName GetOwner

ProcessId Name HandleCount WorkingSetSize VirtualSize

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

0 System Idle Process 0 8192 8192

Domain :

ReturnValue : 2

User :

PSComputerName :

The Get-CimInstance cmdlet then retrieves a particular single instance. The Invoke-
CimMethod
cmdlet calls the GetOwner method on the retrieved instance.

Example 4: Create an instance for a CIM class of a specific


namespace
This example gets an instance of a CIM class named MSFT_Something in the namespace
root/somewhere and stores it in a variable named $class . The variable is passed to the
New-CimInstance cmdlet to create a new CIM instance and perform client side

validations on the new


instance.

PowerShell

$class = Get-CimClass -ClassName MSFT_Something -Namespace root/somewhere

New-CimInstance -CimClass $class -Property @{"Prop1"=1;"Prop2"="value"} -


ClientOnly

In this example, using the CimClass parameter instead of the ClassName parameter
validates
that Prop1 and Prop2 actually exist and that the keys are marked correctly.

You cannot use the ComputerName or CimSession parameter with the ClientOnly
parameter.

Parameters
-CimClass

Specifies a CIM class object that represents the type of the instance. Use the Get-
CimClass cmdlet
to retrieve the class declaration from a computer. Using this

parameter results in better client


side schema validations.

Type: CimClass

Position: 0
Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-CimSession

Runs the command using the specified CIM session. Enter a variable that contains
the CIM session, or
a command that creates or gets the CIM session, such as the
New-CimSession or Get-CimSession
cmdlets. For more information, see
about_CimSession.

Type: CimSession[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-ClassName

Specifies the name of the CIM class of which the operation creates an instance.
NOTE: You can use
tab completion to browse the list of classes, because PowerShell
gets a list of classes from the
local WMI server to provide a list of class names.

Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-ClientOnly

Indicates that the instance is only created in PowerShell without going to the CIM
server. You can
use this parameter to create an in-memory CIM instance for use in
subsequent PowerShell operations.

Type: SwitchParameter
Aliases: Local

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ComputerName

Specifies the name of the computer on which you want to run the CIM operation.
You can specify a
fully qualified domain name (FQDN), a NetBIOS name, or an IP
address.

If you specify this parameter, the cmdlet creates a temporary session to the specified
computer
using the WSMan protocol.

If you do not specify this parameter, the cmdlet performs the operation on the local
computer using
Component Object Model (COM).

If multiple operations are being performed on the same computer, connecting using
a CIM session
gives better performance.

Type: String[]

Aliases: CN, ServerName

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False


Accept pipeline input: False

Accept wildcard characters: False

-Key

Specifies the properties that are used as keys. CimSession and ComputerName
cannot be used
when Key is specified.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Namespace

Specifies the namespace of the class for the new instance. The default namespace is
root/cimv2.
You can use tab completion to browse the list of namespaces, because
PowerShell gets a list of
namespaces from the local WMI server to provide the list of
namespaces.

Type: String

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-OperationTimeoutSec

Specifies the amount of time that the cmdlet waits for a response from the CIM
server. By default,
the value of this parameter is 0, which means that the cmdlet uses
the default timeout value for the
server. If the OperationTimeoutSec parameter is
set to a value less than the robust connection retry
timeout of 3 minutes, network
failures that last more than the value of the OperationTimeoutSec
parameter are not
recoverable, because the operation on the server times out before the client can
reconnect.
Type: UInt32

Aliases: OT

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Property

Specifies the properties of the CIM instance using a hash table (name-value pairs).

If you specify the CimClass parameter, then the New-CimInstance cmdlet performs a
property
validation on the client to make sure that the properties specified are
consistent with the class
declaration on the server. If the CimClass parameter is not
specified, then the property
validation is done on the server.

Type: IDictionary

Aliases: Arguments

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-ResourceUri

Specifies the resource 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://intel.com/wbem/wscim/1/amt-schema/1/AMT_GeneralSettings

By default, if you do not specify this parameter, the DMTF standard resource URI
http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/ is used and the class name is

appended to it.
ResourceURI can only be used with CIM sessions created using the WSMan protocol,
or when
specifying the ComputerName parameter, which creates a CIM session
using WSMan. If you specify
this parameter without specifying the ComputerName
parameter, or if you specify a CIM session
created using DCOM protocol, you will get
an error, because the DCOM protocol does not support the
ResourceURI parameter.

If both the ResourceUri parameter and the Filter parameter are specified, the Filter
parameter is ignored.

Type: Uri

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
Object

This cmdlet returns an object that contains the CIM instance information.
Related Links
Get-CimClass
Get-CimInstance
Remove-CimInstance
Set-CimInstance
New-CimSession
Reference
Module: CimCmdlets

Creates a CIM session.

Syntax
PowerShell

New-CimSession

[-Authentication <PasswordAuthenticationMechanism>]

[[-Credential] <PSCredential>]
[[-ComputerName] <String[]>]

[-Name <String>]

[-OperationTimeoutSec <UInt32>]

[-SkipTestConnection]

[-Port <UInt32>]

[-SessionOption <CimSessionOptions>]

[<CommonParameters>]

PowerShell

New-CimSession

[-CertificateThumbprint <String>]

[[-ComputerName] <String[]>]

[-Name <String>]

[-OperationTimeoutSec <UInt32>]

[-SkipTestConnection]

[-Port <UInt32>]

[-SessionOption <CimSessionOptions>]

[<CommonParameters>]

Description
The New-CimSession cmdlet creates a CIM session. A CIM session is a client-side object
representing a connection to a local computer or a remote computer. The CIM session
contains
information about the connection, such as ComputerName, the protocol used,
or various
identifiers.

This cmdlet returns a CIM session object that can be used by all other CIM cmdlets.
Examples

Example 1: Create a CIM session with default options


This example creates a local CIM session with default options. If ComputerName is not
specified,
New-CimSession creates a DCOM session to the local computer.

PowerShell

New-CimSession

Example 2: Create a CIM session to a specific computer


This example creates a CIM session to the computer specified by ComputerName.
By
default, New-CimSession creates a WSMan session when ComputerName is specified.

PowerShell

New-CimSession -ComputerName Server01

Example 3: Create a CIM session to multiple computers


This example creates a CIM session to each of the computers specified by
ComputerName, in the
comma separated list.

PowerShell

New-CimSession -ComputerName Server01,Server02,Server03

Example 4: Create a CIM session with a friendly name


This example creates a remote CIM session to each of the computers specified by
ComputerName, in
the comma separated list, and assigns a friendly name to the new
sessions, by specifying Name.

PowerShell

New-CimSession -ComputerName Server01,Server02 -Name FileServers

Get-CimSession -Name File*


You can use the friendly name of a CIM session to refer to the session in other CIM
cmdlets, for
example, Get-CimSession.

Example 5: Create a CIM session to a computer using a


PSCredential object
This example creates a CIM session to the computer specified by ComputerName, using
the
PSCredential object specified by Credential, and the authentication type specified
by
Authentication.

PowerShell

New-CimSession -ComputerName Server01 -Credential $cred -Authentication


Negotiate

You can create a PSCredential object using the


Get-Credential cmdlet.

Example 6: Create a CIM session to a computer using a


specific port
This example creates a CIM session to the computer specified by ComputerName using
the TCP port
specified by Port.

PowerShell

New-CimSession -ComputerName Server01 -Port 1234

Example 7: Create a CIM session using DCOM


This example creates a CIM session using the Distributed COM (DCOM) protocol instead
of WSMan.

PowerShell

$SessionOption = New-CimSessionOption -Protocol DCOM

New-CimSession -ComputerName Server1 -SessionOption $SessionOption

Parameters
-Authentication
Specifies the authentication type used for the user's credentials. The acceptable
values for this
parameter are:

Default
Digest
Negotiate
Basic
Kerberos
NtlmDomain
CredSsp

You cannot use the NtlmDomain authentication type for connection to the local
computer. CredSSP
authentication is available only in Windows Vista, Windows
Server 2008, and later versions of
Windows.

U Caution

Credential Security Service Provider (CredSSP) authentication 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.

Type: PasswordAuthenticationMechanism

Accepted values: Default, Digest, Negotiate, Basic, Kerberos, NtlmDomain,


CredSsp

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-CertificateThumbprint

Specifies the digital public key certificate (X.509) 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 cmdlets in the
PowerShell
Certificate Provider.

For more information, see about_Certificate_Provider.

Type: String

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-ComputerName

Specifies the name of the computer to which to create the CIM session. Specify
either a single
computer name, or multiple computer names separated by a comma.

If ComputerName is not specified, a CIM session to the local computer is created.


You can
specify the value for computer name in one of the following formats:

One or more NetBIOS names


One or more IP addresses
One or more fully qualified domain names.

If the computer is in a different domain than the user, you must specify the fully
qualified domain
name.

Type: String[]

Aliases: CN, ServerName

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Credential

Specifies a user account that has permission to perform this action. If Credential is
not
specified, the current user account is used.

Specify the value for Credential using one of the following formats:
A user name: "User01"
A domain name and a user name: "Domain01\User01"
A user principal name: "User@Domain.com"
A PSCredential object, such as one returned by the Get-Credential cmdlet.

When you type a user name, you are prompted for a password.

Type: PSCredential

Position: 2

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Name

Specifies a friendly name for the CIM session.

You can use the name to refer to the CIM session when using other cmdlets, such as
the Get-CimSession cmdlet.
The name is not required to be unique to the computer
or the current session.

Type: String

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-OperationTimeoutSec

Duration for which the cmdlet waits for a response from the server.

By default, the value of this parameter is 0, which means that the cmdlet uses the
default timeout value for the server.

If the OperationTimeoutSec parameter is set to a value less than the robust


connection retry timeout of 3 minutes, network failures that last more than the value
of the OperationTimeoutSec parameter are not recoverable, because the operation
on the server times out before the client can reconnect.
Type: UInt32

Aliases: OT

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Port

Specifies the network port on the remote computer that is used for this connection.
To connect to a remote computer, the remote computer must be listening on the
port that the connection uses.
The default ports are 5985 (the WinRM port for HTTP)
and 5986 (the WinRM port for HTTPS).

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:

winrm delete winrm/config/listener?Address=*+Transport=HTTP

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.

Type: UInt32

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-SessionOption

Sets advanced options for the new CIM session. Enter the name of a
CimSessionOption object
created using the New-CimSessionOption cmdlet.
Type: CimSessionOptions

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-SkipTestConnection

By default, the New-CimSession cmdlet establishes a connection with a remote WS-


Management
endpoint for two reasons: to verify that the remote server is listening
on the port number that is
specified using the Port parameter, and to verify the
specified account credentials. The
verification is accomplished using a standard WS-
Identity operation. You can add the
SkipTestConnection switch parameter if the
remote WS-Management endpoint cannot use WS-Identify,
or to reduce some data
transmission time.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
CimSession

This cmdlet returns a CIM session object.

Related Links
Get-ChildItem
Get-Credential
Get-Item
Get-CimSession
Remove-CimSession
New-CimSessionOption
about_CimSession
New-CimSessionOption
Reference
Module: CimCmdlets

Specifies advanced options for the New-CimSession cmdlet.

Syntax
PowerShell

New-CimSessionOption

[-Protocol] <ProtocolType>

[-UICulture <CultureInfo>]

[-Culture <CultureInfo>]

[<CommonParameters>]

PowerShell

New-CimSessionOption

[-NoEncryption]

[-SkipCACheck]

[-SkipCNCheck]

[-SkipRevocationCheck]

[-EncodePortInServicePrincipalName]

[-Encoding <PacketEncoding>]

[-HttpPrefix <Uri>]

[-MaxEnvelopeSizeKB <UInt32>]

[-ProxyAuthentication <PasswordAuthenticationMechanism>]

[-ProxyCertificateThumbprint <String>]

[-ProxyCredential <PSCredential>]

[-ProxyType <ProxyType>]

[-UseSsl]

[-UICulture <CultureInfo>]

[-Culture <CultureInfo>]

[<CommonParameters>]

PowerShell

New-CimSessionOption

[-Impersonation <ImpersonationType>]

[-PacketIntegrity]

[-PacketPrivacy]

[-UICulture <CultureInfo>]

[-Culture <CultureInfo>]

[<CommonParameters>]
Description
The New-CimSessionOption cmdlet creates an instance of a CIM session options object.
You use a CIM
session options object as input to the New-CimSession cmdlet to specify
the options for a CIM
session.

This cmdlet has two parameter sets, one for WsMan options and one for Distributed
Component Object
Model (DCOM) options. Depending on which parameters you use,
the cmdlet returns either an instance
of DCOM session options or returns WsMan
session options.

Examples

Example 1: Create a CIM session options object for DCOM


This example creates a CIM session options object for the DCOM protocol and stores it
in a variable
named $so . The contents of the variable are then passed to the New-
CimSession cmdlet.
New-CimSession then creates a new CIM session with the remote

server named Server01, using the


options defined in the variable.

PowerShell

$so = New-CimSessionOption -Protocol DCOM

New-CimSession -ComputerName Server01 -SessionOption $so

Example 2: Create a CIM session options object for


WsMan
This example creates a CIM session options object for the WsMan protocol. The object
contains
configuration for the authentication mode of Kerberos specified by the
ProxyAuthentication
parameter, the credentials specified by the ProxyCredential
parameter, and specifies that the
command is to skip the CA check, skip the CN check,
and use SSL.

PowerShell

New-CimSessionOption -ProxyAuthentication Kerberos -ProxyCredential $cred -


SkipCACheck -SkipCNCheck -UseSsl
Example 3: Create a CIM session options object with the
culture specified
PowerShell

New-CimSessionOption -Culture Fr-Fr -Protocol Wsman

This example specifies the culture that is used for the CIM session. By default, the culture
of the
client is used when performing operations. However, the default culture can be
overridden using the
Culture parameter.

Parameters
-Culture

Specifies the user interface culture to use for the CIM session. Specify the value for
this
parameter using one of the following formats:

A culture name in <languagecode2>-<country/regioncode2> format such as "EN-


US".
A variable that contains a CultureInfo object.
A command that gets a CultureInfo object, such as Get-Culture

Type: CultureInfo

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-EncodePortInServicePrincipalName

Indicates that the Kerberos connection is connecting to a service whose service


principal name (SPN)
includes the service port number. This type of connection is not
common.

Type: SwitchParameter

Position: Named

Default value: None


Accept pipeline input: True

Accept wildcard characters: False

-Encoding

Specifies the encoding used for the WsMan protocol. The acceptable values for this
parameter are:
Default, Utf8, or Utf16.

Type: PacketEncoding

Accepted values: Default, Utf8, Utf16

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-HttpPrefix

Specifies the part of the HTTP URL after the computer name and port number.
Changing this is not
common. By default, the value of this parameter is /wsman.

Type: Uri

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Impersonation

Creates a DCOM session to Windows Management Instrumentation (WMI) using


impersonation.

Valid values for this parameter are:

Default: DCOM can choose the impersonation level using its normal security
negotiation algorithm.
None: The client is anonymous to the server. The server process can
impersonate the client, but
the impersonation token does not contain any
information and cannot be used.
Identify: Allows objects to query the credentials of the caller.
Impersonate: Allows objects to use the credentials of the caller.
Delegate: Allows objects to permit other objects to use the credentials of the
caller.

If Impersonation is not specified, the New-CimSession cmdlet uses the value of


Impersonate.

Type: ImpersonationType

Accepted values: Default, None, Identify, Impersonate, Delegate

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-MaxEnvelopeSizeKB

Specifies the size limit of WsMan XML messages for either direction.

Type: UInt32

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-NoEncryption

Specifies that data encryption is turned off.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-PacketIntegrity

Specifies that the DCOM session created to WMI uses the Component Object Model
(COM)
PacketIntegrity functionality. By default, all CIM sessions created using DCOM
have the
PacketIntegrity parameter set to True.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-PacketPrivacy

Creates a DCOM session to WMI using the COM PacketPrivacy. By default, all CIM
sessions created
using DCOM have the PacketPrivacy parameter set to true.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Protocol

Specifies the protocol to use. The acceptable values for this parameter are: DCOM,
Default,
or Wsman.

Type: ProtocolType

Accepted values: Dcom, Default, Wsman

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False


-ProxyAuthentication

Specifies the authentication method to use for proxy resolution. The acceptable
values for this
parameter are: Default, Digest, Negotiate, Basic, Kerberos,
NtlmDomain, or
CredSsp.

Type: PasswordAuthenticationMechanism

Accepted values: Default, Digest, Negotiate, Basic, Kerberos, NtlmDomain,


CredSsp

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-ProxyCertificateThumbprint

Specifies the (x.509) digital public key certificate of a user account for proxy
authentication.
Enter the certificate thumbprint of the certificate. Certificates are
used in client
certificate-based authentication. They can only be mapped 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


PowerShell
Cert: drive.

Type: String

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-ProxyCredential

Specifies the credentials to use for proxy authentication. Enter one of the following:

A variable that contains a PSCredential object.


A command that gets a PSCredential object, such as Get-Credential

If this option is not set, then you cannot specify any credentials.
Type: PSCredential

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ProxyType

Specifies the host name resolution mechanism to use. The acceptable values for this
parameter are:
None, WinHttp, Auto, or InternetExplorer.

The default value of this parameter is InternetExplorer.

Type: ProxyType

Accepted values: None, WinHttp, Auto, InternetExplorer

Position: Named

Default value: InternetExplorer

Accept pipeline input: True

Accept wildcard characters: False

-SkipCACheck

Indicates that when connecting over HTTPS, the client does not validate that the
server certificate
is signed by a trusted certification authority (CA).

Use this parameter only when the remote computer is trusted using another
mechanism, such as when
the remote computer is part of a network that is physically
secure and isolated, or when the remote
computer is listed as a trusted host in a
WinRM configuration.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False


-SkipCNCheck

Indicates that the certificate common name (CN) of the server does not need to
match the hostname of
the server. Use this parameter for remote operations only
with trusted computers that use the HTTPS
protocol.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-SkipRevocationCheck

Indicates that the revocation check for server certificates is skipped. Use this
parameter only for
trusted computers.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-UICulture

Specifies the user interface culture to use for the CIM session. Specify the value for
this
parameter using one of the following formats:

A culture name in <languagecode2>-<country/regioncode2> format such as "EN-


US".
A variable that contains a CultureInfo object.
A command that gets a CultureInfo object, such as Get-Culture .

Type: CultureInfo

Position: Named

Default value: None

Accept pipeline input: True


Accept wildcard characters: False

-UseSsl

Indicates that SSL should be used to establish a connection to the remote computer.
By default, SSL
is not used. WsMan encrypts all content that is transmitted over the
network, even when using HTTP.

This parameter lets you specify the additional protection of HTTPS instead of HTTP. If
SSL is not
available on the port used for the connection and you specify this
parameter, then the command
fails.

It is recommended that you use this parameter only when the PacketPrivacy
parameter is not
specified.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
CimSessionOptions

This cmdlet returns an object that contains CIM session options information.

Related Links
Get-ChildItem
Get-Credential
Get-Culture
Get-Item
New-CimSession
Register-CimIndicationEvent
Reference
Module: CimCmdlets

Subscribes to indications using a filter expression or a query expression.

Syntax
PowerShell

Register-CimIndicationEvent

[-Namespace <String>]

[-ClassName] <String>

[-OperationTimeoutSec <UInt32>]

[-ComputerName <String>]

[[-SourceIdentifier] <String>]

[[-Action] <ScriptBlock>]
[-MessageData <PSObject>]
[-SupportEvent]

[-Forward]

[-MaxTriggerCount <Int32>]

[<CommonParameters>]

PowerShell

Register-CimIndicationEvent

[-Namespace <String>]

[-ClassName] <String>

[-OperationTimeoutSec <UInt32>]

-CimSession <CimSession>

[[-SourceIdentifier] <String>]

[[-Action] <ScriptBlock>]
[-MessageData <PSObject>]
[-SupportEvent]

[-Forward]

[-MaxTriggerCount <Int32>]

[<CommonParameters>]

PowerShell

Register-CimIndicationEvent

[-Namespace <String>]

[-Query] <String>

[-QueryDialect <String>]

[-OperationTimeoutSec <UInt32>]

-CimSession <CimSession>

[[-SourceIdentifier] <String>]

[[-Action] <ScriptBlock>]
[-MessageData <PSObject>]
[-SupportEvent]

[-Forward]

[-MaxTriggerCount <Int32>]

[<CommonParameters>]

PowerShell

Register-CimIndicationEvent

[-Namespace <String>]

[-Query] <String>

[-QueryDialect <String>]

[-OperationTimeoutSec <UInt32>]

[-ComputerName <String>]

[[-SourceIdentifier] <String>]

[[-Action] <ScriptBlock>]
[-MessageData <PSObject>]
[-SupportEvent]

[-Forward]

[-MaxTriggerCount <Int32>]

[<CommonParameters>]

Description
The Register-CimIndicationEvent cmdlet subscribes to indications using an indication
class name or
a query expression. Use the SourceIdentifier parameter give a name to
the subscription.

This cmdlet returns an EventSubscription object. You can use this object to cancel the
subscription.

Examples

Example 1: Register the events generated by a class


This example subscribes to the events generated by the class named
Win32_ProcessStartTrace. This
class raises an event whenever a process starts.

PowerShell

Register-CimIndicationEvent -ClassName 'Win32_ProcessStartTrace' -


SourceIdentifier "ProcessStarted"
Get-Event -SourceIdentifier "ProcessStarted"
The Get-Event cmdlet gets the events with ProcessStarted subscription. For more
information,
see Get-Event.

7 Note

For this example, you must run PowerShell as an Administrator.

Example 2: Register the events using a query


This example uses a query to subscribe to an event generated whenever there is a
change in
the instance of a class named Win32_LocalTime.

PowerShell

$query = "SELECT * FROM CIM_InstModification WHERE TargetInstance ISA


'Win32_LocalTime'"

Register-CimIndicationEvent -Query $query -SourceIdentifier "Timer"

Example 3: Run a script when the event arrives


This example shows how to use an action in response to an event. The variable $action
holds the
script block for Action, which uses the $event variable to access the event
received from CIM.

PowerShell

$action = {

$name = $event.SourceEventArgs.NewEvent.ProcessName

$id = $event.SourceEventArgs.NewEvent.ProcessId

Write-Host -Object "New Process Started : Name = $name

ID = $id"

Register-CimIndicationEvent -ClassName 'Win32_ProcessStartTrace' -


SourceIdentifier "ProcessStarted" -Action $action

For more information, see Win32_ProcessStartTrace.

Example 4: Register the events on a remote computer


This example subscribes to events on a remote computer named Server01. Events
received from the
CIM server are stored in the event queue in the current PowerShell
session and then runs a local
Get-Event to retrieve the events.

PowerShell

Register-CimIndicationEvent -ClassName 'Win32_ProcessStartTrace' -


SourceIdentifier "ProcessStarted" -ComputerName Server01

Get-Event -SourceIdentifier "ProcessStarted"

Parameters
-Action

Specifies the commands that handle the events. The commands specified by this
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 script block specified with Action 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.

Type: ScriptBlock

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-CimSession

Runs the command using the specified CIM session. Enter a variable that contains
the CIM session, or
a command that creates or gets the CIM session, such as the
New-CimSession or Get-CimSession
cmdlets. For more information, see

about_CimSession.

Type: CimSession

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-ClassName

Specifies the indication class to which you are subscribing. You can use tab
completion to browse
the list of classes, because PowerShell gets a list of classes
from the local WMI server to provide
a list of class names.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ComputerName

Specifies the name of the computer on which you want to run the CIM operation.
You can specify a
fully qualified domain name (FQDN), a NetBIOS name, or an IP
address.

If you specify this parameter, the cmdlet creates a temporary session to the specified
computer
using the WsMan protocol. If you do not specify this parameter, the
cmdlet performs operation on the
local system using Component Object Model
(COM).

If multiple operations are being performed on the same computer, connect using a
CIM session for
better performance.

Type: String

Aliases: CN, ServerName

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Forward
Indicates that events for the subscription are forwarded 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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-MaxTriggerCount

Parameter to indicate that the subscriber should be auto-unregistered after being


triggered for
specified times. If the value is equal or less than zero, there is no limit
on the number of times
the event can be triggered without being unregistered.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-MessageData

Specifies any additional data to associate with this event subscription. The value of
this parameter
appears in the MessageData property of all the events associated
with this subscription.

Type: PSObject

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Namespace
Specifies the namespace for the CIM operation. The default namespace is
root/cimv2. You can use
tab completion to browse the list of namespaces, because
PowerShell gets a list of namespaces from
the local WMI server to provide the list of
namespaces.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-OperationTimeoutSec

Specifies the amount of time that the cmdlet waits for a response from the
computer. By default, the
value of this parameter is 0, which means that the cmdlet
uses the default timeout value for the
server.

If the OperationTimeoutSec parameter is set to a value less than the robust


connection retry
timeout of 3 minutes, network failures that last more than the value
of the OperationTimeoutSec
parameter are not recoverable, because the operation
on the server times out before the client can
reconnect.

Type: UInt32

Aliases: OT

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Query

Specifies a query to run on the CIM server. If the value specified contains double
quotes " ,
single quotes ' , or a backslash \ , you must escape those characters by
prefixing them with the
backslash character. If the value specified uses the WQL LIKE
operator, then you must escape the
following characters by enclosing them in
square brackets [] : percent % , underscore _ , or
opening square bracket [ .
Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-QueryDialect

Specifies the query language used for the Query parameter. The acceptable values
for this
parameter are: WQL or CQL. The default value is WQL.

Type: String

Position: Named

Default value: WQL

Accept pipeline input: False

Accept wildcard characters: False

-SourceIdentifier

Specifies a name for the subscription. The name that you specify must be unique in
the current
session. The default value is a GUID that PowerShell assigns. This value
appears in the value of the
SourceIdentifier property of the subscriber object and of
all event objects associated with this
subscription.

Type: String

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SupportEvent

Indicates that the event subscription is hidden. Use this parameter when the current
subscription is
part of a more complex event registration mechanism and it should
not be discovered independently.
Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
Object

This cmdlet returns an EventSubscription object.

Related Links
Get-Event
Remove-Event
Unregister-Event
Write-Host
Get-CimSession
New-CimSession
Remove-CimInstance
Reference
Module: CimCmdlets

Removes a CIM instance from a computer.

Syntax
PowerShell

Remove-CimInstance

[-ResourceUri <Uri>]

[-ComputerName <String[]>]

[-OperationTimeoutSec <UInt32>]

[-InputObject] <CimInstance>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-CimInstance

-CimSession <CimSession[]>

[-ResourceUri <Uri>]

[-OperationTimeoutSec <UInt32>]

[-InputObject] <CimInstance>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-CimInstance

-CimSession <CimSession[]>

[[-Namespace] <String>]

[-OperationTimeoutSec <UInt32>]

[-Query] <String>

[-QueryDialect <String>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell
Remove-CimInstance

[-ComputerName <String[]>]

[[-Namespace] <String>]

[-OperationTimeoutSec <UInt32>]

[-Query] <String>

[-QueryDialect <String>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
This cmdlet removes a CIM instance from a CIM server. You can specify the CIM instance
to remove by
using either a CIM instance object retrieved by the Get-CimInstance
cmdlet, or by specifying a
query.

If the InputObject parameter is not specified, the cmdlet works in one of the following
ways:

If neither the ComputerName parameter nor the CimSession parameter is


specified, then this
cmdlet works on local Windows Management Instrumentation
(WMI) using a Component Object Model
(COM) session.
If either the ComputerName parameter or the CimSession parameter is specified,
then this
cmdlet works against the CIM server specified by either the
ComputerName parameter or the
CimSession parameter.

Examples

Example 1: Remove the CIM instance


This example use the Query parameter to remove CIM instances from the class named
Win32_Environment that start with the character string testvar .

PowerShell

Remove-CimInstance -Query 'Select * from Win32_Environment where name LIKE


"testvar%"'

Example 2: Remove the CIM instance using CIM instance


object
This example retrieves the CIM instance objects filtered by the Query parameter and
stores them
in variable named $var using the Get-CimInstance cmdlet. The contents of
the variable are then
passed to the Remove-CimInstance cmdlet, which removes the CIM
instances.

PowerShell

notepad.exe

$var = Get-CimInstance -Query 'Select * from Win32_Process where name LIKE


"notepad%"'

Remove-CimInstance -InputObject $var

Parameters
-CimSession

Runs the command using the specified CIM session. Enter a variable that contains
the CIM session, or
a command that creates or gets the CIM session, such as the
New-CimSession or Get-CimSession
cmdlets. For more information, see
about_CimSession.

Type: CimSession[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-ComputerName

Specifies the name of the computer on which you want to run the CIM operation.
You can specify a
fully qualified domain name (FQDN) or a NetBIOS name.

If you specify this parameter, the cmdlet creates a temporary session to the specified
computer
using the WsMan protocol.

If you do not specify this parameter, the cmdlet performs the operation on the local
computer using
Component Object Model (COM).

If multiple operations are being performed on the same computer, connecting using
a CIM session
gives better performance.
Type: String[]

Aliases: CN, ServerName

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies a CIM instance object to be removed from the CIM server. The object
passed to the cmdlet
is not changed, only the instance in the CIM server is removed.

The InputObject parameter doesn't enumerate over collections. If a collection is


passed, an
error is thrown. When working with collections, pipe the input to
enumerate the values.

Type: CimInstance

Aliases: CimInstance

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False


-Namespace

Specifies the namespace for the CIM operation. The default namespace is
root/cimv2 . You can use
tab completion to browse the list of namespaces, because

PowerShell gets a list of namespaces from


the local WMI server to provide the list of
namespaces.

Type: String

Position: 2

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-OperationTimeoutSec

Specifies the amount of time that the cmdlet waits for a response from the
computer. By default, the
value of this parameter is 0 , which means that the cmdlet
uses the default timeout value for the
server.

If the OperationTimeoutSec parameter is set to a value less than the robust


connection retry
timeout of 3 minutes, network failures that last more than the value
of the OperationTimeoutSec
parameter are not recoverable, because the operation
on the server times out before the client can
reconnect.

Type: UInt32

Aliases: OT

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Query

Specifies a query to run on the CIM server. You can specify the query dialect using
the
QueryDialect parameter.

If the value specified contains double quotes ( " ), single quotes ( ' ), or a backslash
( \ ), you
must escape those characters by prefixing them with the backslash ( \ )
character. If the value
specified uses the WQL LIKE operator, then you must escape
the following characters by enclosing
them in square brackets ( [] ): percent ( % ),
underscore ( _ ), or opening square bracket ( [ ).

Type: String

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-QueryDialect

Specifies the query language used for the Query parameter. The acceptable values
for this parameter
are: WQL or CQL . The default value is WQL .

Type: String

Position: Named

Default value: WQL

Accept pipeline input: True

Accept wildcard characters: False

-ResourceUri

Specifies the resource 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://intel.com/wbem/wscim/1/amt-schema/1/AMT_GeneralSettings

By default, if you do not specify this parameter, the DMTF standard resource URI
http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/ is used and the class name is
appended to it.

ResourceURI can only be used with CIM sessions created using the WSMan protocol,
or when specifying
the ComputerName parameter, which creates a CIM session
using WSMan. If you specify this parameter
without specifying the ComputerName
parameter, or if you specify a CIM session created using DCOM
protocol, you get an
error, because the DCOM protocol does not support the ResourceURI
parameter.

If both the ResourceUri parameter and the Filter parameter are specified, the Filter
parameter is ignored.

Type: Uri

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

This cmdlet returns no output.


Related Links
New-CimInstance
Get-CimInstance
Set-CimInstance
Remove-CimSession
Reference
Module: CimCmdlets

Removes one or more CIM sessions.

Syntax
PowerShell

Remove-CimSession

[-CimSession] <CimSession[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-CimSession

[-ComputerName] <String[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-CimSession

[-Id] <UInt32[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-CimSession

-InstanceId <Guid[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-CimSession

-Name <String[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Remove-CimSession cmdlet removes one or more CIM session objects from the local
PowerShell
session.

Examples

Example 1: Remove all the CIM sessions


This example retrieves all the available CIM sessions on the local computer using the
Get-CimSession cmdlet, and then removes them using the Remove-CimSession .

PowerShell

Get-CimSession | Remove-CimSession

Example 2: Remove a specific CIM session


This example removes the CIM session that has an Id value of 5.

PowerShell

Remove-CimSession -Id 5

Example 3: Show the list of CIM sessions to remove by


using the WhatIf parameter
This example uses the common parameter WhatIf to specify that the removal should
not be done,
but only output what would happen if it were done.

PowerShell

Remove-CimSession -Name a* -WhatIf


Parameters
-CimSession

Specifies the session objects of the CIM sessions to close.

Enter a variable that contains the CIM session, or a command that creates or gets the
CIM session,
such as the New-CimSession or Get-CimSession cmdlets.
For more
information, see
about_CimSessions.

Type: CimSession[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-ComputerName

Specifies an array of names of computers. Removes the sessions that connect to the
specified
computers. You can specify a fully qualified domain name (FQDN) or a
NetBIOS name.

Type: String[]

Aliases: CN, ServerName

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named
Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Id

Specifies the ID of the CIM session to remove. Specify 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 CIM session in the current PowerShell session.

For more information about the range operator, see about_Operators.

Type: UInt32[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-InstanceId

Specifies the instance ID of the CIM session to remove. InstanceId is a Globally


Unique
Identifier (GUID) that uniquely identifies a CIM session. The InstanceId is
unique, even when
you have multiple sessions running in PowerShell.

The InstanceId is stored in the InstanceId property of the object that represents a
CIM session.

Type: Guid[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies the friendly name of the CIM session to remove. You can use wildcard
characters with this
parameter.
Type: String[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
Object

This cmdlet returns an object that contains CIM session information.

Related Links
Get-CimSession
New-CimSession
about_CimSession
Set-CimInstance
Reference
Module: CimCmdlets

Modifies a CIM instance on a CIM server by calling the ModifyInstance method of the
CIM class.

Syntax
PowerShell

Set-CimInstance

[-ComputerName <String[]>]

[-ResourceUri <Uri>]

[-OperationTimeoutSec <UInt32>]

[-InputObject] <CimInstance>

[-Property <IDictionary>]

[-PassThru]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Set-CimInstance

-CimSession <CimSession[]>

[-ResourceUri <Uri>]

[-OperationTimeoutSec <UInt32>]

[-InputObject] <CimInstance>

[-Property <IDictionary>]

[-PassThru]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Set-CimInstance

-CimSession <CimSession[]>

[-Namespace <String>]

[-OperationTimeoutSec <UInt32>]

[-Query] <String>

[-QueryDialect <String>]

-Property <IDictionary>

[-PassThru]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Set-CimInstance

[-ComputerName <String[]>]

[-Namespace <String>]

[-OperationTimeoutSec <UInt32>]

[-Query] <String>

[-QueryDialect <String>]

-Property <IDictionary>

[-PassThru]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
This cmdlet modifies a CIM instance on a CIM server.

If the InputObject parameter is not specified, the cmdlet works in one of the following
ways:

If neither the ComputerName parameter nor the CimSession parameter is


specified, then this
cmdlet works on local Windows Management Instrumentation
(WMI) using a Component Object Model
(COM) session.
If either the ComputerName parameter or the CimSession parameter is specified,
then this
cmdlet works against the CIM server specified by either the
ComputerName parameter or the
CimSession parameter.

If the InputObject parameter is specified, the cmdlet works in one of the following ways:

If neither the ComputerName parameter nor the CimSession parameter is


specified, then this
cmdlet uses the CIM session or computer name from the input
object.
If the either the ComputerName parameter or the CimSession parameter is
specified, then
this cmdlet uses the either the CimSession parameter value or
ComputerName parameter
value. This is not very common.

Examples

Example 1: Set the CIM instance


This example sets the value of the VariableValue property to abcd using the Query
parameter. You can modify instances matching a Windows Management
Instrumentation Query Language
(WQL) query.

PowerShell

Set-CimInstance -Query 'Select * from Win32_Environment where name LIKE


"testvar%"' -Property @{VariableValue="abcd"}

Example 2: Set the CIM instance property using pipeline


This example retrieves the CIM instance object filtered by the Query parameter using
the
Get-CimInstance cmdlet. The Set-CimInstance cmdlet modifies the value of
VariableValue
property to abcd.

PowerShell

Get-CimInstance -Query 'Select * from Win32_Environment where name LIKE


"testvar%"' |

Set-CimInstance -Property @{VariableValue="abcd"}

Example 3: Set the CIM instance property using input


object
PowerShell

$x = Get-CimInstance -Query 'Select * from Win32_Environment where


Name="testvar"'

Set-CimInstance -InputObject $x -Property @{VariableValue="somevalue"} -


PassThru

This example retrieves the CIM instance objects filtered by the Query parameter in to a
variable
$x using Get-CimInstance , and then passes the contents of the variable to the
Set-CimInstance
cmdlet. Set-CimInstance then modifies the VariableValue property to

somevalue. Because the


Passthru parameter is used, This example returns a modified
CIM instance object.

Example 4: Set the CIM instance property


This example retrieves the CIM instance object that is specified in the Query parameter
into a
variable $x using the Get-CimInstance cmdlet, and changes the VariableValue
property value
of the object to change. The CIM instance object is then saved using the
Set-CimInstance cmdlet.
Because the Passthru parameter is used, This example returns
a modified CIM instance object.

PowerShell

$x = Get-CimInstance -Query 'Select * from Win32_Environment where


name="testvar"'

$x.VariableValue = "Change"

Set-CimInstance -CimInstance $x -PassThru

Example 5: Show the list of CIM instances to modify using


WhatIf
This example uses the common parameter WhatIf to specify that the modification
should not be
done, but only output what would happen if it were done.

PowerShell

Set-CimInstance -Query 'Select * from Win32_Environment where name LIKE


"testvar%"' -Property @{VariableValue="abcd"} -WhatIf

Example 6: Set the CIM instance after confirmation from


the user
This example uses the common parameter Confirm to specify that the modification
should be done
only after confirmation from the user.

PowerShell

Set-CimInstance -Query 'Select * from Win32_Environment where name LIKE


"testvar%"' -Property @{VariableValue="abcd"} -Confirm

Example 7: Set the created CIM instance


This example creates a CIM instance with the specified properties using the New-
CimInstance
cmdlet, and retrieves its contents in to a variable $x . The variable is then

passed to the
Set-CimInstance cmdlet, which modifies the value of VariableValue
property to somevalue.
Because the Passthru parameter is used, This example returns a
modified CIM instance object.
PowerShell

$x = New-CimInstance -ClassName Win32_Environment -Property


@{Name="testvar";UserName="domain\user"} -Key Name,UserName -ClientOnly

Set-CimInstance -CimInstance $x -Property @{VariableValue="somevalue"} -


PassThru

Parameters
-CimSession

Runs the cmdlets on a remote computer. Enter a computer name or a session object,
such as the output
of a New-CimSession or Get-CimSession cmdlet.

Type: CimSession[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-ComputerName

Specifies the name of the computer on which you want to run the CIM operation.
You can specify a
fully qualified domain name (FQDN) or a NetBIOS name.

If you do not specify this parameter, the cmdlet performs the operation on the local
computer using
Component Object Model (COM).

If you specify this parameter, the cmdlet creates a temporary session to the specified
computer
using the WsMan protocol.

If multiple operations are being performed on the same computer, connecting using
a CIM session
gives better performance.

Type: String[]

Aliases: CN, ServerName

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies a CIM instance object to use as input.

The InputObject parameter doesn't enumerate over collections. If a collection is


passed, an
error is thrown. When working with collections, pipe the input to
enumerate the values.

Type: CimInstance

Aliases: CimInstance

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Namespace

Specifies the namespace for the CIM operation. The default namespace is
root/cimv2. You can use tab
completion to browse the list of namespaces, because
PowerShell gets a list of namespaces from the
local WMI server to provide the list of
namespaces.

Type: String
Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-OperationTimeoutSec

Specifies the amount of time that the cmdlet waits for a response from the
computer. By default, the
value of this parameter is 0, which means that the cmdlet
uses the default timeout value for the
server.

If the OperationTimeoutSec parameter is set to a value less than the robust


connection retry
timeout of 3 minutes, network failures that last more than the value
of the OperationTimeoutSec
parameter are not recoverable, because the operation
on the server times out before the client can
reconnect.

Type: UInt32

Aliases: OT

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-PassThru

Returns an object representing the item with which you are working. By default, this
cmdlet does not
generate any output.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Property
Specifies the properties of the CIM instance as a hash table (using name-value pairs).
Only the
properties specified using this parameter are changed. Other properties of
the CIM instance are not
changed.

Type: IDictionary

Aliases: Arguments

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Query

Specifies a query to run on the CIM server to retrieve CIM instances on which to run
the cmdlet. You
can specify the query dialect using the QueryDialect parameter.

If the value specified contains double quotes ( " ), single quotes ( ' ), or a backslash
( \ ), you
must escape those characters by prefixing them with the backslash ( \ )
character. If the value
specified uses the WQL LIKE operator, then you must escape
the following characters by enclosing
them in square brackets ( [] ): percent ( % ),
underscore ( _ ), or opening square bracket ( [ ).

Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-QueryDialect

Specifies the query language used for the Query parameter. The acceptable values
for this parameter
are: WQL or CQL. The default value is WQL.

Type: String

Position: Named

Default value: None


Accept pipeline input: True

Accept wildcard characters: False

-ResourceUri

Specifies the resource 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://intel.com/wbem/wscim/1/amt-schema/1/AMT_GeneralSettings

By default, if you do not specify this parameter, the DMTF standard resource URI
http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/ is used and the class name is
appended to it.

ResourceURI can only be used with CIM sessions created using the WSMan protocol,
or when specifying
the ComputerName parameter, which creates a CIM session
using WSMan. If you specify this parameter
without specifying the ComputerName
parameter, or if you specify a CIM session created using DCOM
protocol, you will get
an error, because the DCOM protocol does not support the ResourceURI
parameter.

If both the ResourceUri parameter and the Filter parameter are specified, the Filter
parameter is ignored.

Type: Uri

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named
Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
CimInstance

Outputs
None

By default, this cmdlet returns no output.

CimInstance

When you use the Passthru parameter, this cmdlet returns the modified CIM instance
object.

Related Links
Get-CimInstance
New-CimInstance
Remove-CimInstance
ISE
Reference

This section contains the help topics for the cmdlets that are installed with the Windows
PowerShell
Integrated Scripting Environment (ISE) module. The Windows PowerShell ISE
module contains cmdlets
that add features to Windows PowerShell ISE.

ISE
Get-IseSnippet Gets snippets that the user created.

Import-IseSnippet Imports ISE snippets into the current session

New-IseSnippet Creates a Windows PowerShell ISE code snippet.


Get-IseSnippet
Reference
Module: ISE

Gets snippets that the user created.

Syntax
PowerShell

Get-IseSnippet []

Description
The Get-IseSnippet cmdlet gets the PS1XML files that contain reusable text snippets
that the user
created. It works only in Windows PowerShell Integrated Scripting
Environment (ISE).

When you use the New-IseSnippet cmdlet to create a snippet, New-IseSnippet creates a
<SnippetTitle>.Snippets.ps1xml file in the $HOME\Documents\WindowsPowerShell\Snippets

directory.
Get-IseSnippet gets the snippet files in the Snippets directory.

This cmdlet does not get built-in snippets or snippets that are imported from modules
through the
Import-IseSnippet cmdlet.

This cmdlet was introduced in Windows PowerShell 3.0.

Examples

Example 1: Get all user-defined snippets


This example gets all user-define snippets in the Snippets directory.

PowerShell

Get-IseSnippet
Example 2: Copy all user-defined snippets from remote
computers to a shared directory
This example copies all of the user-created snippets from a group of remote computers
to a shared Snippets directory.

PowerShell

Invoke-Command -Computer (Get-Content Servers.txt) {Get-IseSnippet | Copy-


Item -Destination \\Server01\Share01\Snippets}

Invoke-Command runs Get-IseSnippet on the computers in the Servers.txt file. A

pipeline
operator ( | ) sends the snippet files to the Copy-Item cmdlet, which copies
them to the directory
that is specified by the Destination parameter.

Example 3: Display the title and text of each snippet on a


local computer
This example uses the Get-IseSnippet and Select-Xml cmdlets to display the title and
text of each
snippet on the local computer.

PowerShell

#Parse-Snippet Function

function Parse-Snippet {

$SnippetFiles = Get-IseSnippet

$SnippetNamespace =
@{x="http://schemas.microsoft.com/PowerShell/Snippets"}

foreach ($SnippetFile in $SnippetFiles) {

Write-Host ""

$Title = Select-Xml -Path $SnippetFile.FullName -Namespace


$SnippetNamespace -XPath "//x:Title" |

ForEach-Object {$_.Node.InnerXML}

$Text = Select-Xml -Path $SnippetFile.FullName -Namespace


$SnippetNamespace -XPath "//x:Script" |

ForEach-Object {$_.Node.InnerText}

Write-Host "Title: $Title"

Write-Host "Text: $Text"

Title: Mandatory

Text:

Param

[parameter(Mandatory=True)]

[String[]]

$<ParameterName>

Title: Copyright

Text: (c) Fabrikam, Inc. 2012

Example 4: Display the title and description of all snippets


in the session
This example displays the title and description of all snippets in the session, including
built-in snippets, user-defined snippets, and imported snippets.

PowerShell

$PSISE.CurrentPowerShellTab.Snippets | Format-Table DisplayTitle,


Description

The $PSISE variable represents the Windows PowerShell ISE host program. The
CurrentPowerShellTab property of the $PSISE variable represent the current session.
The
Snippets property represents snippets in the current session.

The $PSISE.CurrentPowerShellTab.Snippets command returns a


Microsoft.PowerShell.Host.ISE.ISESnippet object that represents a snippet, unlike the
Get-IseSnippet cmdlet. Get-IseSnippet returns a file object (System.Io.FileInfo) that
represents
a snippet file.

The Format-Table cmdlet displays the DisplayTitle and Description properties of the
snippets in a table.

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
FileInfo

This cmdlet returns a file object representing the snippet file.


Notes
The New-IseSnippet cmdlet stores new user-created snippets in unsigned .ps1xml
files. As such,
Windows PowerShell cannot add them to a session in which the
execution policy is AllSigned or
Restricted. In a Restricted or AllSigned session,
you can create, get, and import
unsigned user-created snippets, but you cannot
use them in the session.

To use unsigned user-created snippets that the Get-IseSnippet cmdlet returns,


change the
execution policy, and then restart Windows PowerShell ISE.

For more information about Windows PowerShell execution policies, see


about_Execution_Policies.

Related Links
New-IseSnippet
Import-IseSnippet
Import-IseSnippet
Reference
Module: ISE

Imports ISE snippets into the current session

Syntax
PowerShell

Import-IseSnippet

[-Path] <String>

[-Recurse]

[<CommonParameters>]

PowerShell

Import-IseSnippet

[-Recurse]

-Module <String>

[-ListAvailable]

[<CommonParameters>]

Description
The Import-IseSnippet cmdlet imports reusable text "snippets" from a module or a
directory into
the current session. The snippets are immediately available for use in
Windows PowerShell ISE. This
cmdlet works only in Windows PowerShell Integrated
Scripting Environment (ISE).

To view and use the imported snippets, from the Windows PowerShell ISE Edit menu,
click Start
Snippets or press Ctrl + J .

Imported snippets are available only in the current session. To import the snippets into
all Windows
PowerShell ISE sessions, add an Import-IseSnippet command to your
Windows PowerShell profile or
copy the snippet files to your local snippets directory
$HOME\Documents\WindowsPowershell\Snippets .

To import snippets, they must be properly formatted in the snippet XML for Windows
PowerShell ISE
snippets and saved in Snippet.ps1xml files. To create eligible snippets,
use the New-IseSnippet
cmdlet. New-IseSnippet creates a
<SnippetTitle>.Snippets.ps1xml file in the
$HOME\Documents\WindowsPowerShell\Snippets

directory. You can move or copy the snippets to the


Snippets directory of a Windows
PowerShell module, or to any other directory.

The Get-IseSnippet cmdlet, which gets user-created snippets in the local snippets
directory, does
not get imported snippets.

This cmdlet was introduced in Windows PowerShell 3.0.

Examples

Example 1: Import snippets from a directory


This example imports the snippets from the \\Server01\Public\Snippets directory into
the current
session. It uses the Recurse parameter to get snippets from all subdirectories
of the Snippets
directory.

PowerShell

Import-IseSnippet -Path \\Server01\Public\Snippets -Recurse

Example 2: Import snippets from a module


This example imports the snippets from the SnippetModule module. The command
uses the
ListAvailable parameter to import the snippets even if the SnippetModule
module is not
imported into the user's session when the command runs.

PowerShell

Import-IseSnippet -Module SnippetModule -ListAvailable

Example 3: Find snippets in modules


This example gets snippets in all installed modules in the PSModulePath environment
variable.

PowerShell

($env:PSModulePath).split(";") |

ForEach-Object {dir $_\*\Snippets\*.Snippets.ps1xml -ErrorAction


SilentlyContinue} |

ForEach-Object {$_.fullname}
Example 4: Import all module snippets
This example imports all snippets from all installed modules into the current session.
Typically,
you don't need to run a command like this because modules that have
snippets will use the
Import-IseSnippet cmdlet to import them for you when the
module is imported.

PowerShell

($env:PSModulePath).split(";") |

ForEach-Object {dir $_\*\Snippets\*.Snippets.ps1xml -ErrorAction


SilentlyContinue} |

ForEach-Object {$psise.CurrentPowerShellTab.Snippets.Load($_)}

Example 5: Copy all module snippets


This example copies the snippet files from all installed modules into the Snippets
directory of
the current user. Unlike imported snippets, which affect only the current
session, copied snippets
are available in every Windows PowerShell ISE session.

PowerShell

($env:PSModulePath).split(";") |

ForEach-Object {dir $_\*\Snippets\*.Snippets.ps1xml -ErrorAction


SilentlyContinue} |

Copy-Item -Destination $HOME\Documents\WindowsPowerShell\Snippets

Parameters
-ListAvailable

Indicates that this cmdlet gets snippets from modules that are installed on the
computer, even if
the modules are not imported into the current session. If this
parameter is omitted, and the module
that is specified by the Module parameter is
not imported into the current session, the attempt
to get the snippets from the
module fails.

This parameter is valid only when the Module parameter is used in the command.

Type: SwitchParameter
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Module

Imports snippets from the specified module into the current session. Wildcard
characters are not
supported.

This parameter imports snippets from Snippet.ps1xml files in the Snippets


subdirectory in the
module path, such as
$HOME\Documents\WindowsPowerShell\Modules\<ModuleName>\Snippets .

This parameter is designed to be used by module authors in a startup script, such as


a script
specified in the ScriptsToProcess key of a module manifest. Snippets in a
module are not
automatically imported with the module, but you can use an Import-
IseSnippet command to import
them.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Path

Specifies the path to the snippets directory in which this cmdlet imports snippets.

Type: String

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Recurse
Indicates that this cmdlet imports snippets from all subdirectories of the value of the
Path
parameter.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
You cannot use the Get-IseSnippet cmdlet to get imported snippets. Get-
IseSnippet gets only
snippets in the $HOME\Documents\WindowsPowerShell\Snippets
directory.

Import-IseSnippet uses the Load static method of


Microsoft.PowerShell.Host.ISE.ISESnippetCollection objects. You can also use the
Load
method of snippets in the Windows PowerShell ISE object model:
$psISE.CurrentPowerShellTab.Snippets.Load()

The New-IseSnippet cmdlet stores new user-created snippets in unsigned .ps1xml


files. As such,
Windows PowerShell cannot load them into a session in which the
execution policy is AllSigned
or Restricted. In a Restricted or AllSigned session,
you can create, get, and import
unsigned user-created snippets, but you cannot
use them in the session.
To use unsigned user-created snippets that the Import-IseSnippet cmdlet returns,
change the
execution policy, and then restart Windows PowerShell ISE.

For more information about Windows PowerShell execution policies, see


about_Execution_Policies.

Related Links
Get-IseSnippet
New-IseSnippet
New-IseSnippet
Reference
Module: ISE

Creates a Windows PowerShell ISE code snippet.

Syntax
PowerShell

New-IseSnippet

[-Title] <String>

[-Description] <String>

[-Text] <String>

[-Author <String>]

[-CaretOffset <Int32>]

[-Force]

[<CommonParameters>]

Description
The New-ISESnippet cmdlet creates a reusable text "snippet" for Windows PowerShell
ISE. You can
use snippets to add text to the Script pane or Command pane in Windows
PowerShell ISE. This cmdlet
is available only in Windows PowerShell ISE.

Beginning in Windows PowerShell 3.0, Windows PowerShell ISE includes a collection of


built-in
snippets. The New-ISESnippet cmdlet lets you create your own snippets to add
to the built-in
collection. You can view, change, add, delete, and share snippet files and
include them in Windows
PowerShell modules. To see snippets in Windows PowerShell
ISE, from the Edit menu, select
Start Snippets or press CTRL + J .

The New-ISESnippet cmdlet creates a <Title>.Snippets.ps1xml file in the


$HOME\Documents\WindowsPowerShell\Snippets directory with the title that you specify. To

include a
snippet file in a module that you are authoring, add the snippet file to a
Snippets subdirectory of
your module directory.

You cannot use user-created snippets in a session in which the execution policy is
Restricted or
AllSigned.

This cmdlet was introduced in Windows PowerShell 3.0.


Examples

Example 1: Create a Comment-Based help snippet


PowerShell

New-IseSnippet -Title Comment-BasedHelp -Description "A template for


comment-based help." -Text "<#

.SYNOPSIS

.DESCRIPTION

.PARAMETER <Parameter-Name>

.INPUTS

.OUTPUTS

.EXAMPLE

.LINK

#>"

This command creates a Comment-BasedHelp snippet for Windows PowerShell ISE. It


creates a file named
Comment-BasedHelp.snippets.ps1xml in the user's Snippets directory
$HOME\Documents\WindowsPowerShell\Snippets .

Example 2: Create a mandatory snippet


PowerShell

$M = @'

Param

[parameter(Mandatory=$true)]

[String[]]

$<ParameterName>

'@

New-ISESnippet -Text $M -Title Mandatory -Description "Adds a mandatory


function parameter." -Author "Patti Fuller, Fabrikam Corp." -Force

This example creates a snippet named Mandatory for Windows PowerShell ISE. The first
command
saves the snippet text in the $M variable. The second command uses the New-
ISESnippet cmdlet to
create the snippet. The command uses the Force parameter to
overwrite a previous snippet with
the same name.
Example 3: Copy a mandatory snippet from a folder to a
destination folder
PowerShell

Copy-Item
"$HOME\Documents\WindowsPowerShell\Snippets\Mandatory.Snippets.ps1xml" -
Destination "\\Server\Share"

This command uses the Copy-Item cmdlet to copy the Mandatory snippet from the
folder where
New-ISESnippet places it to the Server\Share file share.

Parameters
-Author

Specifies the author of the snippet. The author field appears in the snippet file, but it
does not
appear when you click the snippet name in Windows PowerShell ISE.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-CaretOffset

Specifies the character of the snippet text that this cmdlet places the cursor on. Enter
an integer
that represents the cursor position, with "1" representing the first
character of text. The default
value, 0 (zero), places the cursor immediately before
the first character of text. This parameter
does not indent the snippet text.

Type: Int32

Position: Named

Default value: 0

Accept pipeline input: False

Accept wildcard characters: False


-Description

Specifies a description of the snippet. The description value appears when you click
the snippet
name in Windows PowerShell ISE. This parameter is required.

Type: String

Position: 2

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Force

Indicates that this cmdlet overwrites snippet files with the same name in the same
location. By
default, New-ISESnippet does not overwrite files.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Text

Specifies the text value that is added when you select the snippet. The snippet text
appears when
you click the snippet name in Windows PowerShell ISE. This parameter
is required.

Type: String

Position: 3

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Title
Specifies a title or name for the snippet. The title also names the snippet file. This
parameter is
required.

Type: String

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
New-IseSnippet stores new user-created snippets in unsigned .ps1xml files. As such,

Windows
PowerShell cannot add them to a session in which the execution policy is
AllSigned or
Restricted. In a Restricted or AllSigned session, you can create, get, and
import
unsigned user-created snippets, but you cannot use them in the session.

If you use the New-IseSnippet cmdlet in a Restricted or AllSigned session, the snippet
is
created, but an error message appears when Windows PowerShell tries to add the newly
created
snippet to the session. To use the new snippet (and other unsigned user-created
snippets), change
the execution policy, and then restart Windows PowerShell ISE.

For more information about Windows PowerShell execution policies, see


about_Execution_Policies.

To change a snippet, edit the snippet file. You can edit snippet files in the Script
pane of
Windows PowerShell ISE.
To delete a snippet that you added, delete the snippet file.
You cannot delete a built-in snippet, but you can hide all built-in snippets by using
the
"$psise.Options.ShowDefaultSnippets=$false" command.
You can create a snippet that has the same name as a built-in snippet. Both
snippets appear in the
snippet menu in Windows PowerShell ISE.

Related Links
Get-IseSnippet
Import-IseSnippet
Microsoft.PowerShell.Archive
Reference

This section contains the help topics for the cmdlets that are installed with the
PowerShell Microsoft.PowerShell.Archive module. The Archive module contains cmdlets
that let you create and extract archive or ZIP files.

Microsoft.PowerShell.Archive
Compress-Archive Creates a compressed archive, or zipped file, from specified files
and directories.

Expand-Archive Extracts files from a specified archive (zipped) file.


Compress-Archive
Reference
Module: Microsoft.PowerShell.Archive

Creates a compressed archive, or zipped file, from specified files and directories.

Syntax
PowerShell

Compress-Archive

[-Path] <String[]>

[-DestinationPath] <String>

[-CompressionLevel <String>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Compress-Archive

[-Path] <String[]>

[-DestinationPath] <String>

[-CompressionLevel <String>]

-Update

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Compress-Archive

[-Path] <String[]>

[-DestinationPath] <String>

[-CompressionLevel <String>]

-Force

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Compress-Archive

-LiteralPath <String[]>

[-DestinationPath] <String>

[-CompressionLevel <String>]

-Update

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Compress-Archive

-LiteralPath <String[]>

[-DestinationPath] <String>

[-CompressionLevel <String>]

-Force

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Compress-Archive

-LiteralPath <String[]>

[-DestinationPath] <String>

[-CompressionLevel <String>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Compress-Archive cmdlet creates a compressed, or zipped, archive file from one or
more
specified files or directories. An archive packages multiple files, with optional
compression, into
a single zipped file for easier distribution and storage. An archive file
can be compressed by using
the compression algorithm specified by the
CompressionLevel parameter.

The Compress-Archive cmdlet uses the Microsoft .NET API


System.IO.Compression.ZipArchive to compress files.
The maximum file size is 2 GB
because there's a limitation of the underlying API.

7 Note

The Compress-Archive cmdlet ignores hidden files and folders when creating or
updating the
archive file.
To ensure hidden files and folders are compressed into the archive, use the .NET
API instead.

Some examples use splatting to reduce the line length of the code samples. For more
information, see
about_Splatting.

Examples

Example 1: Compress files to create an archive file


This example compresses files from different directories and creates an archive file. A
wildcard is
used to get all files with a particular file extension. There's no directory
structure in the
archive file because the Path only specifies file names.

PowerShell

$compress = @{

Path = "C:\Reference\Draftdoc.docx", "C:\Reference\Images\*.vsd"

CompressionLevel = "Fastest"

DestinationPath = "C:\Archives\Draft.zip"

Compress-Archive @compress

The Path parameter accepts specific file names and file names with wildcards, *.vsd .
The
Path uses a comma-separated list to get files from different directories. The
compression level
is Fastest to reduce processing time. The DestinationPath parameter
specifies the location
for the Draft.zip file. The Draft.zip file contains Draftdoc.docx
and all the files with a
.vsd extension.

Example 2: Compress files using a LiteralPath


This example compresses specific named files and creates a new archive file. There's no
directory
structure in the archive file because the Path only specifies file names.

PowerShell

$compress = @{

LiteralPath= "C:\Reference\Draft Doc.docx",


"C:\Reference\Images\diagram2.vsd"

CompressionLevel = "Fastest"

DestinationPath = "C:\Archives\Draft.zip"

Compress-Archive @compress
Absolute path and file names are used because the LiteralPath parameter doesn't
accept
wildcards. The Path uses a comma-separated list to get files from different
directories. The
compression level is Fastest to reduce processing time. The
DestinationPath parameter
specifies the location for the Draft.zip file. The Draft.zip
file only contains Draftdoc.docx
and diagram2.vsd .

Example 3: Compress a directory that includes the root


directory
This example compresses a directory and creates an archive file that includes the root
directory, and all its files and subdirectories. The archive file has a directory structure
because
the Path specifies a root directory.

PowerShell

Compress-Archive -Path C:\Reference -DestinationPath C:\Archives\Draft.zip

Compress-Archive uses the Path parameter to specify the root directory, C:\Reference .
The
DestinationPath parameter specifies the location for the archive file. The Draft.zip
archive
includes the Reference root directory, and all its files and subdirectories.

Example 4: Compress a directory that excludes the root


directory
This example compresses a directory and creates an archive file that excludes the root
directory
because the Path uses an asterisk ( * ) wildcard. The archive contains a
directory structure
that contains the root directory's files and subdirectories.

PowerShell

Compress-Archive -Path C:\Reference\* -DestinationPath C:\Archives\Draft.zip

Compress-Archive uses the Path parameter to specify the root directory, C:\Reference

with an
asterisk ( * ) wildcard. The DestinationPath parameter specifies the location for
the archive
file. The Draft.zip archive contains the root directory's files and
subdirectories. The
Reference root directory is excluded from the archive.

Example 5: Compress only the files in a root directory


This example compresses only the files in a root directory and creates an archive file.
There's no
directory structure in the archive because only files are compressed.

PowerShell

Compress-Archive -Path C:\Reference\*.* -DestinationPath


C:\Archives\Draft.zip

Compress-Archive uses the Path parameter to specify the root directory, C:\Reference

with a
star-dot-star ( *.* ) wildcard. The DestinationPath parameter specifies the
location for the
archive file. The Draft.zip archive only contains the Reference root
directory's files and the
root directory is excluded.

Example 6: Use the pipeline to archive files


This example sends files down the pipeline to create an archive. There's no directory
structure in
the archive file because the Path only specifies file names.

PowerShell

Get-ChildItem -Path C:\Reference\Afile.txt, C:\Reference\Images\Bfile.txt |

Compress-Archive -DestinationPath C:\Archives\PipelineFiles.zip

Get-ChildItem uses the Path parameter to specify two files from different directories.
Each
file is represented by a FileInfo object and is sent down the pipeline to Compress-
Archive .
The two specified files are archived in PipelineFiles.zip .

Example 7: Use the pipeline to archive a directory


This example sends a directory down the pipeline to create an archive. Files are sent as
FileInfo objects and directories as DirectoryInfo objects. The archive's directory
structure
doesn't include the root directory, but its files and subdirectories are included
in the archive.

PowerShell

Get-ChildItem -Path C:\LogFiles | Compress-Archive -DestinationPath


C:\Archives\PipelineDir.zip

Get-ChildItem uses the Path parameter to specify the C:\LogFiles root directory. Each
FileInfo and DirectoryInfo object is sent down the pipeline.
Compress-Archive adds each object to the PipelineDir.zip archive. The Path parameter

isn't
specified because the pipeline objects are received into parameter position 0.

Example 8: How recursion can affect archives


This example shows how recursion can duplicate files in your archive. For example, if you
use
Get-ChildItem with the Recurse parameter. As recursion processes, each FileInfo
and
DirectoryInfo object is sent down the pipeline and added to the archive.

PowerShell

Get-ChildItem -Path C:\TestLog -Recurse |

Compress-Archive -DestinationPath C:\Archives\PipelineRecurse.zip

The C:\TestLog directory doesn't contain any files. It does contain a subdirectory named
testsub
that contains the testlog.txt file.

Get-ChildItem uses the Path parameter to specify the root directory, C:\TestLog . The

Recurse parameter processes the files and directories. A DirectoryInfo object is created
for
testsub and a FileInfo object testlog.txt .

Each object is sent down the pipeline to Compress-Archive . The DestinationPath


specifies the
location for the archive file. The Path parameter isn't specified because the
pipeline objects
are received into parameter position 0.

The following summary describes the PipelineRecurse.zip archive's contents that


contains a
duplicate file:

The DirectoryInfo object creates the testsub directory and contains the
testlog.txt file,
which reflects the original directory structure.

The FileInfo object creates a duplicate testlog.txt in the archive's root. The
duplicate
file is created because recursion sent a file object to Compress-Archive .
This behavior is
expected because each object sent down the pipeline is added to
the archive.

Example 9: Update an existing archive file


This example updates an existing archive file, Draft.zip , in the C:\Archives directory. In
this
example, the existing archive file contains the root directory, and its files and
subdirectories.

PowerShell
Compress-Archive -Path C:\Reference -Update -DestinationPath
C:\Archives\Draft.zip

The command updates Draft.zip with newer versions of existing files in the
C:\Reference
directory and its subdirectories. And, new files that were added to
C:\Reference or its
subdirectories are included in the updated Draft.zip archive.

Parameters
-CompressionLevel

Specifies how much compression to apply when you're creating the archive file.
Faster compression
requires less time to create the file, but can result in larger file
sizes.

If this parameter isn't specified, the command uses the default value, Optimal.

The following are the acceptable values for this parameter:

Fastest. Use the fastest compression method available to reduce processing


time. Faster
compression can result in larger file sizes.
NoCompression. Doesn't compress the source files.
Optimal. Processing time is dependent on file size.

Type: String

Accepted values: Optimal, NoCompression, Fastest

Position: Named

Default value: Optimal

Accept pipeline input: False

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named
Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-DestinationPath

This parameter is required and specifies the path to the archive output file. The
DestinationPath should include the name of the zipped file, and either the absolute
or relative
path to the zipped file.

If the file name in DestinationPath doesn't have a .zip file name extension, the
cmdlet adds
the .zip file name extension.

Type: String

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Force

Forces the command to run without asking for user confirmation.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-LiteralPath

Specifies the path or paths to the files that you want to add to the archive zipped
file. Unlike the
Path parameter, the value of LiteralPath is used exactly as it's typed.
No characters are
interpreted as wildcards. If the path includes escape characters,
enclose each escape character in
single quotation marks, to instruct PowerShell not
to interpret any characters as escape sequences.
To specify multiple paths, and
include files in multiple locations in your output zipped file, use
commas to separate
the paths.

Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Path

Specifies the path or paths to the files that you want to add to the archive zipped
file. To specify
multiple paths, and include files in multiple locations, use commas to
separate the paths.

This parameter accepts wildcard characters. Wildcard characters allow you to add all
files in a
directory to your archive file.

Using wildcards with a root directory affects the archive's contents:

To create an archive that includes the root directory, and all its files and
subdirectories,
specify the root directory in the Path without wildcards. For
example: -Path C:\Reference
To create an archive that excludes the root directory, but zips all its files and
subdirectories, use the asterisk ( * ) wildcard. For example: -Path C:\Reference\*
To create an archive that only zips the files in the root directory, use the star-
dot-star
( *.* ) wildcard. Subdirectories of the root aren't included in the
archive. For example:
-Path C:\Reference\*.*

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-Update
Updates the specified archive by replacing older file versions in the archive with
newer file
versions that have the same names. You can also add this parameter to
add files to an existing
archive.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet isn't run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a string that contains a path to one or more files.

Outputs
None

Notes
Using recursion and sending objects down the pipeline can duplicate files in your
archive. For
example, if you use Get-ChildItem with the Recurse parameter, each
FileInfo and
DirectoryInfo object that's sent down the pipeline is added to the archive.
The ZIP file specification does not
specify a standard way of encoding filenames that
contain non-ASCII characters. The
Compress-Archive cmdlet uses UTF-8 encoding. Other
ZIP archive tools may use a different encoding
scheme. When extracting files with
filenames not stored using UTF-8 encoding, Expand-Archive uses
the raw value found in
the archive. This can result in a filename that is different than the source
filename stored
in the archive.

Related Links
Expand-Archive
Get-ChildItem
Expand-Archive
Reference
Module: Microsoft.PowerShell.Archive

Extracts files from a specified archive (zipped) file.

Syntax
PowerShell

Expand-Archive

[-Path] <String>

[[-DestinationPath] <String>]

[-Force]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Expand-Archive

-LiteralPath <String>

[[-DestinationPath] <String>]

[-Force]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Expand-Archive cmdlet extracts files from a specified zipped archive file to a
specified
destination folder. An archive file allows multiple files to be packaged, and
optionally compressed,
into a single zipped file for easier distribution and storage.

Examples

Example 1: Extract the contents of an archive


This example extracts the contents of an existing archive file into the folder specified by
the
DestinationPath parameter.
PowerShell

Expand-Archive -LiteralPath 'C:\Archives\Draft[v1].zip' -DestinationPath


C:\Reference

In this example, the LiteralPath parameter is used because the filename contains
characters that
could be interpreted as wildcards.

Example 2: Extract the contents of an archive in the


current folder
This example extracts the contents of an existing archive file in the current folder into
the folder
specified by the DestinationPath parameter.

PowerShell

Expand-Archive -Path Draftv2.zip -DestinationPath C:\Reference

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-DestinationPath

By default, Expand-Archive creates a folder in the current location that is the same
name as the
ZIP file. The parameter allows you to specify the path to a different
folder. The target folder is
created if it does not exist.

Type: String
Position: 1

Default value: A folder in the current location

Accept pipeline input: False

Accept wildcard characters: False

-Force

Forces the command to run without asking for user confirmation.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-LiteralPath

Specifies the path to an archive file. Unlike the Path parameter, the value of
LiteralPath
is used exactly as it is typed. Wildcard characters are not supported. If the
path includes escape
characters, enclose each escape character in single quotation
marks, to instruct PowerShell not to
interpret any characters as escape sequences.

Type: String

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Path

Specifies the path to the archive file.

Type: String

Position: 0
Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a string that contains a path to an existing archive file.

Outputs
None

Notes
The ZIP file specification does not
specify a standard way of encoding filenames that
contain non-ASCII characters. The
Compress-Archive cmdlet uses UTF-8 encoding. Other
ZIP archive tools may use a different encoding
scheme. When extracting files with
filenames not stored using UTF-8 encoding, Expand-Archive uses
the raw value found in
the archive. This can result in a filename that is different than the source
filename stored
in the archive.

Related Links
Compress-Archive
Microsoft.PowerShell.Core
Reference

This section contains the help topics for the cmdlets that are installed with PowerShell
Microsoft.PowerShell.Core module. The Core module contains cmdlets and providers
that manage the
basic features of PowerShell.

Microsoft.PowerShell.Core
Add-History Appends entries to the session history.

Add-PSSnapin Adds one or more Windows PowerShell snap-ins to the current


session.

Clear-History Deletes entries from the PowerShell session command history.

Clear-Host Clears the display in the host program.

Connect-PSSession Reconnects to disconnected sessions.

Debug-Job Debugs a running background, remote, or Windows PowerShell


Workflow job.

Disable-PSRemoting Prevents PowerShell endpoints from receiving remote


connections.

Disable- Disables session configurations on the local computer.


PSSessionConfiguration

Disconnect-PSSession Disconnects from a session.

Enable-PSRemoting Configures the computer to receive remote commands.

Enable- Enables the session configurations on the local computer.


PSSessionConfiguration

Enter-PSHostProcess Connects to and enters into an interactive session with a local


process.

Enter-PSSession Starts an interactive session with a remote computer.

Exit-PSHostProcess Closes an interactive session with a local process.

Exit-PSSession Ends an interactive session with a remote computer.

Export-Console Exports the names of snap-ins in the current session to a console


file.

Export-ModuleMember Specifies the module members that are exported.


ForEach-Object Performs an operation against each item in a collection of input
objects.

Get-Command Gets all commands.

Get-Help Displays information about PowerShell commands and concepts.

Get-History Gets a list of the commands entered during the current session.

Get-Job Gets PowerShell background jobs that are running in the current
session.

Get-Module List the modules imported in the current session or that can be
imported from the PSModulePath.

Get-PSHostProcessInfo Gets process information about the PowerShell host.

Get-PSSession Gets the PowerShell sessions on local and remote computers.

Get-PSSessionCapability Gets the capabilities of a specific user on a constrained session


configuration.

Get-PSSessionConfiguration Gets the registered session configurations on the computer.

Get-PSSnapin Gets the Windows PowerShell snap-ins on the computer.

Get-Verb Gets approved PowerShell verbs.

Import-Module Adds modules to the current session.

Invoke-Command Runs commands on local and remote computers.

Invoke-History Runs commands from the session history.

New-Module Creates a new dynamic module that exists only in memory.

New-ModuleManifest Creates a new module manifest.

New-PSRoleCapabilityFile Creates a file that defines a set of capabilities to be exposed


through a session configuration.

New-PSSession Creates a persistent connection to a local or remote computer.

New- Creates a file that defines a session configuration.


PSSessionConfigurationFile

New-PSSessionOption Creates an object that contains advanced options for a


PSSession.

New-PSTransportOption Creates an object that contains advanced options for a session


configuration.

Out-Default Sends the output to the default formatter and to the default
output cmdlet.

Out-Host Sends output to the command line.

Out-Null Hides the output instead of sending it down the pipeline or


displaying it.

Receive-Job Gets the results of the PowerShell background jobs in the current
session.

Receive-PSSession Gets results of commands in disconnected sessions

Register-ArgumentCompleter Registers a custom argument completer.

Register- Creates and registers a new session configuration.


PSSessionConfiguration

Remove-Job Deletes a PowerShell background job.

Remove-Module Removes modules from the current session.

Remove-PSSession Closes one or more PowerShell sessions (PSSessions).

Remove-PSSnapin Removes Windows PowerShell snap-ins from the current session.

Resume-Job Restarts a suspended job.

Save-Help Downloads and saves the newest help files to a file system
directory.

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-StrictMode Establishes and enforces coding rules in expressions, scripts, and


script blocks.

Start-Job Starts a PowerShell background job.

Stop-Job Stops a PowerShell background job.

Suspend-Job Temporarily stops workflow jobs.

Test-ModuleManifest Verifies that a module manifest file accurately describes the


contents of a module.

Test- Verifies the keys and values in a session configuration file.


PSSessionConfigurationFile

Unregister- Deletes registered session configurations from the computer.


PSSessionConfiguration

Update-Help Downloads and installs the newest help files on your computer.
Wait-Job Waits until one or all of the PowerShell jobs running in the
session are in a terminating state.

Where-Object Selects objects from a collection based on their property values.


About topics
Article • 03/02/2023 • 9 minutes to read

Description
About topics cover a range of concepts about PowerShell.

About Topics

about_Alias_Provider
Provides access to the PowerShell aliases and the values that they represent.

about_Aliases
Describes how to use alternate names for cmdlets and commands in PowerShell.

about_ANSI_Terminals
Describes the support available for ANSI escape sequences in Windows PowerShell.

about_Arithmetic_Operators
Describes the operators that perform arithmetic in PowerShell.

about_Arrays
Describes arrays, which are data structures designed to store collections of items.

about_Assignment_Operators
Describes how to use operators to assign values to variables.

about_Automatic_Variables
Describes variables that store state information for PowerShell. These variables are
created and maintained by PowerShell.
about_Booleans
Describes how boolean expressions are evaluated.

about_Break
Describes a the break statement, which provides a way to exit the current control block.

about_Built-in_Functions
Describes the built-in functions in PowerShell.

about_Calculated_Properties
PowerShell provides the ability to dynamically add new properties and alter the
formatting of objects output to the pipeline.

about_Case-Sensitivity
PowerShell is as case-insensitive as possible while preserving case.

about_Character_Encoding
Describes how PowerShell uses character encoding for input and output of string data.

about_CimSession
Describes a CimSession object and the difference between CIM sessions and PowerShell
sessions.

about_Classes
Describes how you can use classes to create your own custom types.

about_Command_Precedence
Describes how PowerShell determines which command to run.

about_Command_Syntax
Describes the syntax diagrams that are used in PowerShell.

about_Comment_Based_Help
Describes how to write comment-based help topics for functions and scripts.

about_CommonParameters
Describes the parameters that can be used with any cmdlet.

about_Comparison_Operators
The comparison operators in PowerShell can either compare two values or filter
elements of a collection against an input value.

about_Continue
Describes how the continue statement immediately returns the program flow to the top
of a program loop, a switch statement, or a trap statement.

about_Core_Commands
Lists the cmdlets that are designed for use with PowerShell providers.

about_Data_Files
PowerShell data files are used to store arbitrary data using PowerShell syntax.

about_Data_Sections
Explains Data sections, which isolate text strings and other read-only data from script
logic.

about_Debuggers
Describes the PowerShell debugger.

about_DesiredStateConfiguration
Provides a brief introduction to the PowerShell Desired State Configuration (DSC)
feature.

about_Do
Runs a statement list one or more times, subject to a While or Until condition.

about_Enum
The enum statement is used to declare an enumeration. An enumeration is a distinct
type that consists of a set of named labels called the enumerator list.

about_Environment_Provider
Provides access to the Windows environment variables.

about_Environment_Variables
Describes how to access and manage environment variables in PowerShell.

about_Eventlogs
This article describes how PowerShell logs events to the Windows Event log.

about_Execution_Policies
Describes the PowerShell execution policies and explains how to manage them.

about_FileSystem_Provider
Provides access to files and directories.

about_For
Describes a language command you can use to run statements based on a conditional
test.

about_Foreach
Describes a language command you can use to traverse all the items in a collection of
items.

about_Format.ps1xml
The Format.ps1xml files in PowerShell define the default display of objects in the
PowerShell console.

about_Function_Provider
Provides access to the functions defined in PowerShell.

about_Functions_Advanced_Methods
Describes how functions that specify the CmdletBinding attribute can use the methods
and properties that are available to compiled cmdlets.

about_Functions_Advanced_Parameters
Explains how to add parameters to advanced functions.

about_Functions_Advanced
Introduces advanced functions that are a way to create cmdlets using scripts.

about_Functions_Argument_Completion
Argument completion is a feature of PowerShell that provide hints, enables discovery,
and speeds up input entry of argument values.

about_Functions_CmdletBindingAttribute
Describes the attribute that makes a function work like a compiled cmdlet.

about_Functions_OutputTypeAttribute
Describes an attribute that reports the type of object that the function returns.

about_Functions
Describes how to create and use functions in PowerShell.

about_Group_Policy_Settings
Describes the Group Policy settings for Windows PowerShell

about_Hash_Tables
Describes how to create, use, and sort hashtables in PowerShell.

about_Hidden
Describes the hidden keyword, which hides class members from default Get-Member
results.

about_History
Describes how to get and run commands in the command history.

about_If
Describes a language command you can use to run statement lists based on the results
of one or more conditional tests.

about_Intrinsic_Members
Provides information about PowerShell's intrinsic members that are available to all
PowerShell objects.

about_Job_Details
Provides details about background jobs on local and remote computers.

about_Jobs
Provides information about how PowerShell background jobs run a command or
expression in the background without interacting with the current session.

about_Join
Describes how the join operator (-join) combines multiple strings into a single string.

about_Language_Keywords
Describes the keywords in the PowerShell scripting language.

about_Language_Modes
Explains language modes and their effect on PowerShell sessions.

about_Line_Editing
Describes how to edit commands at the PowerShell command prompt.

about_Locations
Describes how to access items from the working location in PowerShell.

about_Logging
PowerShell logs internal operations from the engine, providers, and cmdlets.

about_Logical_Operators
Describes the operators that connect statements in PowerShell.

about_Member-Access_Enumeration
Describes the automatic enumeration of list collection items when using the member-
access operator.

about_Methods
Describes how to use methods to perform actions on objects in PowerShell.

about_Module_Manifests
Describes the settings and practices for writing module manifest files.
about_Modules
Explains how to install, import, and use PowerShell modules.

about_Numeric_Literals
This article describes the syntax and usage of numeric values in PowerShell.

about_Object_Creation
Explains how to create objects in PowerShell.

about_Objects
Provides essential information about objects in Windows PowerShell.

about_Operator_Precedence
Lists the PowerShell operators in precedence order.

about_Operators
Describes the operators that are supported by PowerShell.

about_Output_Streams
Explains the availability and purpose of output streams in PowerShell.

about_PackageManagement
PackageManagement is an aggregator for software package managers.

about_Parameter_Sets
Describes how to define and use parameter sets in advanced functions.

about_Parameters_Default_Values
Describes how to set custom default values for cmdlet parameters and advanced
functions.
about_Parameters
Describes how to work with command parameters in PowerShell.

about_Parsing
Describes how PowerShell parses commands.

about_Path_Syntax
Describes the full and relative path formats in PowerShell.

about_Pipelines
Combining commands into pipelines in the PowerShell

about_PowerShell_exe
Explains how to use the powershell.exe command-line interface. Displays the
command-line parameters and describes the syntax.

about_PowerShell_Ise_exe
Explains how to use the PowerShell_Ise.exe command-line tool.

about_Preference_Variables
Variables that customize the behavior of PowerShell.

about_Profiles
Describes how to create and use a PowerShell profile.

about_Prompts
Describes the Prompt function and demonstrates how to create a custom Prompt
function.

about_Properties
Describes how to use object properties in PowerShell.

about_Providers
Describes how PowerShell providers provide access to data and components that
wouldn't otherwise be easily accessible at the command line. The data is presented in a
consistent format that resembles a file system drive.

about_PSConsoleHostReadLine
Explains how to create a customize how PowerShell reads input at the console prompt.

about_PSCustomObject
Explains the differences between the [psobject] and [pscustomobject] type
accelerators.

about_PSItem
The automatic variable that contains the current object in the pipeline object.

about_PSModulePath
This article the purpose and usage of the $env:PSModulePath environment variable.

about_PSSession_Details
Provides detailed information about Windows PowerShell sessions and the role they
play in remote commands.

about_PSSessions
Describes Windows PowerShell sessions (PSSessions) and explains how to establish a
persistent connection to a remote computer.

about_PSSnapins
Describes Windows PowerShell snap-ins and shows how to use and manage them.
about_Quoting_Rules
Describes rules for using single and double quotation marks in PowerShell.

about_Redirection
Explains how to redirect output from PowerShell to text files.

about_Ref
Describes how to create and use a reference type variable. You can use reference type
variables to permit a function to change the value of a variable that is passed to it.

about_Registry_Provider
Registry

about_Regular_Expressions
Describes regular expressions in PowerShell.

about_Remote_Disconnected_Sessions
Explains how to disconnect and reconnect to a PowerShell Session (PSSession).

about_Remote_Jobs
Describes how to run jobs on remote computers.

about_Remote_Output
Describes how to interpret and format the output of remote commands.

about_Remote_Requirements
Describes the system requirements and configuration requirements for running remote
commands in PowerShell.

about_Remote_Troubleshooting
Describes how to troubleshoot remote operations in PowerShell.

about_Remote_Variables
Explains how to use local and remote variables in remote commands.

about_Remote
Describes how to run remote commands in PowerShell.

about_Requires
Prevents a script from running without the required elements.

about_Reserved_Words
Lists the reserved words that cannot be used as identifiers because they have a special
meaning in PowerShell.

about_Return
Exits the current scope, which can be a function, script, or script block.

about_Run_With_PowerShell
Explains how to use the "Run with PowerShell" feature to run a script from a file system
drive.

about_Scopes
Explains the concept of scope in PowerShell and shows how to set and change the
scope of elements.

about_Script_Blocks
Defines what a script block is and explains how to use script blocks in the PowerShell
programming language.

about_Script_Internationalization
Describes the script internationalization features that make it easy for scripts to display
messages and instructions to users in their user interface (UI) language.

about_Scripts
Describes how to run and write scripts in PowerShell.

about_Session_Configuration_Files
Describes session configuration files, which are used in a session configuration (also
known as an "endpoint") to define the environment of sessions that use the session
configuration.

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
Explains how to sign scripts so that they comply with the PowerShell execution policies.

about_Simplified_Syntax
Describes easier, more natural-language ways of scripting filters for collections of
objects.

about_Special_Characters
Describes the special character sequences that control how PowerShell interprets the
next characters in the sequence.

about_Splatting
Describes how to use splatting to pass parameters to commands in PowerShell.

about_Split
Explains how to use the Split operator to split one or more strings into substrings.
about_Switch
Explains how to use a switch to handle multiple if statements.

about_Tab_Expansion
PowerShell provides completions on input to provide hints, enable discovery, and speed
up input entry. Command names, parameter names, argument values and file paths can
all be completed by pressing the Tab key.

about_Throw
Describes the throw keyword that generates a terminating error.

about_Transactions
Describes how to manage transacted operations in PowerShell.

about_Trap
Describes a keyword that handles a terminating error.

about_Try_Catch_Finally
Describes how to use the try , catch , and finally blocks to handle terminating errors.

about_Type_Accelerators
Describes the Type accelerators available for .NET framework classes

about_Type_Operators
Describes the operators that work with Microsoft .NET types.

about_Types.ps1xml
Explains how to use Types.ps1xml files to extend the types of objects that are used in
PowerShell.
about_Updatable_Help
Describes the updatable help system in PowerShell.

about_Using
Allows you to indicate which namespaces are used in the session.

about_Variable_Provider
Variable

about_Variables
Describes how variables store values that can be used in PowerShell.

about_While
Describes a language statement that you can use to run a command block based on the
results of a conditional test.

about_Wildcards
Describes how to use wildcard characters in PowerShell.

about_Windows_Powershell_5.1
Describes new features that are included in Windows PowerShell 5.1.

about_Windows_PowerShell_ISE
Describes the features and system requirements of Windows PowerShell Integrated
Scripting Environment (ISE).

about_Windows_RT
Explains limitations of Windows PowerShell 4.0 on Windows RT 8.1.

about_WMI_Cmdlets
Provides background information about Windows Management Instrumentation (WMI)
and Windows PowerShell.

about_WMI
Windows Management Instrumentation (WMI) uses the Common Information Model
(CIM) to represent systems, applications, networks, devices, and other manageable
components of the modern enterprise.

about_WQL
Describes WMI Query Language (WQL), which can be used to get WMI objects in
Windows PowerShell.
about_Aliases
Article • 09/19/2022 • 4 minutes to read

Short description
Describes how to use alternate names for cmdlets and commands in 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 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:

PowerShell

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:

PowerShell

Get-AuthenticodeSignature SqlScript.ps1

Or, type:

PowerShell

gas SqlScript.ps1

If you create word as the alias for Microsoft Office Word, you can type
"word" instead of
the following:

PowerShell

"C:\Program Files\Microsoft Office\Office11\Winword.exe"

Built in aliases
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:

PowerShell

Get-Alias

Alias cmdlets
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 PowerShell.

For detailed information about the cmdlets, type:

PowerShell

Get-Help <cmdlet-Name> -Detailed

For example, type:

PowerShell

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:

PowerShell

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-CimInstance cmdlet, type:

PowerShell

Get-Help Get-CimInstance -Detailed

Or, type:

PowerShell

gh Get-CimInstance -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 PowerShell profile. Or,
use the Export-Alias
cmdlet to save the aliases to a file.

For more information, type:

PowerShell

Get-Help about_Profiles

Getting aliases
To get all the aliases in the current session, including the built-in aliases,
the aliases in
your PowerShell profiles, and the aliases that you have created
in the current session,
type:

PowerShell

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:

PowerShell
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:

PowerShell

Get-Alias -Definition Get-ChildItem

Get-Alias output
Get-Alias returns only one type of object, an AliasInfo object

(System.Management.Automation.AliasInfo). The name of aliases that don't


include a
hyphen, such as cd are displayed in the following format:

PowerShell

Get-Alias ac

Output

CommandType Name Version Source

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

Alias ac -> Add-Content

This makes it very quick and easy to get the information that you need.

The arrow-based alias name format is not used for aliases that include a
hyphen. These
are likely to be preferred substitute names for cmdlets and
functions, instead of typical
abbreviations or nicknames, and the author might
not want them to be as evident.

Alternate names for commands with


parameters
You can assign an alias to a cmdlet, script, function, or executable file. 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.
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:

PowerShell

function Get-SystemEventlog {Get-Eventlog -LogName System}

Set-Alias -Name syslog -Value Get-SystemEventlog

You can now type "syslog" instead of the command. And, you can create aliases
for the
new function.

For more information about functions, type:

PowerShell

Get-Help about_Functions

Alias objects
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 PowerShell SDK.

To view the properties and methods of the alias objects, get the aliases.
Then, pipe them
to the Get-Member cmdlet. For example:

PowerShell

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:

PowerShell
Get-Alias -Name dir | Format-List -Property *

PowerShell Alias provider


PowerShell includes the Alias provider. The Alias provider lets you view the
aliases in
PowerShell as though they were on a file system drive.

The Alias provider exposes the Alias: drive. To go into the Alias: drive,
type:

PowerShell

Set-Location Alias:

To view the contents of the drive, type:

PowerShell

Get-ChildItem

To view the contents of the drive from another PowerShell drive, begin the
path with the
drive name. Include the colon (:). For example:

PowerShell

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:

PowerShell

Get-ChildItem -Path Alias:p*

For more information about the PowerShell Alias provider, type:

PowerShell

Get-Help Alias

See also
about_Functions
about_Profiles
about_Providers
Export-Alias
Get-Alias
Import-Alias
New-Alias
Set-Alias
Get-PSDrive
Get-PSProvider
about_Alias_Provider
Article • 09/19/2022 • 6 minutes to read

Provider name
Alias

Drives
Alias:

Capabilities
ShouldProcess

Short description
Provides access to the PowerShell aliases and the values that they represent.

Detailed description
The PowerShell Alias provider lets you get, add, change, clear, and delete
aliases in
PowerShell.

An alias is an alternate name for a cmdlet, function, executable file,


including scripts.
PowerShell includes a set of built-in aliases. You can add
your own aliases to the current
session and to your PowerShell profile.

The Alias drive is a flat namespace that contains only the alias objects.
The aliases have
no child items.

The Alias provider supports the following cmdlets, which are covered
in this article.

Get-Location
Set-Location
Get-Item
New-Item
Remove-Item
Clear-Item
PowerShell includes a set of cmdlets that are designed to view and to change
aliases.
When you use Alias cmdlets, you do not need to specify the
Alias: drive in the name.
This article does not cover working with Alias
cmdlets.

Export-Alias
Get-Alias
Import-Alias
New-Alias
Set-Alias

Types exposed by this provider


Each alias is an instance of the
System.Management.Automation.AliasInfo
class.

Navigating the Alias drive


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:

PowerShell

Set-Location Alias:

To return to a file system drive, type the drive name. For example, type:

PowerShell

Set-Location C:

You can also work with the Alias provider from any other PowerShell drive. To
reference
an alias from another location, use the Alias: drive name in the
path.

7 Note

PowerShell uses aliases to allow you a familiar way to work with provider
paths.
Commands such as dir and ls are now aliases for
Get-ChildItem, cd is
an alias for
Set-Location. and pwd
is an alias for
Get-Location.

Displaying the Contents of the Alias: drive


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.

PowerShell

PS Alias:\> 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.

The Alias provider has no containers, so the above command has the
same effect when
used with Get-ChildItem .

PowerShell

Get-ChildItem -Path Alias:

Get a selected alias


This command gets the ls alias.
Because it includes the path, you can use it in any
PowerShell drive.

PowerShell

Get-Item -Path Alias:ls

If you are in the Alias: drive, you can omit the drive name from the path.

You can also retrieve the definition for an alias by prefixing the provider
path with the
dollar sign ( $ ).

PowerShell

$Alias:ls

Get all aliases for a specific cmdlet


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

Get-Item -Path Alias:* | Where-Object {$_.Definition -eq "Get-ChildItem"}

Creating aliases

Create an alias from the Alias: drive


This command creates the serv alias for the Get-Service cmdlet. Because the
current
location is in the Alias: drive, the -Path parameter is not needed.

This command also uses the -Options dynamic parameter to set the AllScope
option on
the alias. The -Options parameter is available in the New-Item
cmdlet only when you are
in the Alias: drive. The dot ( . ) indicates the
current directory, which is the alias drive.

PS Alias:\> New-Item -Path . -Name serv -Value Get-Service -Options


"AllScope"

Create an alias with an absolute path


You can create an alias for any item that invokes a command.
This command creates the
np alias for Notepad.exe .

PowerShell

New-Item -Path Alias:np -Value c:\windows\notepad.exe

Create an alias to a new function


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.

When the command is complete, you can use either CD32 or go to invoke the
function.

PowerShell
function CD32 {Set-Location -Path c:\windows\system32}

Set-Item -Path Alias:go -Value CD32

Changing aliases

Change the options of an alias


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 when you use it
with the Alias or Function provider.

PowerShell

Set-Item -Path Alias:dir -Options "AllScope,ReadOnly"

Change an aliases referenced command


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.

PowerShell

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:

PowerShell

Get-Item -Path gp | Format-List -Property *

Rename an alias
This command uses the Rename-Item cmdlet to change the popd alias to pop .

PowerShell

Rename-Item -Path Alias:popd -NewName pop

Copying an alias
This command copies the pushd alias so that a new push alias is created for
the Push-
Location cmdlet.

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.

PowerShell

Copy-Item -Path Alias:pushd -Destination Alias:push

Deleting an alias
This command deletes the serv alias from the current session.
You can use this
command in any PowerShell drive.

PowerShell

Remove-Item -Path Alias:serv

This command deletes aliases that begin with "s". It does not delete read-only
aliases.

PowerShell

Clear-Item -Path Alias:s*

Delete read-only aliases


This command deletes all aliases from the current session, except those with a
value of
Constant for their Options property. The -Force parameter
allows the command to
delete aliases whose Options property has a value of
ReadOnly .
PowerShell

Remove-Item Alias:* -Force

Dynamic parameters
Dynamic parameters are cmdlet parameters that are added by a 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.

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

Using the pipeline


Provider cmdlets accept pipeline input. You can use the pipeline to simplify
task by
sending provider data from one cmdlet to another provider cmdlet.
To read more about
how to use the pipeline with provider cmdlets, see the
cmdlet references provided
throughout this article.

Getting help
Beginning in Windows PowerShell 3.0, you can get customized help topics for
provider
cmdlets that explain how those cmdlets behave in a file system drive.
To get the help topics that are customized for the file system drive, run a
Get-Help
command in a file system
drive or use the -Path parameter of
Get-Help to specify a file
system
drive.

PowerShell

Get-Help Get-ChildItem

PowerShell

Get-Help Get-ChildItem -Path alias:

See also
about_Aliases
about_Providers
about_ANSI_Terminals
Article • 03/02/2023 • 2 minutes to read

Short description
Describes the support available for ANSI escape sequences in Windows PowerShell.

Long description
Unlike newer versions of PowerShell, the Windows PowerShell 5.1 engine and core
cmdlets don't output ANSI escape sequences to format the text displayed on your
screen. However, that doesn't prevent you from using ANSI escape sequences for
text
formatting in terminals that support it.

ANSI Terminal support


On Windows 10 and higher, the Windows Console Host is xterm compatible.
The
Windows Terminal application is also xterm compatible. These
terminals support ANSI
escape sequences.

The PSReadLine module uses ANSI sequences to colorize PowerShell syntax


elements on
the command line. The colors can be managed using
Get-PSReadLineOption and Set-
PSReadLineOption.

The default colors were chosen for use with terminals that have a dark
background. You
can change the colors needed for your environment. For more
information, see
Customizing your shell experience.

Redirecting output
You should be careful about creating output that's decorated with ANSI escape
sequences. The formatting is intended for display in the terminal. When you
pipe that
output to another command or redirect the output to a file, the
output contains the
ANSI escape sequences. This formatting may not be
understood by the downstream
command in your pipeline or be rendered correctly
in the output file.

PowerShell 7.2 and higher removes ANSI decorations when redirecting and
provides
tools that make using ANSI escape sequences easier.
about_Arithmetic_Operators
Article • 09/19/2022 • 11 minutes to read

Short description
Describes the operators that perform arithmetic in 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.

The addition operator ( + ) and multiplication operator ( * ) also operate on


strings,
arrays, and hashtables. 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's used to evaluate
the statement is determined
by the type of the leftmost object in the
expression.

Beginning in PowerShell 2.0, all arithmetic operators work on 64-bit numbers.

Beginning in PowerShell 3.0, the -shr (shift-right) and -shl (shift-left)


are added to
support bitwise arithmetic in PowerShell. The bitwise operators
only work on integer
types.

PowerShell supports the following arithmetic operators:

Addition ( + ) - Adds numbers, concatenates strings, arrays, and hash tables

PowerShell

6 + 2 # result = 8

"file" + "name" # result = "filename"

@(1, "one") + @(2.0, "two") # result = @(1, "one", 2.0, "two")

@{"one" = 1} + @{"two" = 2} # result = @{"one" = 1; "two" = 2}

Subtraction ( - ) - Subtracts or negates numbers

PowerShell

6 - 2 # result = 4

- -6 # result = 6

(Get-Date).AddDays(-1) # Yesterday's date

Multiplication ( * ) - Multiply numbers or copy strings and arrays the


specified
number of times

PowerShell

6 * 2 # result = 12

@("!") * 4 # result = @("!","!","!","!")

"!" * 3 # result = "!!!"

Division ( / ) - Divides numbers

PowerShell

6 / 2 # result = 3

Modulus ( % ) - returns the remainder of a division operation.

PowerShell

7 % 2 # result = 1

Bitwise AND ( -band )

PowerShell

5 -band 3 # result = 1

Bitwise NOT ( -bnot )

PowerShell

-bnot 5 # result = -6

Bitwise OR ( -bor )

PowerShell

5 -bor 0x03 # result = 7

Bitwise XOR ( -bxor )


PowerShell

5 -bxor 3 # result = 6

Shifts bits to the left ( -shl )

PowerShell

102 -shl 2 # result = 408

Shifts bits to the right ( -shr )

PowerShell

102 -shr 2 # result = 25

Operator precedence
PowerShell processes arithmetic operators in the following order:

Precedence Operator Description

1 () Parentheses

2 - For a negative number or unary operator

3 *, /, % For multiplication and division

4 +, - For addition and subtraction

5 -band , -bnot For bitwise operations

5 -bor , -bxor For bitwise operations

5 -shr , -shl For bitwise operations

PowerShell processes the expressions from left to right according to the


precedence
rules. The following examples show the effect of the precedence
rules:

PowerShell

3+6/3*4 # result = 11

3+6/(3*4) # result = 3.5

(3+6)/3*4 # result = 12

The order in which PowerShell evaluates expressions might differ from other
programming and scripting languages that you have used. The following example
shows
a complicated assignment statement.

PowerShell

$a = 0

$b = @(1,2)

$c = @(-1,-2)

$b[$a] = $c[$a++]

In this example, the expression $a++ is evaluated before $b[$a] . Evaluating


$a++
changes the value of $a after it's used in the statement $c[$a++] ,
but before it's used in
$b[$a] . The variable $a in $b[$a] equals 1 , not
0 . Therefore, the statement assigns a
value to $b[1] , not $b[0] .

The code above is equivalent to:

PowerShell

$a = 0

$b = @(1,2)

$c = @(-1,-2)

$tmp = $c[$a]

$a = $a + 1

$b[$a] = $tmp

Division and rounding


When the quotient of a division operation is an integer, PowerShell rounds the
value to
the nearest integer. When the value is .5 , it rounds to the nearest
even integer.

The following example shows the effect of rounding to the nearest even integer.

PowerShell

PS> [int]( 5 / 2 ) # Result is rounded down

PS> [int]( 7 / 2 ) # Result is rounded up

You can use the [Math] class to get different rounding behavior.
PowerShell

PS> [int][Math]::Round(5 / 2,[MidpointRounding]::AwayFromZero

PS> [int][Math]::Ceiling(5 / 2)

PS> [int][Math]::Floor(5 / 2)

For more information, see the Math.Round


method.

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 can't 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:

PowerShell

$a = 1,2,3

$b = "A","B","C"

$a + $b

Output

You can also perform arithmetic operations on objects of different types. The
operation
that PowerShell performs is determined by the Microsoft .NET type of
the leftmost
object in the operation. PowerShell tries to convert all the
objects in the operation to the
.NET type of the first object. If it succeeds
in converting the objects, it performs the
operation appropriate to the .NET
type of the first object. If it fails to convert any of the
objects, the
operation fails.

The following examples demonstrate the use of the addition and multiplication
operators in operations that include different object types.

PowerShell

$array = 1,2,3

$red = [ConsoleColor]::Red

$blue = [ConsoleColor]::Blue

"file" + 16 # result = "file16"

$array + 16 # result = 1,2,3,16

$array + "file" # result = 1,2,3,"file"

$array * 2 # result = 1,2,3,1,2,3

"file" * 3 # result = "filefilefile"

$blue + 3 # result = Red

$red - 3 # result = Blue

$blue - $red # result = -3

+ '123' # result = 123

Because the method that's used to evaluate statements is determined by the


leftmost
object, addition and multiplication in PowerShell aren't strictly
commutative. For
example, (a + b) doesn't always equal (b + a) , and (ab)
doesn't always equal (ba) .

The following examples demonstrate this principle:

PowerShell

PS> "file" + 16

file16

PS> 16 + "file"

InvalidArgument: can't convert value "file" to type "System.Int32". Error:

"Input string wasn't in a correct format."

Hash tables are a slightly different case. You can add hash tables to another
hash table,
as long as, the added hash tables don't have duplicate keys.

The following example show how to add hash tables to each other.

PowerShell

$hash1 = @{a=1; b=2; c=3}

$hash2 = @{c1="Server01"; c2="Server02"}

$hash1 + $hash2

Output

Name Value

---- -----

c2 Server02

a 1

b 2

c1 Server01

c 3

The following example throws an error because one of the keys is duplicated in
both
hash tables.

PowerShell

$hash1 = @{a=1; b=2; c=3}

$hash2 = @{c1="Server01"; c="Server02"}

$hash1 + $hash2

Output

OperationStopped:

Line |

3 | $hash1 + $hash2

| ~~~~~~~~~~~~~~~

| Item has already been added. Key in dictionary: 'c' Key being added:
'c'

Also, you can add a hash table to an array; and, the entire hash table becomes
an item
in the array.

PowerShell

$array1 = @(0, "Hello World", [datetime]::Now)

$hash1 = @{a=1; b=2}

$array2 = $array1 + $hash1

$array2

Output

Hello World

Monday, June 12, 2017 3:05:46 PM

Key : a

Value : 1

Name : a

Key : b

Value : 2

Name : b

However, you can't add any other type to a hash table.

PowerShell

$hash1 + 2

Output

InvalidOperation: A hash table can only be added to another hash table.

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:

PowerShell

$array = @()

(0..9).foreach{ $array += $_ }

$array

Output

Type conversion to accommodate result


PowerShell automatically selects the .NET numeric type that best expresses the
result
without losing precision. For example:

PowerShell

2 + 3.1

(2).GetType().FullName

(2 + 3.1).GetType().FullName

Output

5.1

System.Int32

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:

PowerShell

(512MB).GetType().FullName

(512MB * 512MB).GetType().FullName

Output

System.Int32

System.Double

The type of the result isn't always the same as one of the operands. In the
following
example, the negative value can't be cast to an unsigned integer, and
the unsigned
integer is too large to be cast to Int32 :

PowerShell

([int32]::minvalue + [uint32]::maxvalue).gettype().fullname

Output

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 is Decimal type. Any result too large for the
Decimal value is an error.

PowerShell

PS> [Decimal]::maxvalue

79228162514264337593543950335

PS> [Decimal]::maxvalue + 1

RuntimeException: Value was either too large or too small for a Decimal.

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:

PowerShell

PS> $intA = 6

PS> $intB = 4

PS> $intA + $intB

10

PS> $a = "Power"

PS> $b = "Shell"

PS> $a + $b

PowerShell

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
PowerShell commands:

PowerShell

(get-date) + (new-timespan -day 1)

The parenthesis operator forces the evaluation of the Get-Date cmdlet and the
evaluation of the New-TimeSpan -Day 1 cmdlet expression, in that order. Both
results are
then added using the + operator.

PowerShell

Get-Process | Where-Object { ($_.ws * 2) -gt 50mb }

Output

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

In the above expression, each process working space ( $_.ws ) is multiplied by


2 ; and, the
result, compared against 50mb to see if it's greater than that.

Bitwise operators
PowerShell supports the standard bitwise operators, including bitwise-AND
( -band ), the
inclusive and exclusive bitwise-OR operators ( -bor and
-bxor ), and bitwise-NOT ( -
bnot ).

Beginning in PowerShell 2.0, all bitwise operators work with 64-bit integers.

Beginning in PowerShell 3.0, the -shr (shift-right) and -shl (shift-left)


are introduced to
support bitwise arithmetic in PowerShell.

PowerShell supports the following bitwise operators.

Operator Description Expression Result

-band Bitwise AND 10 -band 3 2

-bor Bitwise OR (inclusive) 10 -bor 3 11

-bxor Bitwise OR (exclusive) 10 -bxor 3 9

-bnot Bitwise NOT -bNot 10 -11

-shl Shift-left 102 -shl 2 408

-shr Shift-right 102 -shr 1 51

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's set to 1 only when both input
bits are 1.
1010 (10)

0011 ( 3)

-------------- bAND

0010 ( 2)

In a bitwise OR (inclusive) operation, the resulting bit's set to 1 when either


or both
input bits are 1. The resulting bit's set to 0 only when both input
bits are set to 0.

1010 (10)

0011 ( 3)

-------------- bOR (inclusive)

1011 (11)

In a bitwise OR (exclusive) operation, the resulting bit's set to 1 only when


one input
bit's 1.

1010 (10)

0011 ( 3)

-------------- bXOR (exclusive)

1001 ( 9)

The bitwise NOT operator is a unary operator that produces the binary
complement of
the value. A bit of 1 is set to 0 and a bit of 0 is set to 1.

For example, the binary complement of 0 is -1, the maximum unsigned integer
(0xffffffff), and the binary complement of -1 is 0.

PowerShell

-bNot 10

Output

-11

0000 0000 0000 1010 (10)

------------------------- bNOT

1111 1111 1111 0101 (-11, xfffffff5)

In a bitwise shift-left operation, all bits are moved "n" places to the left,
where "n" is the
value of the right operand. A zero is inserted in the ones
place.

When the left operand is an Integer (32-bit) value, the lower 5 bits of the
right operand
determine how many bits of the left operand are shifted.

When the left operand is a Long (64-bit) value, the lower 6 bits of the right
operand
determine how many bits of the left operand are shifted.

Expression Result Binary Result

21 -shl 0 21 0001 0101

21 -shl 1 42 0010 1010

21 -shl 2 84 0101 0100

In a bitwise shift-right operation, all bits are moved "n" places to the right,
where "n" is
specified by the right operand. The shift-right operator (-shr)
inserts a zero in the left-
most place when shifting a positive or unsigned
value to the right.

When the left operand is an Integer (32-bit) value, the lower 5 bits of the
right operand
determine how many bits of the left operand are shifted.

When the left operand is a Long (64-bit) value, the lower 6 bits of the right
operand
determine how many bits of the left operand are shifted.

Expression Result Binary Hex

21 -shr 0 21 0001 0101 0x15

21 -shr 1 10 0000 1010 0x0A

21 -shr 2 5 0000 0101 0x05

21 -shr 31 0 0000 0000 0x00

21 -shr 32 21 0001 0101 0x15

21 -shr 64 21 0001 0101 0x15

21 -shr 65 10 0000 1010 0x0A

21 -shr 66 5 0000 0101 0x05

[int]::MaxValue -shr 1 1073741823 0x3FFFFFFF

[int]::MinValue -shr 1 -1073741824 0xC0000000


Expression Result Binary Hex

-1 -shr 1 -1 0xFFFFFFFF

See also
about_Arrays
about_Hash_Tables
about_Operators
about_Assignment_Operators
about_Comparison_Operators
about_Variables
Get-Date
New-TimeSpan
about_Arrays
Article • 01/18/2023 • 17 minutes to read

Short description
Describes arrays, which are data structures designed to store collections of
items.

Long description
An array is a data structure that's designed to store a collection of items.
The items can
be the same type or different types.

Beginning in Windows PowerShell 3.0, a collection of zero or one object has


some
properties of arrays.

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
(integer)
values of 22, 5, 10, 8, 12, 9, and 80, type:

PowerShell

$A = 22,5,10,8,12,9,80

The comma can also be used to initialize a single item array by placing the
comma
before the single item.

For example, to create a single item array named $B containing the single
value of 7,
type:

PowerShell

$B = ,7

You can also create and initialize an array using the range operator ( .. ).
The following
example creates an array containing the values 5 through 8.
PowerShell

$C = 5..8

As a result, $C contains four values: 5, 6, 7, and 8.

When no data type is specified, PowerShell creates each array as an object


array
(System.Object[]). To determine the data type of an array, use the
GetType() method.
For example:

PowerShell

$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:

PowerShell

[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 .NET. 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:

PowerShell

[Diagnostics.Process[]]$zz = Get-Process

The array sub-expression operator


The array sub-expression operator creates an array from the statements inside
it.
Whatever the statement inside the operator produces, the operator places it
in an array.
Even if there is zero or one object.

The syntax of the array operator is as follows:


syntax

@( ... )

You can use the array operator to create an array of zero or one object. For
example:

PowerShell

$a = @("Hello World")

$a.Count

Output

PowerShell

$b = @()

$b.Count

Output

The array operator is useful in scripts when you are getting objects, but don't
know how
many to expect. For example:

PowerShell

$p = @(Get-Process Notepad)

For more information about the array sub-expression operator, see


about_Operators.

Accessing and using array elements

Reading an array
You can refer to an array using its variable name. To display all the elements
in the array,
invoke the array name. For example, $a is an array of the
numbers 0 through 9:

PowerShell
$a

Output

You can refer to the elements in an array using an index. Enclose the index
number in
brackets. Index values start at 0 . For example, to display the
first element in the $a
array, type:

PowerShell

$a[0]

Output

To display the third element in the $a array, type:

PowerShell

$a[2]

Output

You can retrieve part of the array using a range operator for the index. For
example, to
retrieve the second to fifth elements of the array, you would type:

PowerShell

$a[1..4]

Output

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,
in index ascending
order, type:

PowerShell

$a = 0 .. 9

$a[-3..-1]

Output

If you type negative indexes in descending order, your output changes.

PowerShell

$a = 0 .. 9

$a[-1..-3]

Output

However, be cautious when using this notation. The notation cycles from the end
boundary to the beginning of the array.

PowerShell

$a = 0 .. 9

$a[2..-2]

Output
2

Also, one common mistake is to assume $a[0..-2] refers 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 plus operator ( + ) to combine a ranges with a list of elements
in an
array. For example, to display the elements at index positions 0, 2, and
4 through 6, type:

PowerShell

$a = 0 .. 9

$a[0,2+4..6]

Output

Also, to list multiple ranges and individual elements you can use the plus
operator. For
example, to list elements zero to two, four to six, and the
element at eighth positional
type:

PowerShell

$a = 0..9

$a[+0..2+4..6+8]

Output

Iterations over array elements


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:

PowerShell

$a = 0..9

foreach ($element in $a) {

$element

Output

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 use a for loop to return every other
value in an
array, type:

PowerShell

$a = 0..9

for ($i = 0; $i -le ($a.length - 1); $i += 2) {

$a[$i]

Output

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:

PowerShell

$a = 0..9

$i=0

while($i -lt 4) {

$a[$i]

$i++

Output

Properties of arrays

Count or Length or LongLength


To determine how many items are in an array, use the Length property or its
Count alias.
Longlength is useful if the array contains more than
2,147,483,647 elements.

PowerShell

$a = 0..9

$a.Count

$a.Length

Output

10

10

Rank
Returns the number of dimensions in the array. Most arrays in PowerShell have
one
dimension, only. Even when you think you are building a multidimensional
array like the
following example:

PowerShell

$a = @(

@(0,1),

@("b", "c"),

@(Get-Process)

"`$a rank: $($a.Rank)"

"`$a length: $($a.Length)"

"`$a[2] length: $($a[2].Length)"

"Process `$a[2][1]: $($a[2][1].ProcessName)"

In this example, you are creating a single-dimensional array that contains


other arrays.
This is also known as a jagged array. The Rank property
proved that this is single-
dimensional. To access items in a jagged array, the
indexes must be in separate brackets
( [] ).

Output

$a rank: 1

$a length: 3

$a[2] length: 348

Process $a[2][1]: AcroRd32

Multidimensional arrays are stored in row-major order . The following


example shows
how to create a truly multidimensional array.

PowerShell

[string[,]]$rank2 = [string[,]]::New(3,2)

$rank2.rank

$rank2.Length

$rank2[0,0] = 'a'

$rank2[0,1] = 'b'

$rank2[1,0] = 'c'

$rank2[1,1] = 'd'

$rank2[2,0] = 'e'

$rank2[2,1] = 'f'

$rank2[1,1]

Output
2

To access items in a multidimensional array, separate the indexes using a comma


( , )
within a single set of brackets ( [] ).

Some operations on a multidimensional array, such as replication and


concatenation,
require that array to be flattened. Flattening turns the array
into a 1-dimensional array
of unconstrained type. The resulting array takes on
all the elements in row-major order.
Consider the following example:

PowerShell

$a = "red",$true

$b = (New-Object 'int[,]' 2,2)

$b[0,0] = 10

$b[0,1] = 20

$b[1,0] = 30

$b[1,1] = 40

$c = $a + $b

$a.GetType().Name

$b.GetType().Name

$c.GetType().Name

$c

The output shows that $c is a 1-dimensional array containing the items from
$a and $b
in row-major order.

Output

Object[]

Int32[,]

Object[]

red

True

10

20

30

40

Methods of arrays

Clear
Sets all element values to the default value of the array's element type. The
Clear()
method doesn't reset the size of the array.

In the following example $a is an array of objects.

PowerShell

$a = 1, 2, 3

$a.Clear()

$a | % { $null -eq $_ }

Output

True

True

True

In this example, $intA is explicitly typed to contain integers.

PowerShell

[int[]] $intA = 1, 2, 3

$intA.Clear()

$intA

Output

ForEach()
Allows to iterate over all elements in the array and perform a given operation
for each
element of the array.

The ForEach() method has several overloads that perform different operations.

ForEach(scriptblock expression)

ForEach(scriptblock expression, object[] arguments)

ForEach(type convertToType)

ForEach(string propertyName)

ForEach(string propertyName, object[] newValue)

ForEach(string methodName)

ForEach(string methodName, object[] arguments)

ForEach(scriptblock expression)

ForEach(scriptblock expression, object[] arguments)

This method was added in PowerShell v4.

7 Note

The syntax requires the usage of a script block. Parentheses are optional if
the
scriptblock is the only parameter. Also, there must not be a space
between the
method and the opening parenthesis or brace.

The following example shows how use the ForEach() method. In this case the
intent is
to generate the square value of the elements in the array.

PowerShell

$a = @(0 .. 3)

$a.ForEach({ $_ * $_})

Output

Just like the ArgumentList parameter of ForEach-Object , the arguments


parameter
allows the passing of an array of arguments to a script block
configured to accept them.

For more information about the behavior of ArgumentList, see


about_Splatting.

ForEach(type convertToType)
The ForEach() method can be used to cast the elements to a different type;
the
following example shows how to convert a list of string dates to
[DateTime] type.

PowerShell
("1/1/2017", "2/1/2017", "3/1/2017").ForEach([datetime])

Output

Sunday, January 1, 2017 12:00:00 AM

Wednesday, February 1, 2017 12:00:00 AM

Wednesday, March 1, 2017 12:00:00 AM

ForEach(string propertyName)

ForEach(string propertyName, object[] newValue)


The ForEach() method can also be used to retrieve, or set property values for
every
item in the collection.

PowerShell

# Set all LastAccessTime properties of files to the current date.

(dir 'C:\Temp').ForEach('LastAccessTime', (Get-Date))

# View the newly set LastAccessTime of all items, and find Unique entries.

(dir 'C:\Temp').ForEach('LastAccessTime') | Get-Unique

Output

Wednesday, June 20, 2018 9:21:57 AM

ForEach(string methodName)

ForEach(string methodName, object[] arguments)


Lastly, ForEach() methods can be used to execute a method on every item in
the
collection.

PowerShell

("one", "two", "three").ForEach("ToUpper")

Output
ONE

TWO

THREE

Just like the ArgumentList parameter of ForEach-Object , the arguments


parameter
allows the passing of an array of values to a script block configured
to accept them.

7 Note

Starting in Windows PowerShell 3.0 retrieving properties and executing


methods
for each item in a collection can also be accomplished using "Methods
of scalar
objects and collections". You can read more about that here
about_Methods.

Where()
Allows to filter or select the elements of the array. The script must evaluate
to anything
different than: zero (0), empty string, $false or $null for the
element to show after the
Where() . For more information about boolean
evaluation, see about_Booleans.

There is one definition for the Where() method.

Where(scriptblock expression[, WhereOperatorSelectionMode mode

[, int numberToReturn]])

7 Note

The syntax requires the usage of a script block. Parentheses are optional if
the
scriptblock is the only parameter. Also, there must not be a space
between the
method and the opening parenthesis or brace.

The Expression is a scriptblock that's required for filtering, the mode


optional argument
allows additional selection capabilities, and the
numberToReturn optional argument
allows the ability to limit how many items
are returned from the filter.

The value of mode must be a WhereOperatorSelectionMode enum value:

Default ( 0 ) - Return all items

First ( 1 ) - Return the first item


Last ( 2 ) - Return the last item

SkipUntil ( 3 ) - Skip items until condition is true, return all the remaining
items
(including the first item for which the condition is true)
Until ( 4 ) - Return all items until condition is true
Split ( 5 ) - Return an array of two elements

The first element contains matching items


The second element contains the remaining items

The following example shows how to select all odd numbers from the array.

PowerShell

(0..9).Where{ $_ % 2 }

Output

This example show how to select the strings that aren't empty.

PowerShell

('hi', '', 'there').Where({$_.Length})

Output

hi

there

Default

The Default mode filters items using the Expression scriptblock.

If a numberToReturn is provided, it specifies the maximum number of items


to return.

PowerShell

# Get the zip files in the current users profile, sorted by LastAccessTime

$Zips = dir $env:userprofile -Recurse '*.zip' | Sort-Object LastAccessTime

# Get the least accessed file over 100MB

$Zips.Where({$_.Length -gt 100MB}, 'Default', 1)

7 Note

Both the Default mode and First mode return the first
( numberToReturn ) items,
and can be used interchangeably.

Last

PowerShell

$h = (Get-Date).AddHours(-1)

$logs = dir 'C:\' -Recurse '*.log' | Sort-Object CreationTime

# Find the last 5 log files created in the past hour

$logs.Where({$_.CreationTime -gt $h}, 'Last', 5)

SkipUntil

The SkipUntil mode skips all objects in a collection until an object passes
the script
block expression filter. It then returns ALL remaining
collection items without testing
them. Only one passing item is tested.

This means the returned collection contains both passing and


non-passing items that
have NOT been tested.

The number of items returned can be limited by passing a value to the


numberToReturn
argument.

PowerShell

$computers = "Server01", "Server02", "Server03", "localhost", "Server04"

# Find the first available online server.

$computers.Where({ Test-Connection $_ }, 'SkipUntil', 1)

Output

localhost

Until
The Until mode inverts the SkipUntil mode. It returns ALL items in a
collection until an
item passes the script block expression. Once an item
passes the scriptblock expression,
the Where() method stops processing
items.

This means that you receive the first set of non-passing items from the
Where() method.
After one item passes, the rest are NOT tested or
returned.

The number of items returned can be limited by passing a value to the


numberToReturn
argument.

PowerShell

# Retrieve the first set of numbers less than or equal to 10.

(1..50).Where({$_ -gt 10}, 'Until')

# This would perform the same operation.

(1..50).Where({$_ -le 10})

Output

10

7 Note

Both Until and SkipUntil operate under the premise of NOT testing a batch
of
items.

Until returns the items BEFORE the first PASS. SkipUntil returns
all items AFTER
the first pass, including the first passing item.

Split
The Split mode splits, or groups collection items into two separate
collections. Those
that pass the scriptblock expression, and those that do not.
If a numberToReturn is specified, the first collection, contains the
passing items, not to
exceed the value specified.

The remaining objects, even those that PASS the expression filter, are
returned in the
second collection.

PowerShell

$running, $stopped = (Get-Service).Where({$_.Status -eq 'Running'}, 'Split')

$running

Output

Status Name DisplayName

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

Running Appinfo Application Information

Running AudioEndpointBu... Windows Audio Endpoint Builder

Running Audiosrv Windows Audio

...

PowerShell

$stopped

Output

Status Name DisplayName

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

Stopped AJRouter AllJoyn Router Service

Stopped ALG Application Layer Gateway Service

Stopped AppIDSvc Application Identity

...

7 Note

Both ForEach() and Where() methods are intrinsic members. For more
information
about intrinsic members, see about_Instrinsic_Members.

Get the members of an array


To get 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 , PowerShell sends the items one at a
time and
Get-Member returns the type of each item in the array (ignoring
duplicates).

When you use the InputObject parameter, Get-Member returns the members of
the
array.

For example, the following command gets the members of the $a array variable.

PowerShell

Get-Member -InputObject $a

You can also get the members of an array by typing a comma ( , ) before the
value that's
piped to the Get-Member cmdlet. The comma makes the array the
second item in an
array of arrays. PowerShell pipes the arrays one at a time
and Get-Member returns the
members of the array. Like the next two examples.

PowerShell

,$a | Get-Member

,(1,2,3) | Get-Member

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:

PowerShell

$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:

PowerShell

$a.SetValue(500,1)

You can use the += operator to add an element to an array. The following
example
shows how to add an element to the $a array.

PowerShell

$a = @(0..4)

$a += 5

7 Note

When you use the += operator, PowerShell actually creates a new array with
the
values of the original array and the added value. This might cause
performance
issues if the operation is repeated several times or the size of
the array is too big.

It isn't 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:

PowerShell

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

PowerShell

$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, assign a value of $null to the array. The following


command deletes
the array in the $a variable.

$a = $null

You can also use the Remove-Item cmdlet, but assigning a value of $null is
faster,
especially for large arrays.
Arrays of zero or one
Beginning in Windows PowerShell 3.0, a collection of zero or one object has the
Count
and Length properties. Also, you can index into an array of one
object. This feature
helps you to avoid scripting errors that occur when a
command that expects a collection
gets fewer than two items.

7 Note

In Windows PowerShell, objects created by casting a Hashtable to


[pscustomobject] do
not have the Length or Count properties.
Attempting to access these members returns
$null .

The following examples demonstrate this feature.

Zero objects
PowerShell

$a = $null

$a.Count

$a.Length

Output

One object
PowerShell

$a = 4

$a.Count

$a.Length

$a[0]

$a[-1]

Output

Indexing .NET types that implement


IDictionary<TKey, TValue>
PowerShell doesn't call a type's true indexer for types that implement the
generic
IDictionary<TKey, TValue> interface. Instead, when given a key,
PowerShell tests for the

existence of the key using TryGetValue() , which


returns $null when the key doesn't
exist.

By contrast, if you call the type's true indexer using Item(<key>) , the
method throws an
exception when the key doesn't exist.

The following example illustrates the difference.

PowerShell

PS> [Collections.Generic.Dictionary[string, int]]::new()['nosuchkey']

# No output ($null)

PS> [Collections.Generic.Dictionary[string, int]]::new().Item('nosuchkey')

Exception getting "Item": "The given key 'nosuchkey' was not present in the
dictionary."

At line:1 char:1

+ [Collections.Generic.Dictionary[string, int]]::new().Item('nosuchkey' ...

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : NotSpecified: (:) [], GetValueInvocationException

+ FullyQualifiedErrorId : ExceptionWhenGetting

Member-access enumeration
Starting in PowerShell 3.0, when you use the member-access operator to access a
member that doesn't exist on a list collection, PowerShell automatically
enumerates the
items in the collection and attempts to access the specified
member on each item. For
more information, see
about_Member-Access_Enumeration.

Examples
The following example creates two new files and stores the resulting objects in
the array
variable $files . Since the array object doesn't have the
LastWriteTime member, the
value of LastWriteTime is returned for each
item in the array.
PowerShell

$files = (New-Item -Type File -Force '/temp/t1.txt'),

(New-Item -Force -Type File '/temp/t2.txt')

$files.LastWriteTime

Output

Friday, June 25, 2021 1:21:17 PM

Friday, June 25, 2021 1:21:17 PM

Member-access enumeration enables you to get values from items in a


collection, but
not to set values on items in a collection. For example:

PowerShell

$files.LastWriteTime = (Get-Date).AddDays(-1)

Output

The property 'LastWriteTime' cannot be found on this object. Verify that the

property exists and can be set.

At line:1 char:1

+ $files.LastWriteTime = (Get-Date).AddDays(-1)

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : InvalidOperation: (:) [], RuntimeException

+ FullyQualifiedErrorId : PropertyAssignmentException

To set the values you must use a method.

PowerShell

$files.set_LastWriteTime((Get-Date).AddDays(-1))

$files.LastWriteTime

Output

Thursday, June 24, 2021 1:23:30 PM

Thursday, June 24, 2021 1:23:30 PM

The set_LastWriteTime() method is a hidden member of the FileInfo


object. The
following example shows how to find members that have a hidden
set method.

PowerShell
$files | Get-Member | Where-Object Definition -like '*set;*'

Output

TypeName: System.IO.FileInfo

Name MemberType Definition

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

Attributes Property System.IO.FileAttributes Attributes {get;set;}

CreationTime Property datetime CreationTime {get;set;}

CreationTimeUtc Property datetime CreationTimeUtc {get;set;}

IsReadOnly Property bool IsReadOnly {get;set;}

LastAccessTime Property datetime LastAccessTime {get;set;}

LastAccessTimeUtc Property datetime LastAccessTimeUtc {get;set;}

LastWriteTime Property datetime LastWriteTime {get;set;}

LastWriteTimeUtc Property datetime LastWriteTimeUtc {get;set;}

U Caution

Since the method is executed for each item in the collection, care should be
taken
when calling methods using member enumeration.

See also
about_For
about_ForEach
about_Hash_Tables
about_Member-Access_Enumeration
about_Operators
about_Assignment_Operators
about_While
about_Assignment_Operators
Article • 09/19/2022 • 15 minutes to read

Short description
Describes how to use operators to assign values to variables.

Long description
Assignment operators assign one or more values to a variable. The equals sign
( = ) is the
PowerShell assignment operator. PowerShell also has the following
compound
assignment operators: += , -= , *= , %= , ++ , -- . Compound
assignment operators
perform numeric operations on the values before the
assignment.

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 be a number or it must be convertible to a


number.

Using the assignment operator


Variables are named memory spaces that store values. You store the values in
variables
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. For example, the
following statement assigns the value PowerShell to the
$MyShell variable:

PowerShell

$MyShell = "PowerShell"

When you assign a value to a variable in PowerShell, the variable is created if


it didn't
already exist. For example, the first of the following two
assignment 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:

PowerShell

$a = 6

$a = 12

Variables in PowerShell don't 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:

PowerShell

$a = Get-Process

$a += Get-Service

$a += "string"

$a += 12

Because the assignment operator = has a lower precedence than the pipeline
operator
| , parentheses aren't 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:

PowerShell

$a = Get-Service | Sort-Object -Property name

You can also assign the value created by a statement to a variable, as in the
following
example:

PowerShell

$a = if ($b -lt 0) { 0 } else { $b }

This example assigns zero to the $a variable if the value of $b is less


than zero. It
assigns the value of $b to $a if the value of $b isn't
less than zero.

To assign an array (multiple values) to a variable, separate the values


with commas, as
follows:

PowerShell

$a = "apple", "orange", "lemon", "grape"

To assign a hash table to a variable, use the standard hash table notation in
PowerShell.
Type an at sign @ followed by key/value pairs that are separated
by semicolons ; and
enclosed in braces { } . For example, to assign a
hashtable to the $a variable, type:

PowerShell

$a = @{one=1; two=2; three=3}

To assign hexadecimal values to a variable, precede the value with 0x .


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:

PowerShell

$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:

PowerShell

$a = 3.1415e3

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:

PowerShell

$a = 10kb

Using compound assignment operators


Compound assignment operators perform numeric operations on the values before
the
assignment.

) Important

Compound assignment operators do not use dynamic scoping. The variable is


always in the current scope. In the following example, the variable $x is
defined in
the global scope. The braces create a new scope. The variable $x
inside the braces
is a new instance and not a reference to the global
variable.

PowerShell

$x = 1 # Global scope

& { $x += 1; $x }

Output

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:

PowerShell

$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:
PowerShell

$a = 4

$a += 2

$a

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:

PowerShell

$a = "Windows"

$a += " PowerShell"

$a

Output

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:

PowerShell

$a = 1,2,3

$a += 2

$a

Output

and

PowerShell
$a += "String"

$a

Output

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:

PowerShell

$a = @{a = 1; b = 2; c = 3}

$a += @{mode = "write"}

$a

Output

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:

PowerShell

$a = @{a = 1; b = 2; c = 3}

$a += 1

Output
A hash table can only be added to another hash table.

At line:2 char:1

+ $a += 1

+ ~~~~~~~

+ CategoryInfo : InvalidOperation: (:) [], RuntimeException

+ FullyQualifiedErrorId : AddHashTableToNonHashTable

The assignment by subtraction operator


The assignment by subtraction operator -= decrements the value of a variable
by the
value that's specified on the right side of the operator. This operator
can't be used with
string variables, and it can't 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:

PowerShell

$a -= 2

$a = ($a - 2)

The following example shows how to use of the -= operator to decrease the
value of a
variable:

PowerShell

$a = 8

$a -= 2

$a

Output

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:

PowerShell

$a = 1,2,3

$a[2] -= 1

$a

Output

You can't 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.

PowerShell

$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:

PowerShell

$a = 1,2,3

$a

Output

PowerShell

$a[1] = $null

$a

Output

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:
PowerShell

Remove-Variable -Name 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:

PowerShell

$a = 3

$a *= 4

$a

Output

12

In this case, the *= operator combines two operations. First, it multiplies,


and then it
assigns. Therefore, the following statements are equivalent:

PowerShell

$a *= 2

$a = ($a * 2)

When a variable contains a string value, PowerShell appends the specified


number of
strings to the value, as follows:

PowerShell

$a = "file"

$a *= 4

$a

Output

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:

PowerShell

$a[0] *= 2

The assignment by division operator


The assignment by division operator /= divides a numeric value by the value
that's
specified on the right side of the operator. The operator can't be
used with string
variables.

The /= operator combines two operations. First, it divides, and then it


assigns.
Therefore, the following two statements are equivalent:

PowerShell

$a /= 2

$a = ($a / 2)

For example, the following command uses the /= operator to divide the value
of a
variable:

PowerShell

$a = 8

$a /=2

$a

Output

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:

PowerShell

$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 can't 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:

PowerShell

$a %= 2

$a = ($a % 2)

The following example shows how to use the %= operator to save the modulus of
a
quotient:

PowerShell

$a = 7

$a %= 4

$a

Output

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:

PowerShell

$a = 7

++$a

$a

Output

To force a value to be returned, enclose the variable and the operator in


parentheses, as
follows:

PowerShell

$a = 7

(++$a)

Output

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:

PowerShell

$a = 7

$c = ++$a

$a

Output

PowerShell

$c

Output

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:
PowerShell

$a = 7

$c = $a++

$a

Output

PowerShell

$c

Output

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:

PowerShell

$a = 7

--$a

$a

Output

PowerShell

(--$a)

Output

The prefix version of the operator decrements a variable before its value is
used in the
statement, as follows:
PowerShell

$a = 7

$c = --$a

$a

Output

PowerShell

$c

Output

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:

PowerShell

$a = 7

$d = $a--

$a

Output

PowerShell

$d

Output

Microsoft .NET types


By default, when a variable has only one value, the value that's assigned to
the variable
determines the data type of the variable. For example, the
following command creates a
variable that has the System.Int32 type:

PowerShell

$a = 6

To find the .NET type of a variable, use the GetType method and its
FullName property.
Be sure to include the parentheses after the GetType
method name, even though the
method call has no arguments:

PowerShell

$a = 6

$a.GetType().FullName

Output

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:

PowerShell

$a = "6"

$a.GetType().FullName

Output

System.String

If the first value that's assigned to the variable is a string, PowerShell


treats all
operations as string operations and casts new values to strings.
This occurs in the
following example:

PowerShell

$a = "file"

$a += 3

$a

Output

file3

If the first value is an integer, PowerShell treats all operations as integer


operations and
casts new values to integers. This occurs in the following
example:

PowerShell

$a = 6

$a += "3"

$a

Output

You can cast a new scalar variable as any .NET 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 are defining the type of data that can be stored
in the variable.

For example, the following command casts the variable as a string type:

PowerShell

[string]$a = 27

$a += 3

$a

Output

273

The following example casts the first value, instead of casting the variable:

PowerShell

$a = [string]27

You can't recast the data type of an existing variable if its value can't be
converted to the
new data type.

PowerShell
$a = "string"

[int]$a

Output

InvalidArgument: Cannot convert value "string" to type "System.Int32".


Error:

"The input string 'string' was not in a correct format."

To change the data type, you must replace its value, as follows:

PowerShell

[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's incompatible with the
existing type, and you don't explicitly
override the type, PowerShell displays
an error, as shown in the following example:

PowerShell

$a = 3

$a = "string"

[int]$a = 3

$a = "string"

Output

Cannot convert value "string" to type "System.Int32". Error: "Input string


was not in a correct format."

At line:4 char:1

+ $a = "string"

+ ~~~~~~~~~~~~~

+ CategoryInfo : MetadataError: (:) [],


ArgumentTransformationMetadataException

+ FullyQualifiedErrorId : RuntimeException

PowerShell

[string]$a = "string"

In 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:

PowerShell

[string []] $a = "one", "two", "three"

PowerShell variables can be any .NET data type. In addition, you can assign any
fully
qualified .NET data type that's available in the current process. For
example, the
following command specifies a System.DateTime data type:

PowerShell

[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:

Output

Tuesday, May 31, 2005 12:00:00 AM

Assigning multiple variables


In PowerShell, you can assign values to multiple variables 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. This is
known as multiple assignment.

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:

PowerShell

$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:
PowerShell

$a, $b, $c = 1, 2, 3, 4, 5

Therefore, 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:

PowerShell

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

If the assignment value contains fewer elements than variables, the


remaining variables
are assigned the value $null . For example, the
following command contains three
variables and two values:

PowerShell

$a, $b, $c = 1, 2

Therefore, PowerShell assigns the value 1 to the $a variable and the value 2
to the $b
variable. The $c variable is $null .

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:

PowerShell

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

PowerShell

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
Article • 05/08/2023

Short description
Describes variables that store state information for and are created and
maintained by
PowerShell.

Long description
Conceptually, most of these variables are considered to be read-only. Even
though they
can be written to, for backward compatibility they should not
be written to.

Here is a list of the automatic variables in PowerShell:

$$
Contains the last token in the last line received by the session.

$?
Contains the execution status of the last command. It contains True if the
last command
succeeded and False if it failed.

For cmdlets and advanced functions that are run at multiple stages in a
pipeline, for
example in both process and end blocks, calling
this.WriteError() or
$PSCmdlet.WriteError() respectively at any point sets
$? to False, as does

this.ThrowTerminatingError() and
$PSCmdlet.ThrowTerminatingError() .

The Write-Error cmdlet always sets $? to False immediately after it's


executed, but
won't set $? to False for a function calling it:

PowerShell

function Test-WriteError

Write-Error "Bad"

"The `$? variable is: $?"

Test-WriteError

"Now the `$? variable is: $?"

Output

Test-WriteError : Bad

At line:7 char:1

+ Test-WriteError

+ ~~~~~~~~~~~~~~~

+ CategoryInfo : NotSpecified: (:) [Write-Error],


WriteErrorException

+ FullyQualifiedErrorId :
Microsoft.PowerShell.Commands.WriteErrorException,Test-WriteError

The $? variable is: False

Now the $? variable is: True

For the latter purpose, $PSCmdlet.WriteError() should be used instead.

For native commands (executables), $? is set to True when $LASTEXITCODE


is 0, and set
to False when $LASTEXITCODE is any other value.

7 Note

Until PowerShell 7, wrapping a statement within parentheses (...) ,


subexpression
syntax $(...) , or an array expression @(...) always reset
$? to True. For example,
(Write-Error) shows $? as True. This
behavior changed in PowerShell 7, so that

$? always reflects the actual


success of the last command run in these expressions.

$^
Contains the first token in the last line received by the session.

$_
Same as $PSItem . Contains the current object in the pipeline object. You can
use this
variable in commands that perform an action on every object in a
pipeline.

For more information, see about_PSItem.

$args
Contains an array of values for undeclared parameters that are passed to a
function,
script, or script block. When you create a function, you can declare
the parameters with
the param keyword or by adding a comma-separated list of
parameters in parentheses
after the function name.

In an event action, the $args variable contains objects that represent the
event
arguments of the event that's 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 object that Get-Event returns.

$ConsoleFileName
Contains the path of the console file ( .psc1 ) that was most recently used in
the session.
This variable is populated when you start 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 the file to update.

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

To prevent an error from being added to the $Error array, use the
ErrorAction common
parameter with a value of Ignore. For more
information, see about_CommonParameters.

$Event
Contains a PSEventArgs object that represents the event that's 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. You can use
the properties of the Event variable, such as

$Event.TimeGenerated , in an
Action script block.

$EventArgs
Contains an object that represents the first event argument that derives from
EventArgs
of the event that's 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 SourceEventArgs property of the
PSEventArgs object that Get-Event returns.
$EventSubscriber
Contains a PSEventSubscriber object that represents the event subscriber of
the event
that's 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
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's
converted to a non-empty string or to a
non-zero integer.

$foreach
Contains the enumerator (not the resulting values) of a ForEach loop. The
$ForEach
variable exists only while the ForEach loop is running; it's
deleted after the loop is
completed.

Enumerators contain properties and methods you can use to retrieve loop values
and
change the current loop iteration. For more information, see
Using Enumerators.

$HOME
Contains the full path of the user's home directory. This variable uses the
value of the
"$env:USERPROFILE" Windows environment variable, typically
C:\Users\<UserName> .

) Important

Windows can redirect the location of the user's profile. This means that
$HOME may
not have the same value as $env:HOMEDRIVE$env:HOMEPATH .

$Host
Contains an object that represents the current host application for 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.BackGroundColor = "Red" .

$input
Contains an enumerator that enumerates all input that's passed to a function.
The
$input variable is available only to functions and script blocks (which
are unnamed
functions).

In a function without a begin , process , or end block, the $input


variable
enumerates the collection of all input to the function.

In the begin block, the $input variable contains no data.

In the process block, the $input variable contains the current object in
the
pipeline.

In the end block, the $input variable enumerates the collection of all
input to the
function.

7 Note

You can't use the $input variable inside both the process block and the
end
block in the same function or script block.

Since $input is an enumerator, accessing any of its properties causes


$input to no
longer be available. You can store $input in another variable
to reuse the $input
properties.

Enumerators contain properties and methods you can use to retrieve loop values
and
change the current loop iteration. For more information, see
Using Enumerators.

The $input variable is also available to the command specified by the


-Command
parameter of powershell.exe when invoked from the command line.
The following
example is run from the Windows Command shell.

CMD

echo Hello | powershell -Command """$input World!"""

$LASTEXITCODE
Contains the exit code of the last native program or PowerShell script that
ran.

For PowerShell scripts, the value of $LASTEXITCODE depends on how the script
was called
and whether the exit keyword was used:

When a script uses the exit keyword:

$LASTEXITCODE is set to value the specified by the exit keyword. For more

information, see about_Language_Keywords.

When a script is called directly, like ./Test.ps1 , or with the


call operator ( & ) like &
./Test.ps1 :

The value of $LASTEXITCODE isn't changed unless:


The script calls another script that uses the exit keyword
The script calls a native command
The script uses the exit keyword

When a script is called with powershell.exe using the File parameter,


$LASTEXITCODE is set to:
1 if the script terminated due to an exception

The value specified by the exit keyword, if used in the script


0 if the script completed successfully

When a script is called with powershell.exe using the Command


parameter,
$LASTEXITCODE is set to:
1 if the script terminated due to an exception or if the result of the
last

command set $? to $false


0 if the script completed successfully and the result of the last command
set $?

to $true

For more information on the File and Command parameters, see


about_PowerShell_exe.

$Matches
The $Matches variable works with the -match and -notmatch 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.
The $Matches hash table can also be
populated with captures when you use
regular expressions with the -match operator.
For more information about the -match operator, see
about_Comparison_Operators. For
more information on regular expressions,
see about_Regular_Expressions.

The $Matches variable also works in a switch statement with the -Regex
parameter. It's
populated the same way as the -match and -notmatch
operators. For more information
about the switch statement, see
about_Switch.

7 Note

When $Matches is populated in a session, it retains the matched value until


it's
overwritten by another match. If -match is used again and no match is
found, it
doesn't reset $Matches to $null . The previously matched value
is kept in $Matches
until another match is found.

$MyInvocation
Contains information about the current command, such as the name, parameters,
parameter values, and information about how the command was started, called, or
invoked, such as the name of the script that called the current command.

$MyInvocation is populated only for scripts, function, and script blocks. You
can use the
information in the System.Management.Automation.InvocationInfo
object that
$MyInvocation returns in the current script, such as the name of
a function
( $MyInvocation.MyCommand.Name ) to identify the current command.
This is useful for
finding the name of the current script.

Beginning in PowerShell 3.0, MyInvocation has the following new properties.

PSScriptRoot - Contains the full path to the script that invoked the
current
command. The value of this property is populated only when the caller
is a script.
PSCommandPath - Contains the full path and filename of the script that
invoked
the current command. The value of this property is populated only
when the caller
is a script.

Unlike the $PSScriptRoot and $PSCommandPath automatic variables, the


PSScriptRoot
and PSCommandPath properties of the $MyInvocation
automatic variable contain
information about the invoker or calling script, not
the current script.

$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, PowerShell presents a nested command prompt when you use the
$Host.EnterNestedPrompt method. PowerShell also presents a nested command
prompt
when you reach a breakpoint in the PowerShell debugger.

When you enter a nested prompt, 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 PowerShell command prompt that includes this value so
that it's always
visible.

$null
$null is an automatic variable that contains a null or empty value. You
can use this

variable to represent an absent or undefined value in commands and


scripts.

PowerShell treats $null as an object with a value, or a placeholder, so you


can use
$null to represent an empty value in a collection of values.

For example, when $null is included in a collection, it's counted as one of


the objects.

PowerShell

$a = "one", $null, "three"

$a.count

Output

If you pipe the $null variable to the ForEach-Object cmdlet, it generates a


value for
$null , just as it does for the other objects

PowerShell

"one", $null, "three" | ForEach-Object { "Hello " + $_}

Output

Hello one

Hello

Hello three

As a result, you can't use $null to mean no parameter value. A parameter


value of
$null overrides the default parameter value.

However, because PowerShell treats the $null variable as a placeholder, you


can use it
in scripts like the following one, which wouldn't work if $null
were ignored.

PowerShell

$calendar = @($null, $null, "Meeting", $null, $null, "Team Lunch", $null)

$days = "Sunday","Monday","Tuesday","Wednesday","Thursday",

"Friday","Saturday"

$currentDay = 0

foreach($day in $calendar)

if($day -ne $null)

"Appointment on $($days[$currentDay]): $day"

$currentDay++

Output

Appointment on Tuesday: Meeting

Appointment on Friday: Team lunch

$PID
Contains the process identifier (PID) of the process that's hosting the
current PowerShell
session.

$PROFILE
Contains the full path of the 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:

PowerShell
Test-Path $PROFILE

Or, you can use it in a command to create a profile:

PowerShell

New-Item -ItemType file -Path $PROFILE -Force

You can use it in a command to open the profile in notepad.exe:

PowerShell

notepad.exe $PROFILE

$PSBoundParameters
Contains a dictionary of the parameters that are passed to a script or function
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.

In this example, the Test2 function passes the $PSBoundParameters to the


Test1 function.
The $PSBoundParameters are displayed in the format of
Key and Value.

PowerShell

function Test1 {

param($a, $b)

# Display the parameters in dictionary format.

$PSBoundParameters

function Test2 {

param($a, $b)

# Run the Test1 function with $a and $b.

Test1 @PSBoundParameters

PowerShell

Test2 -a Power -b Shell

Output

Key Value

--- -----

a Power

b Shell

$PSCmdlet
Contains an object that represents the cmdlet or advanced function that's 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's 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_CmdletBindingAttribute and
about_Functions_Advanced.

$PSCommandPath
Contains the full path and filename of the script that's being run. This
variable is valid in
all scripts.

$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, currency, and
dates, and is
stored in a System.Globalization.CultureInfo object. Use
Get-Culture to display the
computer's culture. $PSCulture contains the
Name property's value.

$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 determine 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's being debugged.

$PSEdition
Contains the same value in $PSVersionTable.PSEdition . This variable is
available for use
in module manifest files, whereas $PSVersionTable isn't.

$PSHOME
Contains the full path of the installation directory for PowerShell, typically,
$env:windir\System32\PowerShell\v1.0 in Windows systems. You can use this
variable in
the paths of PowerShell files. For example, the following command
searches the
conceptual Help topics for the word variable:

PowerShell

Select-String -Pattern Variable -Path $pshome\*.txt

$PSItem
Same as $_ . Contains the current object in the pipeline object. You can use
this variable
in commands that perform an action on every object in a pipeline.

For more information, see about_PSItem.

$PSScriptRoot
Contains the full path of the executing script's parent directory.

In PowerShell 2.0, this variable is valid only in script modules ( .psm1 ).


Beginning in
PowerShell 3.0, it's valid in all scripts.

$PSSenderInfo
Contains information about the user who started the PSSession, including the
user
identity and the time zone of the originating computer. This variable is
available only in
PSSessions.

The $PSSenderInfo variable includes a user-configurable property,


ApplicationArguments, that by default, contains only the $PSVersionTable
from the
originating session. To add data to the ApplicationArguments
property, use the
ApplicationArguments parameter of the
New-PSSessionOption cmdlet.

$PSUICulture
Contains the name of the user interface (UI) culture that's configured 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
PowerShell
that's running in the current session. The table includes the
following items:

BuildVersion - The build number of the current version


CLRVersion - The version of the common language runtime (CLR)
PSCompatibleVersions - Versions of PowerShell that are compatible with
the
current version
PSEdition - This property has the value of 'Desktop', for Windows Server
and
Windows client versions. This property has the value of 'Core' for
PowerShell
running under Nano Server or Windows IoT.
PSRemotingProtocolVersion - The version of the PowerShell remote
management
protocol.
PSVersion - The PowerShell version number
SerializationVersion - The version of the serialization method
WSManStackVersion - The version number of the WS-Management stack

$PWD
Contains a path object that represents the full path of the current directory
location for
the current PowerShell runspace.

7 Note

PowerShell supports multiple runspaces per process. Each runspace has its own
current directory. This isn't the same as the current directory of the
process:
[System.Environment]::CurrentDirectory .

$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 object
that Get-Event returns.

$ShellId
Contains the identifier of the current shell.

$StackTrace
Contains a stack trace for the most recent error.

$switch
Contains the enumerator not the resulting values of a Switch statement. The
$switch
variable exists only while the Switch statement is running; it's
deleted when the switch
statement completes execution. For more information,
see about_Switch.

Enumerators contain properties and methods you can use to retrieve loop values
and
change the current loop iteration. For more information, see
Using Enumerators.

$this
The $this variable is used in script blocks that extend classes to refer to
the instance of
the class itself.

PowerShell's Extensible Type System (ETS) allows you to add properties to


classes using
script blocks. In a script block that defines a script property
or script method, the $this
variable refers to an instance of object of the
class that's being extended. For example,
PowerShell uses ETS to add the
BaseName property to the FileInfo class.

PowerShell

PS> Get-ChildItem .\README.md | Get-Member BaseName | Format-List

TypeName : System.IO.FileInfo

Name : BaseName

MemberType : ScriptProperty

Definition : System.Object BaseName {get=if ($this.Extension.Length -gt 0)

{$this.Name.Remove($this.Name.Length - $this.Extension.Length

)}else{$this.Name};}

For more information, see about_Types.ps1xml.


In a PowerShell class, the $this variable refers to the instance object of
the class itself,
allowing access to properties and methods defined in the
class. For more information,
see about_Classes.

The $this variable is also used by .NET event classes that take script blocks
as delegates
for the event handler. In this scenario, $this represents the
object originating the event,
known as the event sender.

$true
Contains True. You can use this variable to represent True in commands
and scripts.

Using Enumerators
The $input , $foreach , and $switch variables are all enumerators used to
iterate
through the values processed by their containing code block.

An enumerator contains properties and methods you can use to advance or reset
iteration, or retrieve iteration values. Directly manipulating enumerators
isn't considered
best practice.

Within loops, flow control keywords break and continue should be


preferred.

Within functions that accept pipeline input, it's best practice to use
parameters
with the ValueFromPipeline or
ValueFromPipelineByPropertyName attributes.

For more information, see about_Functions_Advanced_Parameters.

MoveNext
The MoveNext method
advances the enumerator to the next element of the collection.
MoveNext
returns True if the enumerator was successfully advanced, False if the
enumerator has passed the end of the collection.

7 Note

The Boolean value returned by MoveNext is sent to the output stream.


You can
suppress the output by typecasting it to [void] or piping it to
Out-Null.

PowerShell

$input.MoveNext() | Out-Null

PowerShell

[void]$input.MoveNext()

Reset
The Reset method sets the enumerator to its initial position, which is
before the first
element in the collection.

Current
The Current property gets the element in the collection, or pipeline, at
the current
position of the enumerator.

The Current property continues to return the same property until


MoveNext is called.

Examples

Example 1: Using the $input variable


In the following example, accessing the $input variable clears the variable
until the next
time the process block executes. Using the Reset method
resets the $input variable to
the current pipeline value.

PowerShell

function Test

begin

$i = 0

process

"Iteration: $i"

$i++

"`tInput: $input"

"`tAccess Again: $input"

$input.Reset()

"`tAfter Reset: $input"

"one","two" | Test

Output

Iteration: 0

Input: one

Access Again:

After Reset: one

Iteration: 1

Input: two

Access Again:

After Reset: two

The process block automatically advances the $input variable even if you
don't access
it.

PowerShell

$skip = $true

function Skip

begin

$i = 0

process

"Iteration: $i"

$i++

if ($skip)

"`tSkipping"

$skip = $false

else

"`tInput: $input"

"one","two" | Skip

Output

Iteration: 0

Skipping

Iteration: 1

Input: two

Example 2: Using $input outside the process block


Outside of the process block the $input variable represents all the values
piped into the
function.

Accessing the $input variable clears all values.


The Reset method resets the entire collection.
The Current property is never populated.
The MoveNext method returns false because the collection can't be
advanced.
Calling MoveNext clears out the $input variable.

PowerShell

Function All

"All Values: $input"

"Access Again: $input"

$input.Reset()

"After Reset: $input"

$input.MoveNext() | Out-Null

"After MoveNext: $input"

"one","two","three" | All

Output

All Values: one two three

Access Again:

After Reset: one two three

After MoveNext:

Example 3: Using the $input.Current property


With the Current property, the current pipeline value can be accessed
multiple times
without using the Reset method. The process block doesn't
automatically call the
MoveNext method.

The Current property is never populated unless you explicitly call


MoveNext. The
Current property can be accessed multiple times inside
the process block without
clearing its value.
PowerShell

function Current

begin

$i = 0

process

"Iteration: $i"

$i++

"`tBefore MoveNext: $($input.Current)"

$input.MoveNext() | Out-Null

"`tAfter MoveNext: $($input.Current)"

"`tAccess Again: $($input.Current)"

"one","two" | Current

Output

Iteration: 0

Before MoveNext:

After MoveNext: one

Access Again: one

Iteration: 1

Before MoveNext:

After MoveNext: two

Access Again: two

Example 4: Using the $foreach variable


Unlike the $input variable, the $foreach variable always represents all
items in the
collection when accessed directly. Use the Current property to
access the current
collection element, and the Reset and MoveNext
methods to change its value.

7 Note

Each iteration of the foreach loop automatically calls the MoveNext


method.

The following loop only executes twice. In the second iteration, the collection
is moved
to the third element before the iteration is complete. After the
second iteration, there
are now no more values to iterate, and the loop
terminates.
The MoveNext property doesn't affect the variable chosen to iterate through
the
collection ( $Num ).

PowerShell

$i = 0

foreach ($num in ("one","two","three"))

"Iteration: $i"

$i++

"`tNum: $num"

"`tCurrent: $($foreach.Current)"

if ($foreach.Current -eq "two")

"Before MoveNext (Current): $($foreach.Current)"

$foreach.MoveNext() | Out-Null

"After MoveNext (Current): $($foreach.Current)"

"Num hasn't changed: $num"

Output

Iteration: 0

Num: one

Current: one

Iteration: 1

Num: two

Current: two

Before MoveNext (Current): two

After MoveNext (Current): three

Num hasn't changed: two

Using the Reset method resets the current element in the collection. The
following
example loops through the first two elements twice because the
Reset method is called.
After the first two loops, the if statement fails
and the loop iterates through all three
elements normally.

) Important

This could result in an infinite loop.

PowerShell

$stopLoop = 0

foreach ($num in ("one","two", "three"))

("`t" * $stopLoop) + "Current: $($foreach.Current)"

if ($num -eq "two" -and $stopLoop -lt 2)

$foreach.Reset() | Out-Null

("`t" * $stopLoop) + "Reset Loop: $stopLoop"

$stopLoop++

Output

Current: one

Current: two

Reset Loop: 0

Current: one

Current: two

Reset Loop: 1

Current: one

Current: two

Current: three

Example 5: Using the $switch variable


The $switch variable has the exact same rules as the $foreach variable. The
following
example demonstrates all the enumerator concepts.

7 Note

Note how the NotEvaluated case is never executed, even though there's
no break
statement after the MoveNext method.

PowerShell

$values = "Start", "MoveNext", "NotEvaluated", "Reset", "End"

$stopInfinite = $false

switch ($values)

"MoveNext" {

"`tMoveNext"

$switch.MoveNext() | Out-Null

"`tAfter MoveNext: $($switch.Current)"

# This case is never evaluated.

"NotEvaluated" {

"`tAfterMoveNext: $($switch.Current)"

"Reset" {

if (!$stopInfinite)

"`tReset"

$switch.Reset()

$stopInfinite = $true

default {

"Default (Current): $($switch.Current)"

Output

Default (Current): Start

MoveNext

After MoveNext: NotEvaluated

Reset

Default (Current): Start

MoveNext

After MoveNext: NotEvaluated

Default (Current): End

See also
about_Functions
about_Functions_Advanced
about_Functions_Advanced_Methods
about_Functions_Advanced_Parameters
about_Functions_OutputTypeAttribute
about_Functions_CmdletBindingAttribute
about_Hash_Tables
about_Preference_Variables
about_Splatting
about_Variables
about_Booleans
Article • 03/02/2023 • 2 minutes to read

Short description
Describes how boolean expressions are evaluated.

Long description
PowerShell can implicitly treat any type as a Boolean. It is important to
understand the
rules that PowerShell uses to convert other types to Boolean
values.

Converting from scalar types


A scalar type is an atomic quantity that can hold only one value at a time. The
following
types evaluate to $false :

Empty strings like '' or ""


Null values like $null
Any numeric type with the value of 0

Examples:

PowerShell

PS> $false -eq ''

True

PS> if ("") { $true } else { $false }

False

PS> if ($null) { $true } else { $false }

False

PS> if ([int]0) { $true } else { $false }

False

PS> if ([double]0.0) { $true } else { $false }

False

The following types evaluate to $true :

Non-empty strings
Instances of any other non-collection type

Examples:
PowerShell

# a non-collection type

PS> [bool]@{value = 0}

True

# non-empty strings

PS> if ('hello') { $true } else { $false }

True

PS> [bool]'False'

True

Note that this differs from explicit string parsing:

PowerShell

PS> [bool]::Parse('false')

False

PS> [bool]::Parse('True')

True

PS> [bool]::Parse('Not True')

MethodInvocationException: Exception calling "Parse" with "1" argument(s):

"String 'Not True' was not recognized as a valid Boolean."

Converting from collection types


Arrays are the most common collection type in PowerShell. These rules apply to
any
collection-like types that implement the
IList interface.

Empty collections are always $false


The special null value indicating the absence of output from a command,
[System.Management.Automation.Internal.AutomationNull]::Value is always
$false .

Single-element collections evaluate to the Boolean value of their one and


only
element.
Collections with more than 1 element are always $true .

Examples:

PowerShell

# Empty collections

PS> [bool]@()

False

PS> [bool](Get-ChildItem | Where-Object Name -eq 'Non-existent-File.txt')

False

# Single-element collections

PS> $a = @(0)

PS> [bool]$a

False

PS> $b = @(1)

PS> [bool]$b

True

# Multi-element collections

PS> $c = @(0,0)

PS> [bool]$c

True

See also
about_Arrays
about_Break
Article • 03/02/2023 • 5 minutes to read

Short description
Describes a the break statement, which provides a way to exit the current
control block.

Long description
The break statement provides a way to exit the current control block.
Execution
continues at the next statement after the control block. The
statement supports labels. A
label is a name you assign to a statement in a
script.

Using break in loops


When a break statement appears in a loop, such as a foreach , for , do ,
or while loop,
PowerShell immediately exits the loop.

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.

The following example shows how to use a break statement to exit a for
statement:

PowerShell

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, 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:

PowerShell

$i=0

$varB = 10,20,30,40

foreach ($val in $varB) {

if ($val -eq 30) {

break

$i++

Write-Host "30 was found in array index $i"

In this example, the foreach statement iterates the $varB array. The if
statement
evaluates to False the first two times the loop is run and the
variable $i is incremented
by 1. The third time the loop is run, $i equals
2, and the $val variable equals 30. At this
point, the break statement
runs, and the foreach loop exits.

Using a labeled break in a loop


A break statement can include a label. If you use the break keyword with a
label,
PowerShell exits the labeled loop instead of exiting the current loop.
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 .

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
example has a while
statement with a for statement:

PowerShell

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

PowerShell
:red while (<condition1>) {

:yellow while (<condition2>) {

while (<condition3>) {

if ($a) {break}

if ($b) {break red}

if ($c) {break yellow}

Write-Host "After innermost loop"

Write-Host "After yellow loop"

Write-Host "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.

PowerShell does not limit how far labels can resume execution. The label can
even pass
control across script and function call boundaries.

Using break in a switch statement


In a switch construct, break causes PowerShell to exit the switch code block.

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:

PowerShell

$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 . Because the variable value and the
first test in the switch statement match,
the first code block in the
switch statement runs.

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

Using break in a trap statement


If the final statement executed in the body of a trap statement is break ,
the error
object is suppressed and the exception is re-thrown.

The following example create a DivideByZeroException exception that is


trapped using
the trap statement.

PowerShell

function test {

trap [DivideByZeroException] {

Write-Host 'divide by zero trapped'

break

$i = 3

'Before loop'

while ($true) {

"1 / $i = " + (1 / $i--)

'After loop'

test

Notice that execution stops at the exception. The After loop is never reached.
The
exception is re-thrown after the trap executes.
Output

Before loop

1 / 3 = 0.333333333333333

1 / 2 = 0.5

1 / 1 = 1

divide by zero trapped

Attempted to divide by zero.

At line:10 char:6

+ "1 / $i = " + (1 / $i--)

+ ~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : NotSpecified: (:) [],


ParentContainsErrorRecordException

+ FullyQualifiedErrorId : RuntimeException

Do not use break outside of a loop, switch , or


trap
When break is used outside of a construct that directly supports it
(loops, switch ,
trap ), PowerShell looks up the call stack for an
enclosing construct. If it can't find an

enclosing construct, the current


runspace is quietly terminated.

This means that functions and scripts that inadvertently use a break outside
of an
enclosing construct that supports it can inadvertently terminate their
callers.

Using break inside a pipeline break , such as a ForEach-Object script


block, not only
exits the pipeline, it potentially terminates the entire
runspace.

See also
about_Comparison_Operators
about_Continue
about_For
about_Foreach
about_Switch
about_Throw
about_Trap
about_Try_Catch_Finally
about_While
about_Built-in_Functions
Article • 01/03/2023 • 2 minutes to read

Short description
Describes the built-in functions in PowerShell.

Long description
PowerShell includes a set of functions that are loaded into every PowerShell
session.
These functions are similar to cmdlets but they're not included in any
module. They're
defined in the PowerShell engine itself.

These functions are provided as shorthand helpers for common tasks. In many
cases,
these functions call an existing cmdlet with an additional parameter.

cd..
In the Windows CMD shell it's common to run the cd command without any spaces
between the command and the destination path. This function runs
Set-Location .. to
change to the parent folder.

cd\
In the Windows CMD shell it's common to run the cd command without any spaces
between the command and the destination path. This function runs
Set-Location \ to
change to the root folder.

ImportSystemModules
This function has been deprecated. It is an empty function that does nothing.

Pause
This function replicates the behavior of CMD's pause command. The script
pauses
execution and prompts the user to hit a key to continue.
help
This function invokes Get-Help with your parameters and passes the output to
the
systems pager command, more.com .

prompt
This is the function that creates the default prompt for the PowerShell command
line.
You can customize your prompt by overriding this function with your own.
For more
information see about_Prompts.

Clear-Host
This function clears the screen. For more information, see
Clear-Host.

TabExpansion2
This is the default function to use for tab expansion.

Get-Verb
This function lists PowerShell verbs and the category group they belong to. For
more
information, see Get-Verb

oss
This function provides a short hand way to run Out-String -Stream in a
pipeline.

mkdir
This function provides a short hand way to run New-Item -Type Directory with
your
parameters.

Windows drive letter functions


In Windows, drive mount points are associated with a drive letter like C: .
You can switch
to the current location on another drive just by entering that
drive letter on the
command line.
PowerShell create a function for every possible drive letter, A: through
Z: .
about_Calculated_Properties
Article • 03/24/2023 • 7 minutes to read

Short description
PowerShell provides the ability to dynamically add new properties and alter
the
formatting of objects output to the pipeline.

Long description
Several PowerShell cmdlets transform, group, or process input objects into
output
objects using parameters that allow the addition of new properties to
those output
objects. You can use these parameters to generate new, calculated
properties on output
objects based on the values of input objects. The
calculated property is defined by a
hashtable
containing key-value pairs that specify the name of the new property, an
expression to calculate the value, and optional formatting information.

Supported cmdlets
The following cmdlets support calculated property values for the Property
parameter.
The Format-* cmdlets also support calculated values for the
GroupBy parameter.

The following list itemizes the cmdlets that support calculated properties and
the key-
value pairs that each cmdlet supports.

Compare-Object

expression

ConvertTo-Html

name / label - optional (added in PowerShell 6.x)

expression
width - optional

alignment - optional

Format-Custom

expression

depth - optional

Format-List
name / label - optional

expression
formatstring - optional

This same set of key-value pairs also apply to calculated property values
passed to
the GroupBy parameter for all Format-* cmdlets.

Format-Table

name / label - optional


expression

formatstring - optional
width - optional

alignment - optional

Format-Wide
expression

formatstring - optional

Group-Object

expression

Measure-Object
Only supports a script block for the expression, not a hashtable.
Not supported in PowerShell 5.1 and older.

Select-Object

name / label - optional


expression

Sort-Object

expression
ascending / descending - optional

7 Note

The value of the expression can be a script block instead of a


hashtable. For more
information, see the Notes section.

Hashtable key definitions


name / label - Specifies the name of the property being created. You can
use name

or its alias, label , interchangeably.


expression - A string or script block used to calculate the value of the
new

property. If the expression is a string, the value is interpreted as a


property name
on the input object. This is a shorter option than
expression = { $_.
<PropertyName> } .

alignment - Used by cmdlets that produce tabular output to define how the
values
are displayed in a column. The value must be 'left' , 'center' , or
'right' .
formatstring - Specifies a format string that defines how the value is
formatted for
output. For more information about format strings, see
Format types in .NET.
width - Specifies the maximum width column in a table when the value is

displayed. The value must be greater than 0 .


depth - The Depth parameter of Format-Custom specifies the depth of
expansion

for all properties. The depth key allows you to specify the
depth of expansion per
property.
ascending / descending - Allows you to specify the order of sorting for
one or

more properties. These are boolean values.

You don't need to spell out the hashtable keys as long as the specified name
prefix is
unambiguous. For example, you can use n instead of Name and e
instead of
Expression .

Examples

Compare-Object
With calculated properties, you can control how the properties of the input
objects are
compared. In this example, rather than comparing the values
directly, the values are
compared to the result of the arithmetic operation
(modulus of 2).

PowerShell

Compare-Object @{p=1} @{p=2} -property @{ Expression = { $_.p % 2 } }

Output

$_.p % 2 SideIndicator

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

0 =>

1 <=

ConvertTo-Html
ConvertTo-Html can convert a collection of objects to an HTML table.
Calculated
properties allow you to control how the table is presented.

PowerShell

Get-Alias |

ConvertTo-Html Name,

Definition,

@{

expr={$_.Parameters.Keys.Count}

align='center'

} |

Out-File .\aliases.htm -Force

This example creates an HTML table containing a list of PowerShell aliases and
the
number parameters for each aliased command. The values of
ParameterCount column
are centered.

Format-Custom
Format-Custom provides a custom view of an object in a format similar to a
class
definition. More complex objects can contain members that are deeply
nested with
complex types. The Depth parameter of Format-Custom specifies
the depth of expansion
for all properties. The depth key allows you to
specify the depth of expansion per
property.

In this example, the depth key simplifies the custom output for the
Get-Date cmdlet.
Get-Date returns a DateTime object. The Date
property of this object is also a DateTime

object, so the object is nested.

PowerShell

Get-Date | Format-Custom @{expr={$_.Date};depth=1},TimeOfDay

Output

class DateTime

$_.Date =

class DateTime

Date = 8/7/2020 12:00:00 AM


Day = 7

DayOfWeek = Friday

DayOfYear = 220

Hour = 0

Kind = Local

Millisecond = 0

Minute = 0

Month = 8

Second = 0

Ticks = 637323552000000000

TimeOfDay = 00:00:00

Year = 2020

DateTime = Friday, August 07, 2020 12:00:00 AM

TimeOfDay =

class TimeSpan

Ticks = 435031592302

Days = 0

Hours = 12

Milliseconds = 159

Minutes = 5

Seconds = 3

TotalDays = 0.503508787386574

TotalHours = 12.0842108972778

TotalMilliseconds = 43503159.2302

TotalMinutes = 725.052653836667

TotalSeconds = 43503.1592302

Format-List
In this example, we use calculated properties to change the name and format of
the
output from Get-ChildItem .

PowerShell

Get-ChildItem *.json -File |

Format-List Fullname,

@{

name='Modified'

expression={$_.LastWriteTime}

formatstring='O'

},

@{

name='Size'

expression={$_.Length/1KB}

formatstring='N2'

Output

FullName : C:\Git\PS-Docs\PowerShell-Docs\.markdownlint.json

Modified : 2020-07-23T10:26:28.4092457-07:00

Size : 2.40

FullName : C:\Git\PS-Docs\PowerShell-
Docs\.openpublishing.publish.config.json

Modified : 2020-07-23T10:26:28.4092457-07:00

Size : 2.25

FullName : C:\Git\PS-Docs\PowerShell-Docs\.openpublishing.redirection.json

Modified : 2020-07-27T13:05:24.3887629-07:00

Size : 324.60

Format-Table
In this example, the calculated property adds a Type property used to
classify the files
by the content type.

PowerShell

Get-ChildItem -File |

Sort-Object extension |

Format-Table Name, Length -GroupBy @{

name='Type'

expression={

switch ($_.extension) {

'.md' {'Content'}

'' {'Metacontent'}

'.ps1' {'Automation'}

'.yml' {'Automation'}

default {'Configuration'}

Output

Type: Metacontent

Name Length

---- ------

ThirdPartyNotices 1229

LICENSE-CODE 1106

LICENSE 19047

Type: Configuration

Name Length

---- ------

.editorconfig 183

.gitattributes 419

.gitignore 228

.markdownlint.json 2456

.openpublishing.publish.config.json 2306

.openpublishing.redirection.json 332394

.localization-config 232

Type: Content

Name Length

---- ------

README.md 3355

CONTRIBUTING.md 247

Type: Automation

Name Length

---- ------

.openpublishing.build.ps1 796

build.ps1 7495

ci.yml 645

ci-steps.yml 2035

daily.yml 1271

Format-Wide
The Format-Wide cmdlet allows you to display the value of one property for
objects in a
collection as a multi-column list.

For this example, we want to see the filename and the size (in kilobytes) as a
wide
listing. Since Format-Wide doesn't display more than one property, we
use a calculated
property to combine the value of two properties into a single
value.

PowerShell

Get-ChildItem -File |

Format-Wide -Property @{e={'{0} ({1:N2}kb)' -f $_.name,($_.length/1kb)}}

Output

.editorconfig (0.18kb) .gitattributes (0.41kb)

.gitignore (0.22kb) .localization-config


(0.23kb)

.markdownlint.json (2.40kb) .openpublishing.build.ps1


(0.78kb)

.openpublishing.publish.config.json (2.25kb)
.openpublishing.redirection.json (324.60kb)

build.ps1 (7.32kb) ci.yml (0.63kb)

ci-steps.yml (1.99kb) CONTRIBUTING.md (0.24kb)

daily.yml (1.24kb) LICENSE (18.60kb)

LICENSE-CODE (1.08kb) README.md (3.28kb)

ThirdPartyNotices (1.20kb)

Group-Object
The Group-Object cmdlet displays objects in groups based on the value of a
specified
property. In this example, the calculated property counts the number
of files of each
content type.

PowerShell

Get-ChildItem -File |

Sort-Object extension |

Group-Object -NoElement -Property @{

expression={

switch ($_.extension) {

'.md' {'Content'}

'' {'Metacontent'}

'.ps1' {'Automation'}

'.yml' {'Automation'}

default {'Configuration'}

Output

Count Name

----- ----

5 Automation

7 Configuration

2 Content

3 Metacontent

Select-Object
You can use calculated properties to add additional members to the objects
output with
the Select-Object cmdlet. In this example, we're listing the
PowerShell aliases that
begin with the letter C . Using Select-Object , we
output the alias, the cmdlet it's
mapped to, and a count for the number of
parameters defined for the cmdlet. Using a
calculated property, we can create
the ParameterCount property.
PowerShell

$aliases = Get-Alias c* |

Select-Object Name,

Definition,

@{

name='ParameterCount'

expr={$_.Parameters.Keys.Count}

$aliases | Get-Member

$aliases

Output

TypeName: Selected.System.Management.Automation.AliasInfo

Name MemberType Definition

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

Equals Method bool Equals(System.Object obj)

GetHashCode Method int GetHashCode()

GetType Method type GetType()

ToString Method string ToString()

Definition NoteProperty string Definition=Get-Content

Name NoteProperty string Name=cat

ParameterCount NoteProperty System.Int32 ParameterCount=21

Name Definition ParameterCount

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

cat Get-Content 21

cd Set-Location 15

cdd Push-MyLocation 1

chdir Set-Location 15

clc Clear-Content 20

clear Clear-Host 0

clhy Clear-History 17

cli Clear-Item 20

clp Clear-ItemProperty 22

cls Clear-Host 0

clv Clear-Variable 19

cnsn Connect-PSSession 29

compare Compare-Object 20

copy Copy-Item 24

cp Copy-Item 24

cpi Copy-Item 24

cpp Copy-ItemProperty 23

cvpa Convert-Path 13

Sort-Object
Using the calculated properties, you can sort data in different orders per
property. This
example sorts data from a CSV file in ascending order by
Date. But within each date, it
sorts the rows in descending order by
UnitsSold.

PowerShell

Import-Csv C:\temp\sales-data.csv |

Sort-Object Date, @{expr={$_.UnitsSold}; desc=$true}, Salesperson |

Select-Object Date, Salesperson, UnitsSold

Output

Date Salesperson UnitsSold

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

2020-08-01 Sally 3

2020-08-01 Anne 2

2020-08-01 Fred 1

2020-08-02 Anne 6

2020-08-02 Fred 2

2020-08-02 Sally 0

2020-08-03 Anne 5

2020-08-03 Sally 3

2020-08-03 Fred 1

2020-08-04 Anne 2

2020-08-04 Fred 2

2020-08-04 Sally 2

Notes
You may specify the expression script block directly, as an argument,
rather than
specifying it as the Expression entry in a hashtable. For
example:

PowerShell

'1', '10', '2' | Sort-Object { [int] $_ }

This example is convenient for cmdlets that don't require (or support)
naming a
property via the Name key, such as Sort-Object , Group-Object ,
and Measure-
Object .

For cmdlets that support naming the property, the script block is converted
to a
string and used as the name of the property in the output.

Expression script blocks run in child scopes, meaning that the caller's
variables

can't be directly modified.


Pipeline logic is applied to the output from Expression script blocks. This
means
that outputting a single-element array causes that array to be
unwrapped.

For most cmdlets, errors inside expression script blocks are quietly ignored.
For
Sort-Object , statement-terminating and script-terminating errors are
output but
they don't terminate the statement.

See also
about_Hash_Tables
ConvertTo-Html
Format-Custom
Format-List
Format-Table
Format-Wide
Compare-Object
Group-Object
Measure-Object
Select-Object
Sort-Object
Format types in .NET
about_Case-Sensitivity
Article • 09/19/2022 • 2 minutes to read

Short description
PowerShell is as case-insensitive as possible while preserving case.

Long description
As a general principle, PowerShell is as case insensitive as possible while preserving case
and not
breaking the underlying OS.

On Unix-based systems
On Unix-based systems, PowerShell is case-sensitive because filesystem manipulation
and environment
variables directly affect the underlying operating system and
integration with other tools.

On all systems
PowerShell variables are case-insensitive

Variable names have no interaction between them and the underlying operating
system. PowerShell
treats them case-insensitively.

Module names are case-insensitive (with exceptions)

The name of the module is purely a PowerShell concept and treated case-
insensitively. However, there
is a strong mapping to a foldername, which can be
case-sensitive in the underlying operating
system. Importing two modules with the
same case-insensitive name has the same behavior as
importing two modules with
the same name from different paths.

The name of a module is stored in the session state using the case by which it was
imported. The
name, as stored in the session state, is used by Update-Help when
looking for new help files.
The web service that serves the help files for Microsoft
uses a case-sensitive filesystem. When
the case of the imported name of the
module doesn't match, Update-Help can't find the help files
and reports an error.
Related links
about_Environment_Variables
Import-Module
about_Character_Encoding
Article • 03/09/2023 • 6 minutes to read

Short description
Describes how PowerShell uses character encoding for input and output of string
data.

Long description
Unicode is a worldwide character-encoding standard. The system uses Unicode
exclusively for character and string manipulation. For a detailed description
of all
aspects of Unicode, refer to
The Unicode Standard .

Windows supports Unicode and traditional character sets. Traditional character


sets,
such as Windows code pages, use 8-bit values or combinations of 8-bit
values to
represent the characters used in a specific language or geographical
region settings.

PowerShell uses a Unicode character set by default. However, several cmdlets


have an
Encoding parameter that can specify encoding for a different
character set. This
parameter allows you to choose the specific the character
encoding you need for
interoperability with other systems and applications.

The following cmdlets have the Encoding parameter:

Microsoft.PowerShell.Management
Add-Content
Get-Content
Set-Content
Microsoft.PowerShell.Utility
Export-Clixml
Export-Csv
Export-PSSession
Format-Hex
Import-Csv
Out-File
Select-String
Send-MailMessage

The byte-order-mark
The byte-order-mark (BOM) is a Unicode signature in the first few bytes of a
file or text
stream that indicate which Unicode encoding used for the data. For
more information,
see the
Byte order mark documentation.

In Windows PowerShell, any Unicode encoding, except UTF7 , always creates a


BOM.
PowerShell (v6 and higher) defaults to utf8NoBOM for all text output.

For best overall compatibility, avoid using BOMs in UTF-8 files. Unix platforms
and Unix-
heritage utilities also used on Windows Platforms don't support BOMs.

Similarly, UTF7 encoding should be avoided. UTF-7 is not a standard Unicode


encoding
and is written without a BOM in all versions of PowerShell.

Creating PowerShell scripts on a Unix-like platform or using a cross-platform


editor on
Windows, such as Visual Studio Code, results in a file encoded using
UTF8NoBOM . These
files work fine in PowerShell, but may break in Windows
PowerShell if the file contains
non-Ascii characters.

If you need to use non-Ascii characters in your scripts, save them as UTF-8
with BOM.
Without the BOM, Windows PowerShell misinterprets your script as
being encoded in
the legacy "ANSI" codepage. Conversely, files that do have the
UTF-8 BOM can be
problematic on Unix-like platforms. Many Unix tools such as
cat , sed , awk , and some
editors such as gedit don't know how to treat
the BOM.

Character encoding in Windows PowerShell


In PowerShell 5.1, the Encoding parameter supports the following values:

Ascii Uses Ascii (7-bit) character set.


BigEndianUnicode Uses UTF-16 with the big-endian byte order.

BigEndianUTF32 Uses UTF-32 with the big-endian byte order.

Byte Encodes a set of characters into a sequence of bytes.


Default Uses the encoding that corresponds to the system's active code page

(usually ANSI).
Oem Uses the encoding that corresponds to the system's current OEM code
page.

String Same as Unicode .

Unicode Uses UTF-16 with the little-endian byte order.


Unknown Same as Unicode .

UTF32 Uses UTF-32 with the little-endian byte order.


UTF7 Uses UTF-7.

UTF8 Uses UTF-8 (with BOM).


In general, Windows PowerShell uses the Unicode
UTF-16LE encoding by default.
However,
the default encoding used by cmdlets in Windows PowerShell is not
consistent.

7 Note

Using any Unicode encoding, except UTF7 , always creates a BOM.

For cmdlets that write output to files:

Out-File and the redirection operators > and >> create UTF-16LE, which
notably
differs from Set-Content and Add-Content .

New-ModuleManifest and Export-CliXml also create UTF-16LE files.

When the target file is empty or doesn't exist, Set-Content and


Add-Content use
Default encoding. Default is the encoding specified by
the active system locale's

ANSI legacy code page.

Export-Csv creates Ascii files but uses different encoding when using
Append

parameter (see below).

Export-PSSession creates UTF-8 files with BOM by default.

New-Item -Type File -Value creates a BOM-less UTF-8 file.

Send-MailMessage uses Default encoding by default.

Start-Transcript creates Utf8 files with a BOM. When the Append


parameter is

used, the encoding can be different (see below).

For commands that append to an existing file:

Out-File -Append and the >> redirection operator make no attempt to match
the
encoding of the existing target file's content. Instead, they use the
default
encoding unless the Encoding parameter is used. You must use the
files original
encoding when appending content.

In the absence of an explicit Encoding parameter, Add-Content detects


the existing
encoding and automatically applies it to the new content. If the
existing content
has no BOM, Default ANSI encoding is used. The behavior of
Add-Content is the
same in PowerShell (v6 and higher) except the default
encoding is Utf8 .
Export-Csv -Append matches the existing encoding when the target file
contains a

BOM. In the absence of a BOM, it uses Utf8 encoding.

Start-Transcript -Append matches the existing encoding of files that


include a

BOM. In the absence of a BOM, it defaults to Ascii encoding. This


encoding can
result in data loss or character corruption when the data in the
transcript contains
multibyte characters.

For cmdlets that read string data in the absence of a BOM:

Get-Content and Import-PowerShellDataFile uses the Default ANSI


encoding.

ANSI is also what the PowerShell engine uses when it reads source
code from files.

Import-Csv , Import-CliXml , and Select-String assume Utf8 in the


absence of a

BOM.

Character encoding in PowerShell


In PowerShell (v7.1 and higher), the Encoding parameter supports the
following values:

ascii : Uses the encoding for the ASCII (7-bit) character set.
bigendianunicode : Encodes in UTF-16 format using the big-endian byte order.

bigendianutf32 : Encodes in UTF-32 format using the big-endian byte order.


oem : Uses the default encoding for MS-DOS and console programs.

unicode : Encodes in UTF-16 format using the little-endian byte order.

utf7 : Encodes in UTF-7 format.


utf8 : Encodes in UTF-8 format (no BOM).

utf8BOM : Encodes in UTF-8 format with Byte Order Mark (BOM)


utf8NoBOM : Encodes in UTF-8 format without Byte Order Mark (BOM)

utf32 : Encodes in UTF-32 format using the little-endian byte order.

PowerShell defaults to utf8NoBOM for all output.

Beginning with PowerShell 6.2, the Encoding parameter also allows numeric
IDs of
registered code pages (like -Encoding 1251 ) or string names of
registered code pages
(like -Encoding "windows-1251" ). For more information,
see the .NET documentation for
Encoding.CodePage.

Changing the default encoding


PowerShell has two default variables that can be used to change the default
encoding
behavior.

$PSDefaultParameterValues

$OutputEncoding

For more information, see


about_Preference_Variables.

Beginning in PowerShell 5.1, the redirection operators ( > and >> ) call the
Out-File
cmdlet. Therefore, you can set the default encoding of them using
the
$PSDefaultParameterValues preference variable as shown in this example:

PowerShell

$PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'

Use the following statement to change the default encoding for all cmdlets that
have
the Encoding parameter.

PowerShell

$PSDefaultParameterValues['*:Encoding'] = 'utf8'

) Important

Putting this command in your PowerShell profile makes the preference a


session-
global setting that affects all commands and scripts that do not
explicitly specify an
encoding.

Similarly, you should include such commands in your scripts or modules that
you
want to behave the same way. Using these commands ensure that cmdlets
behave
the same way even when run by another user, on a different computer,
or in a
different version of PowerShell.

The automatic variable $OutputEncoding affects the encoding PowerShell uses


to
communicate with external programs. It has no effect on the encoding that
the output
redirection operators and PowerShell cmdlets use to save to files.

See also
about_Preference_Variables
Byte order mark
Code Pages - Win32 apps
Encoding.CodePage
Introduction to character encoding in .NET
The Unicode Standard
UTF-16LE
about_CimSession
Article • 09/19/2022 • 2 minutes to read

Short description
Describes a CimSession object and the difference between CIM sessions and
PowerShell
sessions.

Long description
A Common Information Model (CIM) session is a client-side object that
represents a
connection to a local computer or a remote computer. You can use
CIM sessions as an
alternative to PowerShell sessions (PSSessions). Both
approaches have advantages.

You can use the New-CimSession cmdlet to create a CIM session that contains
information about a connection, such as computer name, the protocol used for
the
connection, session ID, and instance ID.

After you create a CimSession object that specifies information required to


establish a
connection, PowerShell does not establish the connection
immediately. When a cmdlet
uses the CIM session, PowerShell connects to the
specified computer, and then, when
the cmdlet finishes, PowerShell terminates
the connection.

If you create a PSSession instead of using a CIM session, PowerShell


validates
connection settings, and then establishes and maintains the
connection. If you use CIM
sessions, PowerShell does not open a network
connection until needed. For more
information about PowerShell sessions, see
about_PSSessions.

When to use a CIM session


Only cmdlets that work with a Windows Management Instrumentation (WMI) provider
or CIM over WS-Man accept CIM sessions. For other cmdlets, use PSSessions.

When you use a CIM session, PowerShell runs the cmdlet on the local client. It
connects
to the WMI provider using the CIM session. The target computer does
not require
PowerShell, or even any version of the Windows operating system.

In contrast, a cmdlet run using a PSSession runs on the target computer.


It requires
PowerShell on the target system. Furthermore, the cmdlet sends data
back to the local
computer. PowerShell manages the data sent over the
connection, and keeps the size
within the limits set by Windows Remote
Management (WinRM). CIM sessions do not
impose the WinRM limits.

Using CDXML cmdlets


CIM-based Cmdlet Definition XML (CDXML) cmdlets can be written to use any WMI
Provider. All WMI providers use CimSession objects. For more information
about
CDXML, see CDXML definition and terms.

CDXML cmdlets have an automatic CimSession parameter that can take an array
of
CimSession objects. By default, PowerShell limits number of concurrent
CIM
Connections to 15. This limit can be overridden by CDXML cmdlets that
implement the
ThrottleLimit. See the individual cmdlet documentation to
understand the
ThrottleLimit.

See also
about_PSSessions
New-CimSession
about_Classes
Article • 01/30/2023 • 13 minutes to read

Short description
Describes how you can use classes to create your own custom types.

Long description
PowerShell 5.0 adds a formal syntax to define classes and other user-defined
types. The
addition of classes enables developers and IT professionals to
embrace PowerShell for a
wider range of use cases. It simplifies development of
PowerShell artifacts and
accelerates coverage of management surfaces.

A class declaration is a blueprint used to create instances of objects at run


time. When
you define a class, the class name is the name of the type. For
example, if you declare a
class named Device and initialize a variable
$dev to a new instance of Device, $dev is an
object or instance of type
Device. Each instance of Device can have different values in its
properties.

Supported scenarios
Define custom types in PowerShell using familiar object-oriented programming
semantics like classes, properties, methods, inheritance, etc.
Debug types using the PowerShell language.
Generate and handle exceptions using formal mechanisms.
Define DSC resources and their associated types by using the PowerShell
language.

Syntax
Classes are declared using the following syntax:

syntax

class <class-name> [: [<base-class>][,<interface-list>]] {

[[<attribute>] [hidden] [static] <property-definition> ...]

[<class-name>([<constructor-argument-list>])

{<constructor-statement-list>} ...]

[[<attribute>] [hidden] [static] <method-definition> ...]

Classes are instantiated using either of the following syntaxes:

syntax

[$<variable-name> =] New-Object -TypeName <class-name> [

[-ArgumentList] <constructor-argument-list>]

syntax

[$<variable-name> =] [<class-name>]::new([<constructor-argument-list>])

7 Note

When using the [<class-name>]::new() syntax, brackets around the class name
are
mandatory. The brackets signal a type definition for PowerShell.

Example syntax and usage


This example shows the minimum syntax needed to create a usable class.

PowerShell

class Device {

[string]$Brand

$dev = [Device]::new()

$dev.Brand = "Fabrikam, Inc."

$dev

Output

Brand

-----

Fabrikam, Inc.

Class properties
Properties are variables declared at class scope. A property may be of any
built-in type
or an instance of another class. Classes have no restriction in
the number of properties
they have.
Example class with simple properties
PowerShell

class Device {

[string]$Brand

[string]$Model

[string]$VendorSku

$device = [Device]::new()

$device.Brand = "Fabrikam, Inc."

$device.Model = "Fbk5040"

$device.VendorSku = "5072641000"

$device

Output

Brand Model VendorSku

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

Fabrikam, Inc. Fbk5040 5072641000

Example complex types in class properties


This example defines an empty Rack class using the Device class. The
examples,
following this one, show how to add devices to the rack and how to
start with a pre-
loaded rack.

PowerShell

class Device {

[string]$Brand

[string]$Model

[string]$VendorSku

class Rack {

[string]$Brand

[string]$Model

[string]$VendorSku

[string]$AssetId

[Device[]]$Devices = [Device[]]::new(8)

$rack = [Rack]::new()

$rack

Output

Brand :

Model :

VendorSku :

AssetId :

Devices : {$null, $null, $null, $null...}

Class methods
Methods define the actions that a class can perform. Methods may take
parameters that
provide input data. Methods can return output. Data returned by
a method can be any
defined data type.

When defining a method for a class, you reference the current class object by
using the
$this automatic variable. This allows you to access properties and
other methods
defined in the current class.

Example simple class with properties and methods


Extending the Rack class to add and remove devices
to or from it.

PowerShell

class Device {

[string]$Brand

[string]$Model

[string]$VendorSku

[string]ToString(){

return ("{0}|{1}|{2}" -f $this.Brand, $this.Model, $this.VendorSku)

class Rack {

[int]$Slots = 8

[string]$Brand

[string]$Model

[string]$VendorSku

[string]$AssetId

[Device[]]$Devices = [Device[]]::new($this.Slots)

[void] AddDevice([Device]$dev, [int]$slot){

## Add argument validation logic here

$this.Devices[$slot] = $dev

[void]RemoveDevice([int]$slot){

## Add argument validation logic here

$this.Devices[$slot] = $null

[int[]] GetAvailableSlots(){

[int]$i = 0

return @($this.Devices.foreach{ if($_ -eq $null){$i}; $i++})

$rack = [Rack]::new()

$device = [Device]::new()

$device.Brand = "Fabrikam, Inc."

$device.Model = "Fbk5040"

$device.VendorSku = "5072641000"

$rack.AddDevice($device, 2)

$rack

$rack.GetAvailableSlots()

Output

Slots : 8

Devices : {$null, $null, Fabrikam, Inc.|Fbk5040|5072641000, $null…}

Brand :

Model :

VendorSku :

AssetId :

Output in class methods


Methods should have a return type defined. If a method doesn't return output,
then the
output type should be [void] .
In class methods, no objects get sent to the pipeline except those mentioned in
the
return statement. There's no accidental output to the pipeline from the
code.

7 Note

This is fundamentally different from how PowerShell functions handle output,


where everything goes to the pipeline.

Non-terminating errors written to the error stream from inside a class method
are not
passed through. You must use throw to surface a terminating error.
Using the Write-*
cmdlets, you can still write to PowerShell's output streams
from within a class method.
However, this should be avoided so that the method
emits objects using only the
return statement.

Method output
This example demonstrates no accidental output to the pipeline from class
methods,
except on the return statement.

PowerShell

class FunWithIntegers

[int[]]$Integers = 0..10

[int[]]GetOddIntegers(){

return $this.Integers.Where({ ($_ % 2) })

[void] GetEvenIntegers(){

# this following line doesn't go to the pipeline

$this.Integers.Where({ ($_ % 2) -eq 0})

[string]SayHello(){

# this following line doesn't go to the pipeline

"Good Morning"

# this line goes to the pipeline

return "Hello World"

$ints = [FunWithIntegers]::new()

$ints.GetOddIntegers()

$ints.GetEvenIntegers()

$ints.SayHello()

Output

Hello World

Constructor
Constructors enable you to set default values and validate object logic at the
moment of
creating the instance of the class. Constructors have the same name
as the class.
Constructors might have arguments, to initialize the data members
of the new object.

The class can have zero or more constructors defined. If no constructor is


defined, the
class is given a default parameterless constructor. This
constructor initializes all
members to their default values. Object types and
strings are given null values. When
you define constructor, no default
parameterless constructor is created. Create a
parameterless constructor if one
is needed.

Constructor basic syntax


In this example, the Device class is defined with properties and a constructor.
To use this
class, the user is required to provide values for the parameters
listed in the constructor.

PowerShell

class Device {

[string]$Brand

[string]$Model

[string]$VendorSku

Device(

[string]$b,

[string]$m,

[string]$vsk

){

$this.Brand = $b

$this.Model = $m

$this.VendorSku = $vsk

[Device]$device = [Device]::new(

"Fabrikam, Inc.",

"Fbk5040",

"5072641000"

$device

Output

Brand Model VendorSku

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

Fabrikam, Inc. Fbk5040 5072641000

Example with multiple constructors


In this example, the Device class is defined with properties, a default
constructor, and a
constructor to initialize the instance.

The default constructor sets the brand to Undefined, and leaves model
and vendor-sku
with null values.

PowerShell

class Device {

[string]$Brand

[string]$Model

[string]$VendorSku

Device(){

$this.Brand = 'Undefined'

Device(

[string]$b,

[string]$m,

[string]$vsk

){

$this.Brand = $b

$this.Model = $m

$this.VendorSku = $vsk

[Device]$someDevice = [Device]::new()

[Device]$server = [Device]::new(

"Fabrikam, Inc.",

"Fbk5040",

"5072641000"

$someDevice, $server

Output

Brand Model VendorSku

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

Undefined

Fabrikam, Inc. Fbk5040 5072641000

Hidden attribute
The hidden attribute hides a property or method. The property or method is
still
accessible to the user and is available in all scopes in which the object
is available.
Hidden members are hidden from the Get-Member cmdlet and can't
be displayed using
tab completion or IntelliSense outside the class definition.

For more information, see About_hidden.

Example using hidden attributes


When a Rack object is created, the number of slots for devices is a fixed
value that
shouldn't be changed at any time. This value is known at creation
time.

Using the hidden attribute allows the developer to keep the number of slots
hidden and
prevents unintentional changes to the size of the rack.

PowerShell

class Device {

[string]$Brand

[string]$Model

class Rack {

[int] hidden $Slots = 8

[string]$Brand

[string]$Model

[Device[]]$Devices = [Device[]]::new($this.Slots)

Rack ([string]$b, [string]$m, [int]$capacity){

## argument validation here

$this.Brand = $b

$this.Model = $m

$this.Slots = $capacity

## reset rack size to new capacity

$this.Devices = [Device[]]::new($this.Slots)

[Rack]$r1 = [Rack]::new("Fabrikam, Inc.", "Fbk5040", 16)

$r1

$r1.Devices.Length

$r1.Slots

Output

Devices Brand Model

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

{$null, $null, $null, $null…} Fabrikam, Inc. Fbk5040

16

16

Notice Slots property isn't shown in $r1 output. However, the size was
changed by the
constructor.

Static attribute
The static attribute defines a property or a method that exists in the class
and needs
no instance.

A static property is always available, independent of class instantiation. A


static property
is shared across all instances of the class. A static method is
available always. All static
properties live for the entire session span.

Example using static attributes and methods


Assume the racks instantiated here exist in your data center. So, you would
like to keep
track of the racks in your code.

PowerShell

class Device {

[string]$Brand

[string]$Model

class Rack {

hidden [int] $Slots = 8

static [Rack[]]$InstalledRacks = @()

[string]$Brand

[string]$Model

[string]$AssetId

[Device[]]$Devices = [Device[]]::new($this.Slots)

Rack ([string]$b, [string]$m, [string]$id, [int]$capacity){

## argument validation here

$this.Brand = $b

$this.Model = $m

$this.AssetId = $id

$this.Slots = $capacity

## reset rack size to new capacity

$this.Devices = [Device[]]::new($this.Slots)

## add rack to installed racks

[Rack]::InstalledRacks += $this

static [void]PowerOffRacks(){
foreach ($rack in [Rack]::InstalledRacks) {

Write-Warning ("Turning off rack: " + ($rack.AssetId))

Testing static property and method exist

PS> [Rack]::InstalledRacks.Length
0

PS> [Rack]::PowerOffRacks()

PS> (1..10) | ForEach-Object {

>> [Rack]::new("Adatum Corporation", "Standard-16",

>> $_.ToString("Std0000"), 16)

>> } > $null

PS> [Rack]::InstalledRacks.Length
10

PS> [Rack]::InstalledRacks[3]

Brand Model AssetId Devices

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

Adatum Corporation Standard-16 Std0004 {$null, $null, $null, $null...}

PS> [Rack]::PowerOffRacks()

WARNING: Turning off rack: Std0001

WARNING: Turning off rack: Std0002

WARNING: Turning off rack: Std0003

WARNING: Turning off rack: Std0004

WARNING: Turning off rack: Std0005

WARNING: Turning off rack: Std0006

WARNING: Turning off rack: Std0007

WARNING: Turning off rack: Std0008

WARNING: Turning off rack: Std0009

WARNING: Turning off rack: Std0010

Notice that the number of racks increases each time you run this example.

Property validation attributes


Validation attributes allow you to test that values given to properties meet
defined
requirements. Validation is triggered the moment that the value is
assigned. See
about_functions_advanced_parameters.

Example using validation attributes


PowerShell

class Device {

[ValidateNotNullOrEmpty()][string]$Brand

[ValidateNotNullOrEmpty()][string]$Model

[Device]$dev = [Device]::new()

Write-Output "Testing dev"

$dev

$dev.Brand = ""

Output

Testing dev

Brand Model

----- -----

Exception setting "Brand": "The argument is null or empty. Provide an

argument that is not null or empty, and then try the command again."

At C:\tmp\Untitled-5.ps1:11 char:1

+ $dev.Brand = ""

+ ~~~~~~~~~~~~~~~

+ CategoryInfo : NotSpecified: (:) [],


SetValueInvocationException

+ FullyQualifiedErrorId : ExceptionWhenSetting

Inheritance in PowerShell classes


You can extend a class by creating a new class that derives from an existing
class. The
derived class inherits the properties of the base class. You can add
or override methods
and properties as required.

PowerShell does not support multiple inheritance. Classes cannot inherit from
more than
one class. However, you can use interfaces for that purpose.

Inheritance implementation is defined by the : operator; which means to


extend this
class or implements these interfaces. The derived class should
always be leftmost in the
class declaration.

Example using simple inheritance syntax


This example shows the simple PowerShell class inheritance syntax.

PowerShell

Class Derived : Base {...}

This example shows inheritance with an interface declaration coming after the
base
class.

PowerShell

Class Derived : Base, Interface {...}

Example of simple inheritance in PowerShell classes


In this example the Rack and Device classes used in the previous
examples are better
defined to: avoid property repetitions, better align common
properties, and reuse
common business logic.

Most objects in the data center are company assets, which makes sense to start
tracking
them as assets. Device types are defined by the DeviceType
enumeration, see
about_Enum for details on enumerations.
In our example, we're only defining Rack and ComputeServer ; both extensions
to the
Device class.

PowerShell

enum DeviceType {

Undefined = 0

Compute = 1

Storage = 2

Networking = 4

Communications = 8

Power = 16

Rack = 32

class Asset {

[string]$Brand

[string]$Model

class Device : Asset {

hidden [DeviceType]$devtype = [DeviceType]::Undefined

[string]$Status

[DeviceType] GetDeviceType(){
return $this.devtype

class ComputeServer : Device {

hidden [DeviceType]$devtype = [DeviceType]::Compute

[string]$ProcessorIdentifier

[string]$Hostname

class Rack : Device {

hidden [DeviceType]$devtype = [DeviceType]::Rack

hidden [int]$Slots = 8

[string]$Datacenter

[string]$Location

[Device[]]$Devices = [Device[]]::new($this.Slots)

Rack (){

## Just create the default rack with 8 slots

Rack ([int]$s){

## Add argument validation logic here

$this.Devices = [Device[]]::new($s)

[void] AddDevice([Device]$dev, [int]$slot){

## Add argument validation logic here

$this.Devices[$slot] = $dev

[void] RemoveDevice([int]$slot){

## Add argument validation logic here

$this.Devices[$slot] = $null

$FirstRack = [Rack]::new(16)

$FirstRack.Status = "Operational"
$FirstRack.Datacenter = "PNW"

$FirstRack.Location = "F03R02.J10"

(0..15).ForEach({

$ComputeServer = [ComputeServer]::new()

$ComputeServer.Brand = "Fabrikam, Inc." ## Inherited from Asset

$ComputeServer.Model = "Fbk5040" ## Inherited from Asset

$ComputeServer.Status = "Installed" ## Inherited from Device

$ComputeServer.ProcessorIdentifier = "x64" ## ComputeServer

$ComputeServer.Hostname = ("r1s" + $_.ToString("000")) ## ComputeServer

$FirstRack.AddDevice($ComputeServer, $_)

})

$FirstRack

$FirstRack.Devices

Output

Datacenter : PNW

Location : F03R02.J10

Devices : {r1s000, r1s001, r1s002, r1s003...}

Status : Operational

Brand :

Model :

ProcessorIdentifier : x64

Hostname : r1s000

Status : Installed

Brand : Fabrikam, Inc.

Model : Fbk5040

ProcessorIdentifier : x64

Hostname : r1s001

Status : Installed

Brand : Fabrikam, Inc.

Model : Fbk5040

<... content truncated here for brevity ...>

ProcessorIdentifier : x64

Hostname : r1s015

Status : Installed

Brand : Fabrikam, Inc.

Model : Fbk5040

Calling base class constructors


To invoke a base class constructor from a subclass, add the base keyword.

PowerShell

class Person {

[int]$Age

Person([int]$a)

$this.Age = $a

class Child : Person

[string]$School

Child([int]$a, [string]$s ) : base($a) {

$this.School = $s

[Child]$littleOne = [Child]::new(10, "Silver Fir Elementary School")

$littleOne.Age

Output

10

Invoke base class methods


To override existing methods in subclasses, declare methods using the same
name and
signature.

PowerShell

class BaseClass

[int]days() {return 1}

class ChildClass1 : BaseClass

[int]days () {return 2}

[ChildClass1]::new().days()

Output

To call base class methods from overridden implementations, cast to the


base class
([baseclass]$this) on invocation.

PowerShell

class BaseClass

[int]days() {return 1}

class ChildClass1 : BaseClass

[int]days () {return 2}

[int]basedays() {return ([BaseClass]$this).days()}

[ChildClass1]::new().days()

[ChildClass1]::new().basedays()

Output

Inheriting from interfaces


PowerShell classes can implement an interface using the same inheritance syntax
used
to extend base classes. Because interfaces allow multiple inheritance, a
PowerShell class
implementing an interface may inherit from multiple types, by
separating the type
names after the colon ( : ) with commas ( , ). A PowerShell
class that implements an
interface must implement all the members of that
interface. Omitting the implemention
interface members causes a parse-time
error in the script.
7 Note

PowerShell does not currently support declaring new interfaces in PowerShell


script.

PowerShell

class MyComparable : System.IComparable

[int] CompareTo([object] $obj)

return 0;

class MyComparableBar : bar, System.IComparable

[int] CompareTo([object] $obj)

return 0;

Importing classes from a PowerShell module


Import-Module and the #requires statement only import the module functions,
aliases,
and variables, as defined by the module. Classes are not imported. The
using module
statement imports the classes defined in the module. If the
module isn't loaded in the
current session, the using statement fails. For
more information about the using
statement, see about_Using.

The using module statement imports classes from the root module
( ModuleToProcess ) of
a script module or binary module. It does not
consistently import classes defined in
nested modules or classes defined in
scripts that are dot-sourced into the module.
Classes that you want to be
available to users outside of the module should be defined
in the root module.

Loading newly changed code during


development
During development of a script module, it is common to make changes to the code
then
load the new version of the module using Import-Module with the
Force parameter. This
works for changes to functions in the root module
only. Import-Module does not reload
any nested modules. Also, there is no way
to load any updated classes.

To ensure that you are running the latest version, you must unload the module
using the
Remove-Module cmdlet. Remove-Module removes the root module, all
nested modules,
and any classes defined in the modules. Then you can reload the
module and the classes
using Import-Module and the using module statement.

Another common development practice is to separate your code into different


files. If
you have function in one file that use classes defined in another
module, you should
using the using module statement to ensure that the
functions have the class definitions
that are needed.

The PSReference type is not supported with


class members
Using the [ref] type-cast with a class member silently fails. APIs that use
[ref]
parameters cannot be used with class members. The PSReference class
was designed to
support COM objects. COM objects have cases where you need to
pass a value in by
reference.

For more information about the [ref] type, see


PSReference Class.

See also
about_Enum
About_Hidden
about_Language_Keywords
about_Methods
about_Using
about_Command_Precedence
Article • 05/16/2023

Short description
Describes how PowerShell determines which command to run.

Long description
Command precedence describes how PowerShell determines which command to run
when a session contains more than one command with the same name. Commands
within a session can be hidden or replaced by commands with the same name. This
article shows you how to run hidden commands and how to avoid command-name
conflicts.

Command precedence
When a PowerShell session includes more than one command that has the same
name,
PowerShell determines which command to run using the following rules.

If you specify the path to a command, 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:

PowerShell

C:\TechDocs\FindDocs.ps1

You can run any executable command using its full path. As a security feature,
PowerShell doesn't run executable commands, including PowerShell scripts and
native
commands, unless the command is located in a path listed in the
$env:Path
environment variable.

To run an executable file that's in the current directory, specify the full
path or use the
relative path .\ to represent the current directory.

For example, to run the FindDocs.ps1 file in the current directory, type:
PowerShell

.\FindDocs.ps1

If you don't specify a path, PowerShell uses the following precedence order
when it runs
commands.

1. Alias
2. Function
3. Cmdlet (see Cmdlet name resolution)
4. External executable files (including PowerShell script files)

Therefore, if you type help , 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, if your session contains a cmdlet and a function, both named
Get-Map ,
when you type Get-Map , PowerShell runs the function.

7 Note

This only applies to loaded commands. If there is a build executable and an


Alias
build for a function with the name of Invoke-Build inside a module
that is not

loaded into the current session, PowerShell runs the build


executable instead. It
doesn't auto-load modules if it finds the external
executable. It's only when no
external executable is found that an alias,
function, or cmdlet with the given name
is invoked.

Resolving items with the same names


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 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. You can run the cmdlet by
specifying its module-
qualified name.

When items are replaced or overwritten, you can no longer access the
original item.
For example, if you import a variable that has the same name as a variable in
the
session, the original variable is replaced. You can't qualify a variable
with a module
name.

If you create a function at the command line and then import a function with
the same
name, the original function is replaced.

Finding hidden commands


The All parameter of the Get-Command cmdlet gets all commands with
the specified
name, even if they're hidden or replaced. Beginning in PowerShell
3.0, by default, Get-
Command gets only the commands that run when you type
the command name.

In the following examples, the session includes a Get-Date function and a


Get-Date
cmdlet. You can use Get-Command to determine which command is
chosen first.

PowerShell

Get-Command Get-Date

Output

CommandType Name ModuleName

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

Function Get-Date

Uses the All parameter to list available Get-Date commands.

PowerShell

Get-Command Get-Date -All

Output

CommandType Name Version Source

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

Function Get-Date

Cmdlet Get-Date 3.1.0.0 Microsoft.PowerShell.Utility

PowerShell

Get-Command where -all

Output

CommandType Name Version Source

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

Alias where -> Where-Object


Application where.exe 10.0.22621.1
C:\Windows\system32\where.exe

You can run particular commands by including qualifying information that


distinguishes
the command from other commands that might have the same name.
For cmdlets, you
can use the module-qualified name. For executables, you can
include the file extension.
For example, to run the executable version of
where use where.exe .

Using module-qualified names


Using the module-qualified name of a cmdlet allows you to run commands hidden
by
an item with the same name. For example, you can run the Get-Date cmdlet
by
qualifying it with its module name Microsoft.PowerShell.Utility.

Use this preferred method when writing scripts that you intend to distribute.
You can't
predict which commands might be present in the session in which the
script runs.

PowerShell

New-Alias -Name "Get-Date" -Value "Get-ChildItem"

Microsoft.PowerShell.Utility\Get-Date

Output

Tuesday, May 16, 2023 1:32:51 PM

To run a New-Map command from the MapFunctions module, use its


module-qualified
name:

PowerShell

MapFunctions\New-Map

To find the module from which a command was imported, use the ModuleName
property of commands.
(Get-Command <command-name>).ModuleName

For example, to find the source of the Get-Date cmdlet, type:

PowerShell

(Get-Command Get-Date).ModuleName

Output

Microsoft.PowerShell.Utility

7 Note

You can't qualify variables or aliases.

Using the call operator


You can also use the Call operator & to run hidden commands by combining it
with a
call to Get-ChildItem (the alias is dir ), Get-Command or
Get-Module.

The call operator executes strings and script blocks in a child scope. For more
information, see about_Operators.

For example, use the following command to run the function named Map that's
hidden
by an alias named Map .

PowerShell

& (Get-Command -Name Map -CommandType Function)

or

PowerShell

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

PowerShell

$myMap = (Get-Command -Name map -CommandType function)

& ($myMap)

Replaced items
A replaced item is one that you can no longer access. You can replace items
by
importing items of the same name from a module.

For example, if you type a Get-Map function in your session, and you import a
function
called Get-Map , it replaces the original function. You can't
retrieve it in the current
session.

Variables and aliases can't be hidden because you can't use a call operator or
a qualified
name to run them. When you import variables and aliases from a
module, they replace
variables in the session with the same name.

Cmdlet name resolution


When you don't use the qualified name of a cmdlet, PowerShell checks to see if
the
cmdlet is loaded in the current session. If there are multiple modules
loaded that
contain the same cmdlet name, PowerShell uses the cmdlet from the
first module found
alphabetically.

If the cmdlet isn't loaded, PowerShell searches the installed modules and
autoloads the
first module that contains the cmdlet and runs that cmdlet.
PowerShell searches for
modules in each path defined in the $env:PSModulePath
environment variable. The paths
are searched in the order that they're listed
in the variable. Within each path, the
modules are searched in alphabetical
order. PowerShell uses the cmdlet from the first
match it finds.

Avoiding name conflicts


The best way to manage command name conflicts is to prevent them. When you name
your commands, use a unique name. For example, add your initials or company
name
acronym to the nouns in your commands.
When you import commands into your session from a PowerShell module or from
another session, you can 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 PowerShell when you import the
DateFunctions module.

PowerShell

Import-Module -Name DateFunctions -Prefix ZZ

Running external executables


On Windows. PowerShell treats the file extensions listed in the $env:PATHEXT
environment variable as executable files. Files that aren't Windows executables
are
handed to Windows to process. Windows looks up the file association and
executes the
default Windows Shell verb for the extension. For Windows to
support the execution by
file extension, the association must be registered
with the system.

You can register the executable engine for a file extension using the ftype
and assoc
commands of the CMD command shell. PowerShell has no direct method
to register the
file handler. For more information, see the documentation for
the ftype command.

For PowerShell to see a file extension as executable in the current session,


you must add
the extension to the $env:PATHEXT environment variable.

See also
about_Aliases
about_Functions
about_Path_Syntax
Alias-Provider
Function-Provider
Get-Command
Import-Module
Import-PSSession
about_Command_Syntax
Article • 09/19/2022 • 7 minutes to read

Short description
Describes the syntax diagrams that are used in PowerShell.

Long description
The Get-Help and
Get-Command cmdlets display
syntax diagrams to help you construct
commands correctly. This topic
explains how to interpret the syntax diagrams.

SYNTAX DIAGRAMS
Each paragraph in a command syntax diagram represents a valid form of the
command.

To construct a command, follow the syntax diagram from left to right. Select
from
among the optional parameters and provide values for the placeholders.

PowerShell uses the following notation for syntax diagrams.

PowerShell

<command-name> -<Required Parameter Name> <Required Parameter Value>

[-<Optional Parameter Name> <Optional Parameter Value>]

[-<Optional Switch Parameters>]

[-<Optional Parameter Name>] <Required Parameter Value>

The following is the syntax for the New-Alias


cmdlet.

PowerShell

New-Alias [-Name] <string> [-Value] <string> [-Description <string>]

[-Force] [-Option {None | ReadOnly | Constant | Private | AllScope}]

[-PassThru] [-Scope <string>] [-Confirm] [-WhatIf] [<CommonParameters>]

The syntax is capitalized for readability, but PowerShell is


case-insensitive.

The syntax diagram has the following elements.

Command name
Commands always begin with a command name, such as New-Alias . Type the
command
name or its alias, such a "gcm" for Get-Command .

Parameters
The parameters of a command are options that determine what the command does.
Some parameters take a "value" which is user input to the command.

For example, the Get-Help command has a Name parameter that lets you
specify the
name of the topic for which help is displayed. The topic name is
the value of the Name
parameter.

In a PowerShell command, parameter names always begin with a hyphen.


The hyphen
tells PowerShell that the item in the command is a
parameter name.

For example, to use the Name parameter of New-Alias , you type the following:

PowerShell

-Name

Parameters can be mandatory or optional. In a syntax diagram, optional items


are
enclosed in brackets [ ] .

For more information about parameters, see


about_Parameters.

Parameter Values
A parameter value is the input that the parameter takes. Because Windows
PowerShell is
based on the Microsoft .NET Framework, parameter values are
represented in the syntax
diagram by their .NET type.

For example, the Name parameter of Get-Help takes a "String" value, which is
a text
string, such as a single word or multiple words enclosed in quotation
marks.

PowerShell

[-Name] <string>

The .NET type of a parameter value is enclosed in angle brackets < > to
indicate that it
is placeholder for a value and not a literal that you type in
a command.
To use the parameter, replace the .NET type placeholder with an object that
has the
specified .NET type.

For example, to use the Name parameter, type "-Name" followed by a string,
such as
the following:

PowerShell

-Name MyAlias

Parameters with no values


Some parameters do not accept input, so they do not have a parameter value.
Parameters without values are called "switch parameters" because they work
like on/off
switches. You include them (on) or you omit them (off) from a
command.

To use a switch parameter, just type the parameter name, preceded by a hyphen.

For example, to use the WhatIf parameter of the New-Alias cmdlet, type
the following:

PowerShell

-WhatIf

Parameter Sets
The parameters of a command are listed in parameter sets. Parameter sets look
like the
paragraphs of a syntax diagram.

The New-Alias cmdlet has one parameter set, but many cmdlets have multiple
parameter sets. Some of the cmdlet parameters are unique to a parameter set,
and
others appear in multiple parameter sets. Each parameter set represents
the format of a
valid command. A parameter set includes only parameters that
can be used together in
a command. If parameters cannot be used in the same
command, they appear in
separate parameter sets.

For example, the Get-Random


cmdlet has the following parameter sets:

PowerShell

Get-Random [[-Maximum] <Object>] [-Minimum <Object>] [-SetSeed <int>]

[<CommonParameters>]

Get-Random [-InputObject] <Object[]> [-Count <int>] [-SetSeed <int>]

[<CommonParameters>]

The first parameter set, which returns a random number, has the Minimum
and
Maximum parameters. The second parameter set, which returns a randomly
selected
object from a set of objects, includes the InputObject and
Count parameters. Both
parameter sets have the SetSeed parameter and
the common parameters.

These parameter sets indicate that you can use the InputObject and
Count parameters
in the same command, but you cannot use the Maximum
and Count parameters in the
same command.

You indicate which parameter set you want to use by using the parameters in
that
parameter set.

However, every cmdlet also has a default parameter set. The default parameter
set is
used when you do not specify parameters that are unique to a parameter
set. For
example, if you use Get-Random without parameters, Windows
PowerShell assumes that
you are using the Number parameter set and it
returns a random number.

In each parameter set, the parameters appear in position order. The order of
parameters
in a command matters only when you omit the optional parameter
names. When
parameter names are omitted, PowerShell assigns values to
parameters by position and
type. For more information about parameter
position, see about_Parameters .

Symbols in Syntax Diagrams


The syntax diagram lists the command name, the command parameters, and the
parameter values. It also uses symbols to show how to construct a valid
command.

The syntax diagrams use the following symbols:

A hyphen - indicates a parameter name. In a command, type the hyphen


immediately before the parameter name with no intervening spaces, as shown
in
the syntax diagram.

For example, to use the Name parameter of New-Alias , type:

PowerShell

-Name

Angle brackets <> indicate placeholder text. You do not type the angle
brackets or
the placeholder text in a command. Instead, you replace it
with the item that it
describes.

Angle brackets are used to identify the .NET type of the value that a
parameter
takes. For example, to use the Name parameter of the
New-Alias cmdlet, you
replace the <string> with a string, which is a
single word or a group of words that
are enclosed in quotation marks.

Brackets [ ] indicate optional items. A parameter and its value can be


optional, or
the name of a required parameter can be optional.

For example, the Description parameter of New-Alias and its value are
enclosed in
brackets because they are both optional.

PowerShell

[-Description <string>]

The brackets also indicate that the Name parameter value <string> is
required,
but the parameter name, "Name", is optional.

PowerShell

[-Name] <string>

A right and left bracket [] appended to a .NET type indicates that the
parameter
can accept one or multiple values of that type. Enter the values
in a comma-
separated list.

For example, the Name parameter of the New-Alias cmdlet takes only
one string,
but the Name parameter of
Get-Process can take
one or many strings.

PowerShell

New-Alias [-Name] <string>

New-Alias -Name MyAlias

PowerShell

Get-Process [-Name] <string[]>

Get-Process -Name Explorer, Winlogon, Services

Braces {} indicate an "enumeration," which is a set of valid values for


a parameter.

The values in the braces are separated by vertical bars | . These bars
indicate an
"exclusive OR" choice, meaning that you can choose only one
value from the set of
values that are listed inside the braces.

For example, the syntax for the New-Alias cmdlet includes the following
value
enumeration for the Option parameter:

PowerShell

-Option {None | ReadOnly | Constant | Private | AllScope}

The braces and vertical bars indicate that you can choose any one of the
listed
values for the Option parameter, such as "ReadOnly" or
"AllScope".

PowerShell

-Option ReadOnly

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:

PowerShell

[-Scope <string>]

Both the following examples are correct uses of the New-Alias cmdlet:

PowerShell

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:
PowerShell

[-Name] <string> [-Value] <string>

The following commands correctly use the New-Alias cmdlet. The commands
produce
the same result.

PowerShell

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:

PowerShell

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.

See also
about_Parameters
Get-Command
Get-Help
about_Comment_Based_Help
Article • 09/19/2022 • 15 minutes to read

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, Examples, and Online, to
display the
contents of comment-based help.

You can also write XML-based help files for functions and scripts. To enable
the Get-
Help cmdlet to find the XML-based help file for a function or script,
use the

.ExternalHelp keyword. Without this keyword, Get-Help cannot find


XML-based help

topics for functions or scripts.

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.

The Update-Help and


Save-Help cmdlets work only on XML
files. Updatable Help does
not support comment-based help topics.

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:

PowerShell
function Get-Function

<#

.<help keyword>

<help content>

#>

# function logic

or

PowerShell

function Get-Function

# function logic

<#

.<help keyword>

<help content>

#>

or

PowerShell

<#

.<help keyword>

<help content>

#>

function Get-Function { }

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. However, if the script is signed, place
Comment-based
help at the beginning of the script file. The end of the script
is occupied by the
signature block.

For example:

PowerShell

<#

.<help keyword>

<help content>

#>

function Get-Function { }

or

PowerShell

function Get-Function { }

<#

.<help keyword>

<help content>

#>

Syntax for comment-based help in script


modules
In a script module .psm1 , comment-based help uses the syntax for functions,
not the
syntax for scripts. You cannot use the script syntax to provide help
for all functions
defined in a script module.

For example, if you are using the .ExternalHelp keyword to identify the
XML-based
help files for the functions in a script module, you must add an
.ExternalHelp comment
to each function.

PowerShell

# .ExternalHelp <XML-file-name>

function <function-name>

...

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
The description of a parameter. Add a .PARAMETER keyword for each parameter
in the
function or script syntax.

Type the parameter name on the same line as the .PARAMETER keyword. Type the
parameter description on the lines following the .PARAMETER keyword. Windows
PowerShell interprets all text between the .PARAMETER line and the next
keyword or the
end of the comment block as part of the parameter description.
The description can
include paragraph breaks.

.PARAMETER <Parameter-Name>

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. For
this to work, you
must also have a comment block with at least one keyword.
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.

PowerShell

<#

.SYNOPSIS

Short description here

#>

function Verb-Noun {

[CmdletBinding()]

param (

# This is the same as .Parameter

[string]$Computername

# Verb the Noun on the computer

.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 .NET 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 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. The value appears on the line below the ".LINK"
keyword
and must be preceded by a comment symbol # or included in the
comment block.

Repeat the .LINK 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 name of the technology or feature that the function or script uses, or to
which it is
related. The Component parameter of Get-Help uses this value
to filter the search
results returned by Get-Help .

.ROLE
The name of the user role for the help topic. The Role parameter of
Get-Help uses this
value to filter the search results returned by Get-Help .

.FUNCTIONALITY
The keywords that describe the intended use of the function. The
Functionality
parameter of Get-Help uses this value to filter the search
results returned by Get-Help .

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

PowerShell

# .FORWARDHELPTARGETNAME <Command-Name>

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

PowerShell
# .FORWARDHELPCATEGORY <Category>

.REMOTEHELPRUNSPACE
Specifies a session that contains the help topic. Enter a variable that
contains a
PSSession object. This keyword is used by the
Export-PSSession
cmdlet to find the help
topics for the exported commands.

PowerShell

# .REMOTEHELPRUNSPACE <PSSession-variable>

.EXTERNALHELP
Specifies an XML-based help file for the script or function.

PowerShell

# .EXTERNALHELP <XML Help File>

The .ExternalHelp keyword is required when a function or script is documented


in XML
files. Without this keyword, Get-Help cannot find the XML-based help
file for the
function or script.

The .ExternalHelp keyword takes precedence over other comment-based help


keywords. If .ExternalHelp is present, Get-Help does not display
comment-based help,
even if it cannot find a help topic that matches the value
of the .ExternalHelp keyword.

If the function is exported by a module, set the value of the .ExternalHelp


keyword to a
filename without a path. Get-Help looks for the specified file
name in a language-
specific subdirectory of the module directory. There are no
requirements for the name
of the XML-based help file for a function, but a best
practice is to use the following
format:

<ScriptModule.psm1>-help.xml

If the function is not included in a module, include a path to the XML-based


help file. If
the value includes a path and the path 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,
just
as it does in a module directory.

For more information about the cmdlet help XML-based help file format, see
How to
Write Cmdlet Help.

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 filename. To
change the name or its capitalization, change the
function syntax or the script filename.

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

Default values and a value for Accept Wildcard characters do not appear in
the
parameter attribute table even when they are defined in the function or
script. To help
users, provide this information in the parameter description.

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

Comment-based Help for a Function


The following sample function includes comment-based help:

PowerShell

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

PS> extension -name "File"

File.txt

.EXAMPLE

PS> extension -name "File" -extension "doc"

File.doc

.EXAMPLE

PS> extension "File" "doc"

File.doc

.LINK

http://www.fabrikam.com/extension.html

.LINK

Set-Item

#>

The results are as follows:

PowerShell

Get-Help -Name "Add-Extension" -Full

Output

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

PS> extension -name "File"

File.txt

Example 2

PS> extension -name "File" -extension "doc"

File.doc

Example 3

PS> extension "File" "doc"

File.doc

RELATED LINKS

http://www.fabrikam.com/extension.html

Set-Item

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.

PowerShell

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

PS> extension -name "File"

File.txt

.EXAMPLE

PS> extension -name "File" -extension "doc"

File.doc

.EXAMPLE

PS> extension "File" "doc"

File.doc

.LINK

http://www.fabrikam.com/extension.html

.LINK

Set-Item

#>

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.

PowerShell

<#

.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

PS> .\Update-Month.ps1

.EXAMPLE

PS> .\Update-Month.ps1 -inputpath C:\Data\January.csv

.EXAMPLE

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 $env:Path environment variable, the
Get-Help command that gets the
script help must specify the script path.

PowerShell

Get-Help -Name .\update-month.ps1 -Full

Output

# 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

PS> .\Update-Month.ps1

Example 2

PS> .\Update-Month.ps1 -inputpath C:\Data\January.csv

Example 3

PS> .\Update-Month.ps1 -inputpath C:\Data\January.csv -outputPath

C:\Reports\2009\January.csv

# RELATED LINKS

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 for
Updatable Help and
to provide help topics in 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.

Note that the value of the .ExternalHelp keyword appears on the same
line as the
keyword. Any other placement is ineffective.

PowerShell

# .ExternalHelp C:\MyScripts\Update-Month-Help.xml

param ([string]$InputPath, [string]$OutPutPath)

function Get-Data { }

...

The following examples show three valid placements of the .ExternalHelp


keyword in a
function.

PowerShell

function Add-Extension

# .ExternalHelp C:\ps-test\Add-Extension.xml

param ([string] $name, [string]$extension = "txt")

$name = $name + "." + $extension

$name

PowerShell

function Add-Extension

param ([string] $name, [string]$extension = "txt")

$name = $name + "." + $extension

$name

# .ExternalHelp C:\ps-test\Add-Extension.xml

PowerShell

# .ExternalHelp C:\ps-test\Add-Extension.xml

function Add-Extension

param ([string] $name, [string]$extension = "txt")

$name = $name + "." + $extension

$name

Redirecting to a Different Help Topic


The following code is an excerpt from the beginning of the built-in help
function in
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.

PowerShell

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:

PowerShell

Get-Help -Name help

Output

NAME

Get-Help

SYNOPSIS

Displays information about PowerShell cmdlets and concepts.

...

See also
about_Functions
about_Functions_Advanced_Parameters
about_Scripts
How to Write Cmdlet Help
about_CommonParameters
Article • 09/19/2022 • 15 minutes to read

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're implemented by PowerShell, not by the cmdlet developer, and
they're
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 doesn't generate any verbose
output, using the
Verbose common parameter has no effect.

The common parameters are also available on advanced functions that use the
CmdletBinding attribute or the Parameter attribute.

Several common parameters override system defaults or preferences that you set
by
using the PowerShell preference variables. Unlike the preference variables,
the common
parameters affect only the commands in which they're used.

For more information, see about_Preference_Variables.

The following list displays the common parameters. Their aliases are listed in
parentheses.

Debug (db)
ErrorAction (ea)
ErrorVariable (ev)
InformationAction (infa)
InformationVariable (iv)
OutVariable (ov)
OutBuffer (ob)
PipelineVariable (pv)
Verbose (vb)
WarningAction (wa)
WarningVariable (wv)
The Action parameters are ActionPreference type values.
ActionPreference is an
enumeration with the following values:

Name Value

Suspend 5

Ignore 4

Inquire 3

Continue 2

Stop 1

SilentlyContinue 0

You may use the name or the value with the parameter.

In addition to the common parameters, many cmdlets offer risk mitigation


parameters.
Cmdlets that involve risk to the system or to user data usually
offer these parameters.

The risk mitigation parameters are:

WhatIf (wi)
Confirm (cf)

Common parameter descriptions

-Debug
Displays programmer-level detail about the operation done 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.

YAML

Type: SwitchParameter

Aliases: db

Required: False

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

By default, debugging messages aren't displayed because the value of the


$DebugPreference variable is SilentlyContinue.

In interactive mode, the Debug parameter overrides the value of the


$DebugPreference
variable for the current command, setting the value of
$DebugPreference to Inquire.

In non-interactive mode, the Debug parameter overrides the value of the


$DebugPreference variable for the current command, setting the value of

$DebugPreference to Continue.

-Debug:$true has the same effect as -Debug . Use -Debug:$false to


suppress the display

of debugging messages when $DebugPreference isn't


SilentlyContinue, which is the
default.

-ErrorAction
Determines how the cmdlet responds to a non-terminating error from the command.
This parameter works only when the command generates a non-terminating error,
such
as those from the Write-Error cmdlet.

YAML

Type: ActionPreference

Aliases: ea

Accepted values: Suspend, Ignore, Inquire, Continue, Stop, SilentlyContinue

Required: False

Position: Named

Default value: Depends on preference variable

Accept pipeline input: False

Accept wildcard characters: False

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 aren't valid, or insufficient permissions) that
prevent a command from
completing successfully.

-ErrorAction:Continue display the error message and continues executing the


command. Continue is the default.
-ErrorAction:Ignore suppresses the error message and continues executing the

command. Unlike SilentlyContinue, Ignore doesn't add the error message


to the $Error
automatic variable. The Ignore value is introduced in
PowerShell 3.0.

-ErrorAction:Inquire displays the error message and prompts you for


confirmation
before continuing execution. This value is rarely used.

-ErrorAction:SilentlyContinue suppresses the error message and continues


executing

the command.

-ErrorAction:Stop displays the error message and stops executing the command.

-ErrorAction:Suspend is only available for workflows which aren't supported


in
PowerShell 6 and beyond.

7 Note

The ErrorAction parameter overrides, but does not replace the value of
the
$ErrorActionPreference variable when the parameter is used in a
command to run

a script or function.

-ErrorVariable
ErrorVariable stores error messages about the command in the specified
variable and in
the $Error automatic variable. For more information, see
about_Automatic_Variables

YAML

Type: String

Aliases: ev

Required: False

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

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:
PowerShell

Get-Process -Id 6 -ErrorVariable a

The following command adds any error messages to the $a variable:

PowerShell

Get-Process -Id 2 -ErrorVariable +a

The following command displays the contents of $a :

PowerShell

$a

You can use this parameter to create a variable that contains only error
messages from
specific commands and does not affect the behavior of the
$Error automatic variable.
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.

7 Note

The custom error variable contains all errors generated by the command,
including
errors from calls to nested functions or scripts.

-InformationAction
Introduced in PowerShell 5.0. Within the command or script in which it's used,
the
InformationAction common parameter overrides the value of the
$InformationPreference preference variable, which by default is set to
SilentlyContinue.

When you use Write-Information in a script with


InformationAction, Write-Information
values are shown depending on the
value of the InformationAction parameter. For
more information about
$InformationPreference , see about_Preference_Variables.

YAML

Type: ActionPreference

Aliases: ia

Accepted values: Suspend, Ignore, Inquire, Continue, Stop, SilentlyContinue

Required: False

Position: Named

Default value: Depends on preference variable

Accept pipeline input: False

Accept wildcard characters: False

-InformationAction:Stop stops a command or script at an occurrence of the


Write-

Information command.

-InformationAction:Ignore suppresses the informational message and continues

running the command. Unlike SilentlyContinue, Ignore completely forgets the


informational message; it doesn't add the informational message to the
information
stream.

-InformationAction:Inquire displays the informational message that you specify


in a

Write-Information command, then asks whether you want to continue.

-InformationAction:Continue displays the informational message, and continues


running.

-InformationAction:Suspend isn't supported on PowerShell 6 and higher as it


is only
available for workflows.

-InformationAction:SilentlyContinue no effect as the informational message


aren't

(Default) displayed, and the script continues without interruption.

7 Note

The InformationAction parameter overrides, but does not replace the


value of the
$InformationAction preference variable when the parameter
is used in a command

to run a script or function.

-InformationVariable
Introduced in PowerShell 5.0. Within the command or script in which it's used,
the
InformationVariable common parameter stores in a variable a string that
you specify by
adding the Write-Information command. Write-Information
values are shown
depending on the value of the InformationAction common
parameter; if you don't add
the InformationAction common parameter,
Write-Information strings are shown
depending on the value of the
$InformationPreference preference variable. For more
information about
$InformationPreference , see about_Preference_Variables.
7 Note

The information variable contains all information messages generated by the


command, including information messages from calls to nested functions or
scripts.

YAML

Type: String

Aliases: iv

Required: False

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-OutBuffer
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're generated.

YAML

Type: Int32

Aliases: ob

Required: False

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

This resource management parameter is designed for advanced users. When you use
this parameter, PowerShell sends data to the next cmdlet in batches of
OutBuffer + 1 .

The following example alternates displays between to ForEach-Object process


blocks
that use the Write-Host cmdlet. The display alternates in batches of
2 or OutBuffer + 1 .

PowerShell

1..4 | ForEach-Object {

Write-Host "$($_): First"; $_

} -OutBuffer 1 | ForEach-Object {

Write-Host "$($_): Second" }

Output

1: First

2: First

1: Second

2: Second

3: First

4: First

3: Second

4: Second

-OutVariable
Stores output objects from the command in the specified variable in addition
to sending
the output along the pipeline.

YAML

Type: String

Aliases: ov

Required: False

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

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:

PowerShell

Get-Process PowerShell -OutVariable out

The following command adds the process object to the $out variable:

PowerShell

Get-Process iexplore -OutVariable +out

The following command displays the contents of the $out variable:


PowerShell

$out

7 Note

The variable created by the OutVariable parameter is a


[System.Collections.ArrayList] .

-PipelineVariable
PipelineVariable allows access to the most recent value passed into the
next pipeline
segment by the command that uses this parameter. Any command in
the pipeline can
access the value using the named PipelineVariable. The
value is assigned to the variable
when it is passed into the next pipeline
segment. This makes the PipelineVariable easier
to use than a specific
temporary variable, which might need to be assigned in multiple
locations.

Unlike $_ or $PSItem , using a PipelineVariable allows any pipeline


command to access
pipeline values passed (and saved) by commands other than the
immediately preceding
command. Pipeline commands can access the last value
piped from while processing the
next item passing through the pipeline. This
allows a command to feed back its output
to a previous command (or itself).

7 Note

Advanced functions can have up to three script blocks: begin , process ,


and end .
When using the PipelineVariable parameter with advanced
functions, only values
from the first defined script block are assigned to
the variable as the function runs.
For more information, see
Advanced functions. PowerShell 7.2 corrects
this
behavior.

YAML

Type: String

Aliases: pv

Required: False

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Valid values are strings, the same as for any variable names.

U Caution

The PipelineVariable is scoped to the pipeline in which it is invoked.


Variables
outside the pipeline, which use same name, are removed before the
pipeline is
executed. The PipelineVariable goes out of scope when the
pipeline terminates. If
multiple commands within the pipeline specify the
same PipelineVariable then
there is only one shared variable. That
variable is updated with the most recent
piped output from the command that
specifies the variable.

Some blocking commands collect all the pipeline items before producing any
output, for example Sort-Object or Select-Object -Last . Any
PipelineVariable
assigned in a command before such a blocking command
always contains the final
piped item from the preceding command when used in
a command after the
blocking command.

The following is an example of how PipelineVariable works. In this example,


the
PipelineVariable parameter is added to a Foreach-Object command to
store the results
of the command in variables. A range of numbers, 1 to 5, are
piped into the first
Foreach-Object command, the results of which are stored
in a variable named $temp .

The results of the first Foreach-Object command are piped into a second
Foreach-
Object command, which displays the current values of $temp and
$_ .

PowerShell

# Create a variable named $temp

$temp=8

Get-Variable temp

# Note that the variable just created is not available on the

# pipeline when -PipelineVariable creates the same variable name

1..5 | ForEach-Object -PipelineVariable temp -Begin {

Write-Host "Step1[BEGIN]:`$temp=$temp"

} -Process {

Write-Host "Step1[PROCESS]:`$temp=$temp - `$_=$_"

Write-Output $_

} | ForEach-Object {

Write-Host "`tStep2[PROCESS]:`$temp=$temp - `$_=$_"

# The $temp variable is deleted when the pipeline finishes

Get-Variable temp

Output

Name Value

---- -----

temp 8

Step1[BEGIN]:$temp=

Step1[PROCESS]:$temp= - $_=1

Step2[PROCESS]:$temp=1 - $_=1

Step1[PROCESS]:$temp=1 - $_=2

Step2[PROCESS]:$temp=2 - $_=2

Step1[PROCESS]:$temp=2 - $_=3

Step2[PROCESS]:$temp=3 - $_=3

Step1[PROCESS]:$temp=3 - $_=4

Step2[PROCESS]:$temp=4 - $_=4

Step1[PROCESS]:$temp=4 - $_=5

Step2[PROCESS]:$temp=5 - $_=5

Get-Variable : Cannot find a variable with the name 'temp'.

At line:1 char:1

+ Get-Variable temp

+ ~~~~~~~~~~~~~~~~~

+ CategoryInfo : ObjectNotFound: (temp:String) [Get-Variable],


ItemNotFoundException

+ FullyQualifiedErrorId :
VariableNotFound,Microsoft.PowerShell.Commands.GetVariableCommand

-Verbose
Displays detailed information about the operation done 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.

YAML

Type: SwitchParameter

Aliases: vb

Required: False

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

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 aren't
displayed by default.
-Verbose:$true has the same effect as -Verbose

-Verbose:$false suppresses the display of verbose messages. Use this parameter


when
the value of $VerbosePreference isn't SilentlyContinue (the
default).

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

YAML

Type: ActionPreference

Aliases: wa

Accepted values: Suspend, Ignore, Inquire, Continue, Stop, SilentlyContinue

Required: False

Position: Named

Default value: Depends on preference variable

Accept pipeline input: False

Accept wildcard characters: False

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.

-WarningAction:Continue displays the warning messages and continues executing


the

command. Continue is the default.

-WarningAction:Inquire displays the warning message and prompts you for

confirmation before continuing execution. This value is rarely used.

-WarningAction:SilentlyContinue suppresses the warning message and continues


executing the command.

-WarningAction:Stop displays the warning message and stops executing the


command.

7 Note

The WarningAction parameter overrides, but does not replace the value of
the
$WarningAction preference variable when the parameter is used in a
command to
run a script or function.

-WarningVariable
Stores warnings about the command in the specified variable.

YAML

Type: String

Aliases: wv

Required: False

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

All generated warnings are saved in the variable even if the warnings aren't
displayed to
the user.

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:

PowerShell

Get-Process -Id 6 -WarningVariable a

The following command adds any warnings to the $a variable:

PowerShell

Get-Process -Id 2 -WarningVariable +a

The following command displays the contents of $a :

PowerShell

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

7 Note

The warning variable contains all warnings generated by the command,


including
warnings from calls to nested functions or scripts.

Risk Management Parameter Descriptions

-WhatIf
Displays a message that describes the effect of the command, instead of
executing the
command.

YAML

Type: SwitchParameter

Aliases: wi

Required: False

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

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 isn't done without the
WhatIf parameter. For more
information, see about_Preference_Variables

-WhatIf:$true has the same effect as -WhatIf .

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

PowerShell

Remove-Item Date.csv -WhatIf

Instead of removing the item, PowerShell lists the operations it would


do and the items
that would be affected. This command produces the
following output:

Output

What if: Performing operation "Remove File" on

Target "C:\ps-test\date.csv".

-Confirm
Prompts you for confirmation before executing the command.

YAML

Type: SwitchParameter

Aliases: cf

Required: False

Position: Named

Default value: Depends on preference variable

Accept pipeline input: False

Accept wildcard characters: False

The Confirm parameter overrides the value of the $ConfirmPreference


variable for the
current command. The default value is true. For more
information, see
about_Preference_Variables

-Confirm:$true has the same effect as -Confirm .

-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, PowerShell lists the
operations it would do and
the items that would be affected, and asks for
approval.

PS C:\ps-test> Remove-Item tmp*.txt -Confirm

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"):

The Confirm response options are as follows:

Response Result

Yes ( Y ) Perform the action.

Yes to All ( A ) Perform all actions and suppress subsequent Confirm queries

for this command.

No ( N ): Do not perform the action.

No to All ( L ): Do not perform any actions and suppress subsequent Confirm

queries for this command.

Suspend ( S ): Pause the command and create a temporary session.

Help ( ? ) Display help for these options.

The Suspend option places the command on hold and creates a temporary
nested
session in which you can work until you're ready to choose a Confirm
option. The
command prompt for the nested session has two extra carets (>>) to
indicate that it's a
child operation of the original parent command. You can
run commands and scripts in
the nested session. To end the nested session and
return to the Confirm options for the
original command, type "exit".

In the following example, the Suspend option (S) is used to halt a command
temporarily
while the user checks the help for a command parameter. After
obtaining the needed
information, the user types "exit" to end the nested prompt
and then selects the Yes (y)
response to the Confirm query.

PS C:\ps-test> New-Item -ItemType File -Name Test.txt -Confirm

Confirm

Are you sure you want to perform this action?

Performing operation "Create File" on Target "Destination:

C:\ps-test\test.txt".

[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default

is "Y"): s

PS C:\ps-test> Get-Help New-Item -Parameter ItemType

-ItemType <string>

Specifies the provider-specified type of the new item.

Required? false

Position? named

Default value

Accept pipeline input? true (ByPropertyName)

Accept wildcard characters? false

PS C:\ps-test> exit

Confirm

Are you sure you want to perform this action?

Performing operation "Create File" on Target "Destination: C:\ps-test\test

.txt".

[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (defau

lt is "Y"): y

Directory: C:\ps-test

Mode LastWriteTime Length Name

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

-a--- 8/27/2010 2:41 PM 0 test.txt

Keywords
about_Common_Parameters

See also
about_Preference_Variables
Write-Debug
Write-Error
Write-Verbose
Write-Warning
about_Comparison_Operators
Article • 04/03/2023 • 12 minutes to read

Short description
The comparison operators in PowerShell can either compare two values or filter
elements of a collection against an input value.

Long description
Comparison operators let you compare values or finding values that match
specified
patterns. PowerShell includes the following comparison operators:

Equality

-eq , -ieq , -ceq - equals


-ne , -ine , -cne - not equals

-gt , -igt , -cgt - greater than


-ge , -ige , -cge - greater than or equal

-lt , -ilt , -clt - less than

-le , -ile , -cle - less than or equal

Matching

-like , -ilike , -clike - string matches wildcard pattern


-notlike , -inotlike , -cnotlike - string doesn't match wildcard pattern

-match , -imatch , -cmatch - string matches regex pattern

-notmatch , -inotmatch , -cnotmatch - string doesn't match regex pattern

Replacement

-replace , -ireplace , -creplace - replaces strings matching a regex


pattern

Containment

-contains , -icontains , -ccontains - collection contains a value

-notcontains , -inotcontains , -cnotcontains - collection doesn't


contain a value
-in - value is in a collection

-notin - value isn't in a collection

Type
-is - both objects are the same type

-isnot - the objects aren't the same type

Common features
String comparisons are case-insensitive unless you use the explicit
case-sensitive
operator. To make a comparison operator case-sensitive, add a
c after the - . For
example, -ceq is the case-sensitive version of -eq .
To make the case-insensitivity
explicit, add an i after - . For example,
-ieq is the explicitly case-insensitive version of
-eq .

String comparisons use the InvariantCulture for both case-sensitive and


case-insensitive
comparisons.

When the input of an operator is a scalar value, the operator returns a


Boolean value.
When the input is a collection, the operator returns the
elements of the collection that
match the right-hand value of the expression.
If there are no matches in the collection,
comparison operators return an empty
array. For example:

PowerShell

$a = (1, 2) -eq 3

$a.GetType().Name

$a.Count

Output

Object[]

There are a few exceptions:

The containment and type operators always return a Boolean value


The -replace operator returns the replacement result
The -match and -notmatch operators also populate the $Matches automatic
variable unless the left-hand side of the expression is a collection.

Equality operators

-eq and -ne


When the left-hand side is scalar, -eq returns True if the right-hand
side is equivalent,
otherwise, -eq returns False. -ne does the
opposite; it returns False when both sides are
equivalent; otherwise, -ne
returns True.

Example:

PowerShell

2 -eq 2 # Output: True

2 -eq 3 # Output: False

"abc" -eq "abc" # Output: True

"abc" -eq "abc", "def" # Output: False

"abc" -ne "def" # Output: True

"abc" -ne "abc" # Output: False

"abc" -ne "abc", "def" # Output: True

When the left-hand side is a collection, -eq returns those members that match
the
right-hand side, while -ne filters them out.

Example:

PowerShell

1,2,3 -eq 2 # Output: 2

"abc", "def" -eq "abc" # Output: abc

"abc", "def" -ne "abc" # Output: def

These operators process all elements of the collection. Example:

PowerShell

"zzz", "def", "zzz" -eq "zzz"

Output

zzz

zzz

The equality operator can compare objects of different types. It's important to
understand that the value is on the right-hand side of the comparison can be
converted
to the type of the left-hand side value for comparison.

For example, the string '1.0' is converted to an integer to be compared to


the value 1 .
This example returns True .
PowerShell

PS> 1 -eq '1.0'

True

In this example, the value 1 is converted to a string to be compared to


string '1.0' .
This example returns False .

PowerShell

PS> '1.0' -eq 1

False

The equality operators accept any two objects, not just a scalar or collection.
But the
comparison result isn't guaranteed to be meaningful for the end-user.
The following
example demonstrates the issue.

PowerShell

class MyFileInfoSet {

[String]$File

[Int64]$Size

$a = [MyFileInfoSet]@{File = "C:\Windows\explorer.exe"; Size = 4651032}

$b = [MyFileInfoSet]@{File = "C:\Windows\explorer.exe"; Size = 4651032}

$a -eq $b

Output

False

In this example, we created two objects with identical properties. Yet, the
equality test
result is False because they're different objects. To create
comparable classes, you need
to implement System.IEquatable<T> in your
class. The following example demonstrates
the partial implementation of a
MyFileInfoSet class that implements
System.IEquatable<T> and has two
properties, File and Size. The Equals() method
returns True if
the File and Size properties of two MyFileInfoSet objects are the same.

PowerShell

class MyFileInfoSet : System.IEquatable[Object] {

[String]$File

[Int64]$Size

[bool] Equals([Object] $obj) {

return ($this.File -eq $obj.File) -and ($this.Size -eq $obj.Size)

$a = [MyFileInfoSet]@{File = "C:\Windows\explorer.exe"; Size = 4651032}

$b = [MyFileInfoSet]@{File = "C:\Windows\explorer.exe"; Size = 4651032}

$a -eq $b

Output

True

A prominent example of comparing arbitrary objects is to find out if they're


null. But if
you need to determine whether a variable is $null , you must put
$null on the left-
hand side of the equality operator. Putting it on the
right-hand side doesn't do what
you expect.

For example, let $a be an array containing null elements:

PowerShell

$a = 1, 2, $null, 4, $null, 6

The following tests that $a isn't null.

PowerShell

$null -ne $a

Output

True

The following, however, filers out all null elements from $a :

PowerShell

$a -ne $null # Output: 1, 2, 4, 6

Output

-gt, -ge, -lt, and -le


-gt , -ge , -lt , and -le behave very similarly. When both sides are
scalar they return
True or False depending on how the two sides
compare:

Operator Returns True when...

-gt The left-hand side is greater

-ge The left-hand side is greater or equal

-lt The left-hand side is smaller

-le The left-hand side is smaller or equal

In the following examples, all statements return True.

PowerShell

8 -gt 6 # Output: True

8 -ge 8 # Output: True

6 -lt 8 # Output: True

8 -le 8 # Output: True

7 Note

In most programming languages the greater-than operator is > . In


PowerShell, this
character is used for redirection. For details, see
about_Redirection.

When the left-hand side is a collection, these operators compare each member of
the
collection with the right-hand side. Depending on their logic, they either
keep or discard
the member.

Example:

PowerShell

$a=5, 6, 7, 8, 9

Write-Output "Test collection:"

$a

Write-Output "`nMembers greater than 7"

$a -gt 7

Write-Output "`nMembers greater than or equal to 7"

$a -ge 7

Write-Output "`nMembers smaller than 7"

$a -lt 7

Write-Output "`nMembers smaller than or equal to 7"

$a -le 7

Output

Test collection:

Members greater than 7

Members greater than or equal to 7

Members smaller than 7

Members smaller than or equal to 7

These operators work with any class that implements System.IComparable.

Examples:

PowerShell

# Date comparison

[DateTime]'2001-11-12' -lt [DateTime]'2020-08-01' # True

# Sorting order comparison

'a' -lt 'z' # True; 'a' comes before 'z'

'macOS' -ilt 'MacOS' # False

'MacOS' -ilt 'macOS' # False

'macOS' -clt 'MacOS' # True; 'm' comes before 'M'

The following example demonstrates that there is no symbol on an American


QWERTY
keyboard that gets sorted after 'a'. It feeds a set containing all such
symbols to the -gt
operator to compare them against 'a'. The output is an
empty array.

PowerShell

$a=' ','`','~','!','@','#','$','%','^','&','*','(',')','_','+','-','=',

'{','}','[',']',':',';','"','''','\','|','/','?','.','>',',','<'

$a -gt 'a'

# Output: Nothing

If the two sides of the operators aren't reasonably comparable, these operators
raise a
non-terminating error.

Matching operators
The matching operators ( -like , -notlike , -match , and -notmatch ) find
elements that
match or don't match a specified pattern. The pattern for -like
and -notlike is a
wildcard expression (containing * , ? , and [ ] ), while
-match and -notmatch accept a
regular expression (Regex).

The syntax is:

<string[]> -like <wildcard-expression>

<string[]> -notlike <wildcard-expression>

<string[]> -match <regular-expression>

<string[]> -notmatch <regular-expression>

When the input of these operators is a scalar value, they return a Boolean
value. When
the input is a collection of values, the operators return any
matching members. If there
are no matches in a collection, the operators return
an empty array.

-like and -notlike


-like and -notlike behave similarly to -eq and -ne , but the right-hand
side could be

a string containing wildcards.

Example:

PowerShell
"PowerShell" -like "*shell" # Output: True

"PowerShell" -notlike "*shell" # Output: False


"PowerShell" -like "Power?hell" # Output: True

"PowerShell" -notlike "Power?hell" # Output: False


"PowerShell" -like "Power[p-w]hell" # Output: True

"PowerShell" -notlike "Power[p-w]hell" # Output: False

"PowerShell", "Server" -like "*shell" # Output: PowerShell

"PowerShell", "Server" -notlike "*shell" # Output: Server

-match and -notmatch


-match and -notmatch use regular expressions to search for pattern in the
left-hand side
values. Regular expressions can match complex patterns like
email addresses, UNC
paths, or formatted phone numbers. The right-hand side
string must adhere to the
regular expressions rules.

Scalar examples:

PowerShell

# Partial match test, showing how differently -match and -like behave

"PowerShell" -match 'shell' # Output: True

"PowerShell" -like 'shell' # Output: False

# Regex syntax test

"PowerShell" -match '^Power\w+' # Output: True

'bag' -notmatch 'b[iou]g' # Output: True

If the input is a collection, the operators return the matching members of that
collection.

Collection examples:

PowerShell

"PowerShell", "Super PowerShell", "Power's hell" -match '^Power\w+'

# Output: PowerShell

"Rhell", "Chell", "Mel", "Smell", "Shell" -match "hell"

# Output: Rhell, Chell, Shell

"Bag", "Beg", "Big", "Bog", "Bug" -match 'b[iou]g'

#Output: Big, Bog, Bug

"Bag", "Beg", "Big", "Bog", "Bug" -notmatch 'b[iou]g'

#Output: Bag, Beg

-match and -notmatch support regex capture groups. Each time they run on
scalar

input, and the -match result is True, or the -notmatch result is


False, they overwrite the
$Matches automatic variable. $Matches is a
Hashtable that always has a key named '0',

which stores the entire match.


If the regular expression contains capture groups, the
$Matches contains
additional keys for each group.

It's important to note that the $Matches hashtable contains only the first
occurrence of
any matching pattern.

Example:

PowerShell

$string = 'The last logged on user was CONTOSO\jsmith'

$string -match 'was (?<domain>.+)\\(?<user>.+)'

$Matches

Write-Output "`nDomain name:"

$Matches.domain

Write-Output "`nUser name:"

$Matches.user

Output

True

Name Value

---- -----

domain CONTOSO

user jsmith

0 was CONTOSO\jsmith

Domain name:

CONTOSO

User name:

jsmith

When the -match result is False, or the -notmatch result is True,


or when the input is a
collection, the $Matches automatic variable isn't
overwritten. Consequently, it will
contain the previously set value, or $null
if the variable hasn't been set. When
referencing $Matches after invoking one
of these operators, consider verifying that the
variable was set by the current
operator invocation using a condition statement.

Example:
PowerShell

if ("<version>1.0.0</version>" -match '<version>(.*?)</version>') {

$Matches

For details, see about_Regular_Expressions and


about_Automatic_Variables.

Replacement operator

Replacement with regular expressions


Like -match , the -replace operator uses regular expressions to find the
specified
pattern. But unlike -match , it replaces the matches with another
specified value.

Syntax:

<input> -replace <regular-expression>, <substitute>

The operator replaces all or part of a value with the specified value using
regular
expressions. You can use the operator for many administrative tasks,
such as renaming
files. For example, the following command changes the file
name extensions of all .txt
files to .log :

PowerShell

Get-ChildItem *.txt | Rename-Item -NewName { $_.name -replace


'\.txt$','.log' }

By default, the -replace operator is case-insensitive. To make it case


sensitive, use -
creplace . To make it explicitly case-insensitive, use
-ireplace .

Examples:

PowerShell

"book" -ireplace "B", "C" # Case insensitive

"book" -creplace "B", "C" # Case-sensitive; hence, nothing to replace

Output
Cook

book

Regular expressions substitutions


It's also possible to use regular expressions to dynamically replace text using
capturing
groups, and substitutions. Capture groups can be referenced in the
<substitute> string
using the dollar sign ( $ ) character before the group
identifier.

In the following example, the -replace operator accepts a username in the


form of
DomainName\Username and converts to the Username@DomainName format:

PowerShell

$SearchExp = '^(?<DomainName>[\w-.]+)\\(?<Username>[\w-.]+)$'

$ReplaceExp = '${Username}@${DomainName}'

'Contoso.local\John.Doe' -replace $SearchExp, $ReplaceExp

Output

John.Doe@Contoso.local

2 Warning

The $ character has syntactic roles in both PowerShell and regular


expressions:

In PowerShell, between double quotation marks, it designates variables and


acts as a subexpression operator.
In Regex search strings, it denotes end of the line.
In Regex substitution strings, it denotes captured groups. Be sure
to either put
your regular expressions between single quotation marks or
insert a backtick
( ` ) character before them.

For example:

PowerShell

$1 = 'Goodbye'

'Hello World' -replace '(\w+) \w+', "$1 Universe"

# Output: Goodbye Universe

'Hello World' -replace '(\w+) \w+', '$1 Universe'

# Output: Hello Universe

$$ in Regex denotes a literal $ . This $$ in the substitution string to


include a literal $ in

the resulting replacement. For example:

PowerShell

'5.72' -replace '(.+)', '$ $1' # Output: $ 5.72

'5.72' -replace '(.+)', '$$$1' # Output: $5.72


'5.72' -replace '(.+)', '$$1' # Output: $1

To learn more, see about_Regular_Expressions and


Substitutions in Regular Expressions.

Substituting in a collection
When the <input> to the -replace operator is a collection, PowerShell
applies the
replacement to every value in the collection. For example:

PowerShell

"B1","B2","B3","B4","B5" -replace "B", 'a'

a1

a2

a3

a4

a5

Containment operators
The containment operators ( -contains , -notcontains , -in , and -notin )
are similar to
the equality operators, except that they always return a
Boolean value, even when the
input is a collection. These operators stop
comparing as soon as they detect the first
match, whereas the equality
operators evaluate all input members. In a very large
collection, these
operators return quicker than the equality operators.

Syntax:

<Collection> -contains <Test-object>

<Collection> -notcontains <Test-object>

<Test-object> -in <Collection>

<Test-object> -notin <Collection>

-contains and -notcontains


These operators tell whether a set includes a certain element. -contains
returns True
when the right-hand side (test object) matches one of the
elements in the set. -
notcontains returns False instead. When the test object
is a collection, these operators

use reference equality, i.e. they check


whether one of the set's elements is the same
instance of the test object.

Examples:

PowerShell

"abc", "def" -contains "def" # Output: True

"abc", "def" -notcontains "def" # Output: False

"Windows", "PowerShell" -contains "Shell" # Output: False

"Windows", "PowerShell" -notcontains "Shell" # Output: True

"abc", "def", "ghi" -contains "abc", "def" # Output: False

"abc", "def", "ghi" -notcontains "abc", "def" # Output: True

More complex examples:

PowerShell

$DomainServers = "ContosoDC1","ContosoDC2","ContosoFileServer","ContosoDNS",

"ContosoDHCP","ContosoWSUS"

$thisComputer = "ContosoDC2"

$DomainServers -contains $thisComputer

# Output: True

$a = "abc", "def"

"abc", "def", "ghi" -contains $a # Output: False

$a, "ghi" -contains $a # Output: True

-in and -notin


The -in and -notin operators were introduced in PowerShell 3 as the
syntactic reverse
of the of -contains and -notcontains operators. -in
returns True when the left-hand
side <test-object> matches one of the
elements in the set. -notin returns False
instead. When the test object
is a set, these operators use reference equality to check
whether one of the
set's elements is the same instance of the test object.
The following examples do the same thing that the examples for -contains and
-
notcontains do, but they're written with -in and -notin instead.

PowerShell

"def" -in "abc", "def" # Output: True

"def" -notin "abc", "def" # Output: False

"Shell" -in "Windows", "PowerShell" # Output: False

"Shell" -notin "Windows", "PowerShell" # Output: True

"abc", "def" -in "abc", "def", "ghi" # Output: False

"abc", "def" -notin "abc", "def", "ghi" # Output: True

More complex examples:

PowerShell

$DomainServers = "ContosoDC1","ContosoDC2","ContosoFileServer","ContosoDNS",

"ContosoDHCP","ContosoWSUS"

$thisComputer = "ContosoDC2"

$thisComputer -in $DomainServers

# Output: True

$a = "abc", "def"

$a -in "abc", "def", "ghi" # Output: False

$a -in $a, "ghi" # Output: True

Type comparison
The type comparison operators ( -is and -isnot ) are used to determine if an
object is a
specific type.

Syntax:

PowerShell

<object> -is <type-reference>

<object> -isnot <type-reference>

Example:

PowerShell

$a = 1

$b = "1"

$a -is [int] # Output: True

$a -is $b.GetType() # Output: False

$b -isnot [int] # Output: True

$a -isnot $b.GetType() # Output: True

See also
about_Booleans
about_Operators
about_Regular_Expressions
about_Wildcards
Compare-Object
Foreach-Object
Where-Object
about_Continue
Article • 09/19/2022 • 2 minutes to read

Short description
Describes how the continue statement immediately returns the program flow
to the top
of a program loop, a switch statement, or a trap statement.

Long description
The continue statement provides a way to exit the current control block but
continue
execution, rather than exit completely. The statement supports labels.
A label is a name
you assign to a statement in a script.

Using continue in loops


An unlabeled continue statement immediately returns the program flow to
the top of
the innermost loop that is controlled by a for , foreach , do ,
or while statement. The
current iteration of the loop is terminated and the
loop continues with the next iteration.

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:

PowerShell

while ($ctr -lt 10)

$ctr += 1

if ($ctr -eq 5)

continue

Write-Host -Object $ctr

When using a for loop, execution continues at the <Repeat> statement,


followed by the
<Condition> test. In the example below, an infinite loop
will not occur because the

decrement of $i occurs after the continue


keyword.
PowerShell

# <Init> <Condition> <Repeat>

for ($i = 0; $i -lt 10; $i++)

Write-Host -Object $i

if ($i -eq 5)

continue

# Will not result in an infinite loop.

$i--

Using a labeled continue in a loop


A labeled continue statement terminates execution of the iteration and
transfers control
to the targeted enclosing iteration or switch statement
label.

In the following example, the innermost for is terminated when $condition


is True and
iteration continues with the second for loop at labelB .

PowerShell

:labelA for ($i = 1; $i -le 10; $i++) {

:labelB for ($j = 1; $j -le 10; $j++) {

:labelC for ($k = 1; $k -le 10; $k++) {

if ($condition) {

continue labelB

} else {

$condition = Update-Condition

Using continue in a switch statement


An unlabeled continue statement within a switch terminates execution of the
current
switch iteration and transfers control to the top of the switch to get
the next input
item.

When there is a single input item continue exits the entire switch statement.
When the
switch input is a collection, the switch tests each element of the
collection. The

continue exits the current iteration and the switch continues


with the next element.
PowerShell

switch (1,2,3) {

2 { continue } # moves on to the next element, 3

default { $_ }

Output

Using continue in a trap statement


If the final statement executed in the body a trap statement is continue ,
the trapped
error is silently ignored and execution continues with the
statement immediately
following the one that caused trap to occur.

Do not use continue outside of a loop, switch,


or trap
When continue is used outside of a construct that directly supports it
(loops, switch ,
trap ), PowerShell looks up the call stack for an
enclosing construct. If it can't find an
enclosing construct, the current
runspace is quietly terminated.

This means that functions and scripts that inadvertently use a continue
outside of an
enclosing construct that supports it, can inadvertently terminate
their callers.

Using continue inside a pipeline, such as a ForEach-Object script block,


not only exits
the pipeline, it potentially terminates the entire runspace.

See also
about_Break
about_Comparison_Operators
about_For
about_Throw
about_Trap
about_Try_Catch_Finally
about_Core_Commands
Article • 09/19/2022 • 2 minutes to read

Short description
Lists the cmdlets that are designed for use with PowerShell providers.

Long description
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 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_Files
Article • 01/19/2023 • 2 minutes to read

Short description
PowerShell data files are used to store arbitrary data using PowerShell syntax.

Long description
PowerShell data ( .psd1 ) files can store arbitrary data in PowerShell syntax.
That data can
be imported into variables in a PowerShell session. PowerShell
has three types of data
files and provides a cmdlet to import each type.

Basic data files


The Import-PowerShellDataFile cmdlet imports basic data files. The data in
the file must
be contained in a hashtable. This format only supports constant
values. You can't use
code or PowerShell expressions.

Module manifests
Module manifests are PowerShell data files. The data in the file must be
contained in a
hashtable. The structure of that hashtable only supports
specific key names related to
PowerShell modules.

The values assigned to the settings in the manifest file can be expressions
that are
evaluated by PowerShell. This allows you to construct paths and
conditionally assign
values based on variables.

When you import a module using Import-Module , the manifest is evaluated in


Restricted language mode. Restricted mode limits the commands and variables
that

can be used.

For more information, see about_Module_Manifests.

Localized data
The Import-LocalizedData cmdlet imports localized data files. During import,
the file is
processed in Constrained language mode. Constrained mode limits
the commands and
variables that can be used.

For more information, see about_Language_Modes.

Originally, localized data files were meant to be used to store string data that
could be
translated into other languages. This allowed your scripts to import
the data to provide
localized string output in other languages. However, you
aren't limited to storing string
data and don't have to use the data for
localized output.

The data in the file isn't limited to hashtables. It can be in any format
supported by the
PowerShell syntax, such as DATA sections.

For more information, see about_Data_Sections.

See also
Import-LocalizedData
Import-Module
Import-PowerShellDataFile
about_Data_Sections
about_Language_Modes
about_Module_Manifests
about_Data_Sections
Article • 09/19/2022 • 3 minutes to read

Short description
Explains Data sections, which isolate text strings and other read-only
data from script
logic.

Long description
Scripts that are designed for 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 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 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 PowerShell 2.0 feature. Scripts with Data sections will
not run in
PowerShell 1.0 without revision.

Syntax
The syntax for a Data section is as follows:

DATA [<variable-name>] [-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 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:

PowerShell

1,2,3

"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:

PowerShell

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.

PowerShell

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

PowerShell

$TextMsgs.Text001

$TextMsgs.Text002

Alternately, you can put the variable name in the definition of the Data section. For
example:

PowerShell

DATA TextMsgs {

ConvertFrom-StringData -StringData @'

Text001 = Windows 7

Text002 = Windows Server 2008 R2

'@

$TextMsgs

The result is the same as the previous example.

Output

Name Value

---- -----

Text001 Windows 7

Text002 Windows Server 2008 R2

Examples
Simple data strings.

PowerShell

DATA {

"Thank you for using my PowerShell Organize.pst script."

"It is provided free of charge to the community."

"I appreciate your comments and feedback."

Strings that include permitted variables.

PowerShell

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:

PowerShell

DATA {

ConvertFrom-StringData -stringdata @'

Text001 = Windows 7

Text002 = Windows Server 2008 R2

'@

A double-quoted here-string that uses the ConvertFrom-StringData cmdlet:

PowerShell

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:

PowerShell

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
Article • 03/20/2023 • 17 minutes to read

Short description
Describes the PowerShell debugger.

Long description
Debugging is the process of examining a script while it is running to identify
and correct
errors in the script instructions. The PowerShell debugger can help
you examine and
identify errors and inefficiencies in your scripts, functions,
commands, PowerShell
workflows, PowerShell Desired State Configuration (DSC)
configurations, or expressions.

Starting in PowerShell 5.0, the PowerShell debugger has been updated to debug
scripts,
functions, workflows, commands, configurations, or expressions that
are running in
either the console or Windows PowerShell ISE on remote
computers. You can run Enter-
PSSession to start an interactive remote
PowerShell session in which you can set

breakpoints and debug script files and


commands on the remote computer. Enter-
PSSession functionality has been
updated to let you reconnect to and enter a
disconnected session that is
running a script or command on a remote computer. If the
running script hits a
breakpoint, your client session automatically starts the debugger. If
the
disconnected session that is running a script has already hit a breakpoint, and
is
stopped at the breakpoint, Enter-PSSession automatically starts the
command-line
debugger, after you reconnect to the session.

The PowerShell debugger can also be used to debug PowerShell workflows, in


either the
PowerShell console, or in Windows PowerShell ISE. Starting in
PowerShell 5.0, you can
debug within running jobs or processes, either locally
or remotely.

You can use the features of the PowerShell debugger to examine a PowerShell
script,
function, command, workflow, or expression while it is running. The
PowerShell
debugger includes a set of cmdlets that let you set breakpoints,
manage breakpoints,
and view the call stack.

Debugger Cmdlets
The 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 PowerShell console, use the following commands
to
control the execution. In Windows PowerShell ISE, use commands on the Debug
menu.

Note: For information about how to use the debugger in other host applications,
see the
host application documentation.

s , StepInto : Executes the next statement and then stops.

v , StepOver : Executes the next statement, but skips functions and


invocations. The

skipped statements are executed, but not stepped through.

Ctrl+Break : (Break All in ISE) Breaks into a running script within either
the
PowerShell console, or Windows PowerShell ISE. Note that
Ctrl + Break in
Windows PowerShell 2.0, 3.0, and 4.0
closes the program. Break All works on both
local and remote
interactively-running scripts.

o , StepOut : 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 , Exit : Stops executing the script, and exits the debugger. If
you are
debugging a job by running the Debug-Job cmdlet, the Exit command
detaches
the debugger, and allows the job to continue running.

k , Get-PsCallStack : Displays the current call stack.

<Enter> : Repeats the last command if it was Step (s), StepOver (v), or
List (l).

Otherwise, represents a submit action.

? , h : Displays the debugger command Help.

To exit the debugger, you can use Stop (q).

Starting in PowerShell 5.0, you can run the Exit command to exit a
nested debugging
session that you started by running either Debug-Job or
Debug-Runspace .

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.

NOTE: If you step into a statement with a redirection operator, such as ">",
the
PowerShell debugger steps over all remaining statements in the script.

Displaying the Values of script Variables

While you are in the debugger, you can also enter commands, display the value
of
variables, use cmdlets, and run scripts at the command line.

You can display the current value of all variables in the script that is being
debugged,
except for the following automatic variables:

PowerShell
$_

$Args

$Input

$MyInvocation

$PSBoundParameters

If you try to display the value of any of these variables, you get the value of
that variable
for in an internal pipeline the debugger uses, not the value of
the variable in the script.

To display the value these variables for the script that is being debugged, in
the script,
assign the value of the automatic variable to a new variable. Then
you can display the
value of the new variable.

For example,

PowerShell

$scriptArgs = $Args

$scriptArgs

In the example in this topic, the value of the $MyInvocation variable is


reassigned as
follows:

PowerShell

$scriptname = $MyInvocation.PSCommandPath

The Debugger Environment


When you reach a breakpoint, you enter the debugger environment. The command
prompt changes so that it begins with "[DBG]:". If you are debugging a
workflow, the
prompt is "[WFDBG]". You can customize the prompt.

For more information about customizing the prompt, see about_Prompts.

Also, in some host applications, such as the 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 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:

PowerShell

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:

PowerShell

Get-Variable -scope 0

You can abbreviate the command as:

PowerShell

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 Workflows
The PowerShell 4.0 debugger can be used to debug PowerShell workflows, either
in the
PowerShell console, or in Windows PowerShell ISE. There are some
limitations with using
the PowerShell debugger to debug workflows.

You can view workflow variables while you are in the debugger, but setting
workflow variables from within the debugger is not supported.
Tab completion when stopped in the workflow debugger is not available.
Workflow debugging works only with synchronous running of workflows from a
PowerShell script. You cannot debug workflows if they are running as a job
(with
the AsJob parameter).
Other nested debugging scenarios, such as a workflow calling another workflow
or
a workflow calling a script, are not implemented.

The following example demonstrates debugging a workflow. When the debugger


steps
into the workflow function, the debugger prompt changes to "[WFDBG]".

PowerShell

PS C:> Set-PSBreakpoint -Script C:\TestWFDemo1.ps1 -Line 8

ID Script Line Command Variable Action

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

0 TestWFDemo1.ps1 8

PS C:> C:\TestWFDemo1.ps1

Entering debug mode. Use h or ? for help.

Hit Line breakpoint on 'C:\TestWFDemo1.ps1:8'

At C:\TestWFDemo1.ps1:8 char:5

+ Write-Output -InputObject "Now writing output:"

# ~~~~~

[WFDBG:localhost]: PS C:>> list

# 3:

4: workflow SampleWorkflowTest

5: {

6: param ($MyOutput)

# 7:

8:* Write-Output -InputObject "Now writing output:"

9: Write-Output -Input $MyOutput

# 10:

11: Write-Output -InputObject "Get PowerShell process:"

12: Get-Process -Name powershell

# 13:

14: Write-Output -InputObject "Workflow function complete."

15: }

# 16:

17: # Call workflow function

18: SampleWorkflowTest -MyOutput "Hello"

[WFDBG:localhost]: PS C:>> $MyOutput

Hello

[WFDBG:localhost]: PS C:>> stepOver

Now writing output:

At C:\TestWFDemo1.ps1:9 char:5

+ Write-Output -Input $MyOutput

# +!INCLUDE[]~

[WFDBG:localhost]: PS C:>> list

4: workflow SampleWorkflowTest

5: {

6: param ($MyOutput)

# 7:

8: Write-Output -InputObject "Now writing output:"

9:* Write-Output -Input $MyOutput

# 10:

11: Write-Output -InputObject "Get PowerShell process:"

12: Get-Process -Name powershell

# 13:

14: Write-Output -InputObject "Workflow function complete."

15: }

# 16:

17: # Call workflow function

18: SampleWorkflowTest -MyOutput "Hello"

# 19:

[WFDBG:localhost]: PS C:>> stepOver

Hello

At C:\TestWFDemo1.ps1:11 char:5

+ Write-Output -InputObject "Get PowerShell process:"

# +!INCLUDE[]~~~~~~~~~

[WFDBG:localhost]: PS C:>> stepOut

Get PowerShell process:

Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName

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

433 35 106688 128392 726 2.67 7124 powershell

499 44 134244 172096 787 2.79 7452 powershell

Workflow function complete.

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:

PowerShell

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


Starting in PowerShell 5.0, you can run the PowerShell debugger in a
remote session, in
either the console, or Windows PowerShell ISE.
Enter-PSSession functionality has been
updated to let you reconnect to and
enter a disconnected session that is running on a
remote computer, and
currently running a script. If the running script hits a breakpoint,
your
client session automatically starts the debugger.

The following is an example that shows how this works, with breakpoints set in
a script
at lines 6, 11, 22, and 25. Note that in the example, when the
debugger starts, there are
two identifying prompts: the name of the computer on
which the session is running, and
the DBG prompt that lets you know you are in
debugging mode.

PowerShell

Enter-Pssession -Cn localhost

[localhost]: PS C:\psscripts> Set-PSBreakpoint .\ttest19.ps1 6,11,22,25

ID Script Line Command Variable Action

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

0 ttest19.ps1 6

1 ttest19.ps1 11

2 ttest19.ps1 22

3 ttest19.ps1 25

[localhost]: PS C:\psscripts> .\ttest19.ps1

Hit Line breakpoint on 'C:\psscripts\ttest19.ps1:11'

At C:\psscripts\ttest19.ps1:11 char:1

+ $winRMName = "WinRM"

# + ~

[localhost]: [DBG]: PS C:\psscripts>> list

6: 1..5 | foreach { sleep 1; Write-Output "hello2day $_" }

7: }

# 8:

9: $count = 10

10: $psName = "PowerShell"

11:* $winRMName = "WinRM"

12: $myVar = 102

# 13:

14: for ($i=0; $i -lt $count; $i++)

15: {

16: sleep 1

17: Write-Output "Loop iteration is: $i"

18: Write-Output "MyVar is $myVar"

# 19:

20: hello2day

# 21:

[localhost]: [DBG]: PS C:\psscripts>> stepover

At C:\psscripts\ttest19.ps1:12 char:1

+ $myVar = 102

# + ~

[localhost]: [DBG]: PS C:\psscripts>> quit

[localhost]: PS C:\psscripts> Exit-PSSession

PS C:\psscripts>

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:

PowerShell
PS C:\PS-test> Get-Content test.ps1

function psversion {

"PowerShell " + $PSVersionTable.PSVersion

if ($PSVersionTable.PSVersion.Major -lt 6) {

"Upgrade to PowerShell 6.0!"

else {

"Have you run a background job today (start-job)?"

$scriptName = $MyInvocation.PSCommandPath

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.

PowerShell

PS C:\ps-test> Set-PSBreakpoint -line 1 -script test.ps1

You can abbreviate this command as:

PowerShell

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.


PowerShell

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.

PowerShell

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.

PowerShell

DBG> s

test.ps1:11 $scriptName = $MyInvocation.PSCommandPath

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 .

PowerShell

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.

PowerShell

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.

PowerShell

DBG> $scriptName

C:\ps-test\test.ps1

Use another Step command to execute the function call. Press ENTER, or type "s"
for
Step.

PowerShell

DBG> s

test.ps1:2 "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 StepOut command (o). It
completes the execution of
the function (unless it reaches a breakpoint) and
steps to the next statement in the
script.

PowerShell

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, StepOut, and
Continue
commands have the same effect. In this case, use StepOut (o).

PowerShell

Done C:\ps-test\test.ps1

PS C:\ps-test>

The StepOut 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 .)

PowerShell

PS C:\ps-test> Get-PSBreakpoint| Remove-PSBreakpoint

You can abbreviate this command as:

PowerShell

PS C:\ps-test> gbp | rbp

Or, run the command by writing a function, such as the following


function:

PowerShell

function delbr { gbp | rbp }

Now, create a breakpoint on the $scriptname variable.

PowerShell

PS C:\ps-test> Set-PSBreakpoint -variable scriptname -script test.ps1

You can abbreviate the command as:

PowerShell

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.

PowerShell

PS C:\ps-test> .\test.ps1

Hit Variable breakpoint on 'C:\ps-test\test.ps1:$scriptName'

(Write access)

test.ps1:11 $scriptName = $MyInvocation.PSCommandPath

# DBG>

Display the current value of the $scriptName variable, which is $null .


PowerShell

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.

PowerShell

DBG> $scriptName

C:\ps-test\test.ps1

```powershell

Use a Step command (s) to preview the next statement in the script.

```powershell

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 StepOver command (v). If you are already in the
function when you use
StepOver, it is not effective. The function call is
displayed, but it is not executed.

PowerShell

DBG> v

Windows PowerShell 2.0

Have you run a background job today (start-job)?

test.ps1:13 "Done $scriptName"

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

PowerShell

C:\ps-test>

To delete the breakpoints, use the Get-PsBreakpoint and Remove-PsBreakpoint


cmdlets.

PowerShell

PS C:\ps-test> Get-PSBreakpoint| Remove-PSBreakpoint

Create a new command breakpoint on the PsVersion function.

PowerShell

PS C:\ps-test> Set-PSBreakpoint -command psversion -script test.ps1

You can abbreviate this command to:

PowerShell

PS C:\ps-test> sbp -c psversion -s test.ps1

Now, run the script.

PowerShell

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

PowerShell

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

PowerShell

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

PowerShell

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.

PowerShell

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.

PowerShell

DBG> k

2: prompt

1: .\test.ps1: $args=[]
0: prompt: $args=[]

This example demonstrates just a few of the many ways to use the PowerShell
debugger.

For more information about the debugger cmdlets, type the following command:

PowerShell

help <cmdlet-name> -full

For example, type:

PowerShell

help Set-PSBreakpoint -full

Other Debugging Features in PowerShell


In addition to the PowerShell debugger, PowerShell includes several other
features that
you can use to debug scripts and functions.

Windows PowerShell ISE includes an interactive graphical debugger. For more


information, start Windows PowerShell ISE and press F1.

The Set-PSDebug cmdlet offers very basic script debugging features,


including
stepping and tracing.

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.

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 .

See also
Disable-PSBreakpoint
Enable-PSBreakpoint
Get-PSBreakpoint
Remove-PSBreakpoint
Set-PSBreakpoint
Get-PSCallStack
Write-Debug
Write-Verbose
about_DesiredStateConfiguration
Article • 09/19/2022 • 4 minutes to read

Short description
Provides a brief introduction to the PowerShell Desired State
Configuration (DSC)
feature.

Long description
DSC is a management platform in PowerShell that enables deploying and managing
configuration data for software services, and managing the environment in
which these
services run.

DSC provides a set of PowerShell language extensions, new cmdlets, and


resources that
you can use to declaratively specify how you want the state of
your software
environment to be configured. It also provides a means to
maintain and manage
existing configurations.

DSC is introduced in PowerShell 4.0.

For detailed information about DSC, see


PowerShell Desired State Configuration
Overview.

DEVELOPING DSC RESOURCES WITH CLASSES


Starting in PowerShell 5.0, you can develop DSC resources by using classes.
For more
information, see about_Classes, and
Writing a custom DSC resource with PowerShell
classes.

USING DSC
To use DSC to configure your environment, first define a PowerShell
script block using
the Configuration keyword, followed by an identifier, which
is in turn followed by the
pair of curly braces delimiting the block. Inside
the configuration block you can define
node blocks that specify the desired
configuration state for each node (computer) in the
environment. A node block
starts with the Node keyword, followed by the name of the
target computer,
which can be a variable. After the computer name, come the curly
braces that
delimit the node block. Inside the node block, you can define resource
blocks
to configure specific resources. A resource block starts with the type name of
the
resource, followed by the identifier you want to specify for that block,
followed by the
curly braces that delimit the block, as shown in the following
example.

PowerShell

Configuration MyWebConfig {

# Parameters are optional

param ($MachineName, $WebsiteFilePath)

# A Configuration block can have one or more Node blocks

Node $MachineName

# Next, specify one or more resource blocks

# WindowsFeature is one of the resources you can use in a Node block

# This example ensures the Web Server (IIS) role is installed

WindowsFeature IIS

# To ensure that the role is not installed, set Ensure to


"Absent"

Ensure = "Present"

Name = "Web-Server" # Use the Name property from Get-


WindowsFeature

# You can use the File resource to create files and folders

# "WebDirectory" is the name you want to use to refer to this


instance

File WebDirectory

Ensure = "Present" # You can also set Ensure to "Absent"

Type = "Directory" # Default is "File"

Recurse = $true

SourcePath = $WebsiteFilePath

DestinationPath = "C:\inetpub\wwwroot"

# Ensure that the IIS block is successfully run first before

# configuring this resource

DependsOn = "[WindowsFeature]IIS" # Use for dependencies

To create a configuration, invoke the Configuration block the same way you
would
invoke a PowerShell function, passing in any expected parameters you may
have defined
(two in the example above). For example, in this case:

PowerShell

MyWebConfig -MachineName "TestMachine" -WebsiteFilePath `

"\\filesrv\WebFiles" -OutputPath "C:\Windows\system32\temp"

# OutputPath is optional

This generates a MOF file per node at the path you specify. These MOF files
specify the
desired configuration for each node. Next, use the following
cmdlet to parse the
configuration MOF files, send each node its corresponding
configuration, and enact
those configurations. Note that you do not need to
create a separate MOF file for class-
based DSC resources.

PowerShell

Start-DscConfiguration -Verbose -Wait -Path "C:\Windows\system32\temp"

USING DSC TO MAINTAIN CONFIGURATION


STATE
With DSC, configuration is idempotent. This means that if you use DSC to enact
the
same configuration more than once, the resulting configuration state will
always be the
same. Because of this, if you suspect that any nodes in your
environment may have
drifted from the desired state of configuration, you can
enact the same DSC
configuration again to bring them back to the desired
state. You do not need to modify
the configuration script to address only
those resources whose state has drifted from
the desired state.

The following example shows how you can verify whether the actual state of
configuration on a given node has drifted from the last DSC configuration
enacted on
the node. In this example we are checking the configuration of the
local computer.

PowerShell

$session = New-CimSession -ComputerName "localhost"

Test-DscConfiguration -CimSession $session

BUILT-IN DSC RESOURCES


You can use the following built-in resources in your configuration scripts:

Name Properties

File {DestinationPath, Attributes, Checksum, Content...}

Archive {Destination, Path, Checksum, Credential...}

Environment {Name, DependsOn, Ensure, Path...}


Name Properties

Group {GroupName, Credential, DependsOn, Description...}

Log {Message, DependsOn, PsDscRunAsCredential}

Package {Name, Path, ProductId, Arguments...}

Registry {Key, ValueName, DependsOn, Ensure...}

Script {GetScript, SetScript, TestScript, Credential...}

Service {Name, BuiltInAccount, Credential, Dependencies...}

User {UserName, DependsOn, Description, Disabled...}

WaitForAll {NodeName, ResourceName, DependsOn, PsDscRunAsC...}

WaitForAny {NodeName, ResourceName, DependsOn, PsDscRunAsC...}

WaitForSome {NodeCount, NodeName, ResourceName, DependsOn...}

WindowsFeature {Name, Credential, DependsOn, Ensure...}

WindowsOptionalFeature {Name, DependsOn, Ensure, LogLevel...}

WindowsProcess {Arguments, Path, Credential, DependsOn...}

To get a list of available DSC resources on your system, run the


Get-DscResource cmdlet.

7 Note

In PowerShell versions below 7.0, Get-DscResource does not find Class based
DSC
resources.

The example in this topic demonstrates how to use the File and WindowsFeature
resources. To see all properties that you can use with a resource, insert the
cursor in the
resource keyword (for example, File) within your configuration
script in PowerShell ISE,
hold down CTRL + SPACEBAR

FIND MORE RESOURCES


You can download, install, and learn about many other available DSC resources
that
have been created by the PowerShell and DSC user community, and by
Microsoft. Visit
the PowerShell Gallery
to browse and learn about available DSC resources.
See also
PowerShell Desired State Configuration Overview
Built-In PowerShell Desired State Configuration Resources
Build Custom PowerShell Desired State Configuration Resources
about_Do
Article • 09/19/2022 • 2 minutes to read

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:

PowerShell

do {<statement list>} while (<condition>)

The following shows the syntax of the Do-Until statement:

PowerShell

do {<statement list>} until (<condition>)

The statement 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. For more
information
about how booleans are evaluated, see
about_Booleans.

Example
The following example of a Do statement counts the items in an array until it
reaches an
item with a value of 0.

PowerShell

PS> $x = 1,2,78,0

PS> do { $count++; $a++; } while ($x[$a] -ne 0)

PS> $count

The following example uses the Until keyword. Notice that the not equal to
operator ( -
ne ) is replaced by the equal to operator ( -eq ).

PowerShell

PS> $x = 1,2,78,0

PS> do { $count++; $a++; } until ($x[$a] -eq 0)

PS> $count

The following example writes all the values of an array, skipping any value
that is less
than zero.

PowerShell

do {

if ($x[$a] -lt 0) { continue }

Write-Host $x[$a]

while (++$a -lt 10)

See also
about_Booleans
about_Break
about_Continue
about_Operators
about_Assignment_Operators
about_Comparison_Operators
about_While
about_Enum
Article • 09/19/2022 • 3 minutes to read

Short description
The enum statement is used to declare an enumeration. An enumeration is a
distinct
type that consists of a set of named labels called the enumerator
list.

Long description
The enum statement allows you to create a strongly typed set of labels. That
enumeration can be used in the code without having to parse or check for
spelling
errors.

Enumerations are internally represented as integers with a starting value of


zero. The
first label in the list is assigned the value zero. The remaining
labels are assigned with
consecutive numbers.

In the definition, labels can be given any integer value. Labels with no value
assigned
take the next integer value.

Syntax (basic)
syntax

enum <enum-name> {

<label> [= <int-value>]

...

Usage example
The following example shows an enumeration of objects that can be seen as
media files.
The definition assigns explicit values to the underlying values
of music , picture , video .
Labels immediately following an explicit
assignment get the next integer value.
Synonyms can be created by assigning
the same value to another label; see the
constructed values for: ogg , oga ,
mogg , or jpg , jpeg , or mpg , mpeg .

PowerShell
enum MediaTypes {

unknown

music = 10

mp3

aac

ogg = 15

oga = 15

mogg = 15

picture = 20

jpg

jpeg = 21

png

video = 40

mpg

mpeg = 41

avi

m4v

The GetEnumNames() method returns the list of the labels for the enumeration.

PowerShell

[MediaTypes].GetEnumNames()

Output

unknown

music

mp3

aac

ogg

oga

mogg

picture

jpg

jpeg

png

video

mpg

mpeg

avi

m4v

The GetEnumValues() method returns the list of the values for the enumeration.

PowerShell

[MediaTypes].GetEnumValues()

Output

unknown

music

mp3

aac

oga

oga

oga

picture

jpeg

jpeg

png

video

mpeg

mpeg

avi

m4v

7 Note

GetEnumNames() and GetEnumValues() seem to return the same results; a


list of

named values. However, internally, GetEnumValues() enumerates the


values, then
maps values into names. Read the list carefully and you'll
notice that ogg , oga , and
mogg appear in the output of
GetEnumNames() , but the output of GetEnumValues()

only shows oga . The


same thing happens for jpg , jpeg , and mpg , mpeg .

The GetEnumName() method can be used to get a name associated with a specific
value.
If there are multiple names associated with a value, the method returns
the
alphabetically-first name.

PowerShell

[MediaTypes].GetEnumName(15)

oga

The following example shows how to map each name to its value.

PowerShell

[MediaTypes].GetEnumNames() | ForEach-Object {

"{0,-10} {1}" -f $_,[int]([MediaTypes]::$_)

Output
unknown 0

music 10

mp3 11

aac 12

ogg 15

oga 15

mogg 15

picture 20

jpg 21

jpeg 21

png 22

video 40

mpg 41

mpeg 41

avi 42

m4v 43

Enumerations as flags
Enumerations can be defined as a collection of bit flags.
Where, at any given point the
enumeration represents one or more of
those flags turned on.

For enumerations as flags to work properly, each label should have a power of
two
value.

Syntax (flags)
syntax

[Flags()] enum <enum-name> {

<label 0> [= 1]

<label 1> [= 2]

<label 2> [= 4]

<label 3> [= 8]

...

Flags usage example


In the following example the FileAttributes enumeration is created.

PowerShell

[Flags()] enum FileAttributes {

Archive = 1

Compressed = 2

Device = 4

Directory = 8

Encrypted = 16

Hidden = 32

[FileAttributes]$file1 = [FileAttributes]::Archive

[FileAttributes]$file1 +=[FileAttributes]::Compressed

[FileAttributes]$file1 += [FileAttributes]::Device

"file1 attributes are: $file1"

[FileAttributes]$file2 = [FileAttributes]28 ## => 16 + 8 + 4

"file2 attributes are: $file2"

Output

file1 attributes are: Archive, Compressed, Device

file2 attributes are: Device, Directory, Encrypted

To test that a specific is set, you can use the binary comparison operator
-band . In this
example, we test for the Device and the Archive
attributes in the value of $file2 .

PowerShell

PS > ($file2 -band [FileAttributes]::Device) -eq [FileAttributes]::Device

True

PS > ($file2 -band [FileAttributes]::Archive) -eq [FileAttributes]::Archive

False

about_Environment_Provider
Article • 09/19/2022 • 3 minutes to read

Provider name
Environment

Drives
Env:

Capabilities
ShouldProcess

Short description
Provides access to the Windows environment variables.

Detailed description
The PowerShell Environment provider lets you get, add, change, clear, and delete
environment
variables and values in PowerShell.

Environment variables are dynamically named variables that describe the environment
in which your programs run. Windows and PowerShell use environment variables to
store persistent information that affect system
and process execution. Unlike PowerShell
variables, environment variables are not subject to scope constraints.

The Environment drive is a flat namespace containing the environment variables specific
to the current user's session. The environment variables
have no child items.

The Environment provider supports the following cmdlets, which are covered
in this
article.

Get-Location
Set-Location
Get-Item
New-Item
Remove-Item
Clear-Item

Types exposed by this provider


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.

Navigating the Environment drive


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 PowerShell drive. To reference an
environment variable from another
location, use the Env: drive name in the
path.

PowerShell

Set-Location Env:

To return to a file system drive, type the drive name. For example, type:

PowerShell

Set-Location C:

You can also work with the Environment provider from any other PowerShell
drive. To
reference an environment variable from another location, use the drive name Env: in
the path.

The Environment provider also exposes environment variables using a variable


prefix of
$env: . The following command views the contents of the
ProgramFiles environment

variable. The $env: variable prefix can


be used from any PowerShell drive.

PS C:\> $env:ProgramFiles

C:\Program Files

You can also change the value of an environment variable using the $env:
variable
prefix. Any changes made only pertain to the current PowerShell
session for as long as it
is active.

7 Note

PowerShell uses aliases to allow you a familiar way to work with provider
paths.
Commands such as dir and ls are now aliases for
Get-ChildItem,
cd is an alias for
Set-Location. and pwd is
an alias for Get-Location.

Getting environment variables


This command lists all the environment variables in the current session.

PowerShell

Get-Item -Path Env:

You can use this command from any PowerShell drive.

The Environment provider has no containers, so the above command has the
same
effect when used with Get-ChildItem .

PowerShell

Get-ChildItem -Path Env:

Get a selected environment variable


This command gets the WINDIR environment Variable.

PowerShell

Get-ChildItem -Path Env:windir

You can also use the variable prefix format as well.

PowerShell

$env:windir

Create an environment variable


This command creates the USERMODE environment variable with a value of
"Non-Admin".
The -Path parameter value creates the new item in the Env:
drive. The new
environment variable is only usable in the current PowerShell
session for as long as it is
active.

PowerShell

PS C:\> New-Item -Path Env: -Name USERMODE -Value Non-Admin

Changing an environment variable

Rename an environment variable


This command uses the Rename-Item cmdlet to change the name of the USERMODE
environment variable that you created to USERROLE . 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.

PowerShell

Rename-Item -Path Env:USERMODE -NewName USERROLE

Change an environment variable


This command uses the Set-Item cmdlet to change the value of the USERROLE
environment variable to "Administrator".

PowerShell

Set-Item -Path Env:USERROLE -Value Administrator

Copy an environment variable


This command copies the value of the USERROLE environment variable to the
USERROLE2
environment Variable.

PowerShell

Copy-Item -Path Env:USERROLE -Destination Env:USERROLE2

Remove an environment variable


This command deletes the USERROLE2 environment variable from the current
session.

PowerShell

Remove-Item -Path Env:USERROLE2

Remove an environment variable with Clear-


Item
This command deletes the USERROLE environment variable by clearing its
value.

PowerShell

Clear-Item -Path Env:USERROLE

Using the pipeline


Provider cmdlets accept pipeline input. You can use the pipeline to simplify
task by
sending provider data from one cmdlet to another provider cmdlet.
To read more about
how to use the pipeline with provider cmdlets, see the
cmdlet references provided
throughout this article.

Getting help
Beginning in Windows PowerShell 3.0, you can get customized help topics for
provider
cmdlets that explain how those cmdlets behave in a file system drive.

To get the help topics that are customized for the file system drive, run a
Get-Help
command in a file system drive or use the -Path
parameter of Get-Help to specify a file
system drive.

PowerShell

Get-Help Get-ChildItem

PowerShell

Get-Help Get-ChildItem -Path env:

See also
about_Providers
about_Environment_Variables
Article • 11/30/2022 • 9 minutes to read

Short description
Describes how to access and manage environment variables in PowerShell.

Long description
Environment variables store data that's 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.

PowerShell can access and manage environment variables in any of the supported
operating system platforms. The PowerShell environment provider lets you get,
add,
change, clear, and delete environment variables in the current console.

Environment variables, unlike other types of variables in PowerShell, are


always stored as
a string and can't be empty. Also unlike other variables,
they're inherited by child
processes, 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 processes.

On Windows, environment variables can be defined in three scopes:

Machine (or System) scope


User scope
Process scope

The Process scope contains the environment variables available in the current
process, or
PowerShell session. This list of variables is inherited from the
parent process and is
constructed from the variables in the Machine and
User scopes.

When you change environment variables in PowerShell, the change affects only
the
current session. This behavior resembles the behavior of the Set command
in the
Windows Command Shell and the Setenv command in UNIX-based
environments. To
change values in the Machine or User scopes, you must use the
methods of the
System.Environment class.
To make changes to Machine-scoped variables, you must also have permission. If
you
try to change a value without sufficient permission, the command fails and
PowerShell
displays an error.

PowerShell provides several different methods for using and managing


environment
variables.

The variable syntax


The Environment provider and Item cmdlets
The .NET System.Environment class

Using the variable syntax


You can display and change the values of environment variables with the
following
syntax:

$Env:<variable-name>

For example, to display the value of the WINDIR environment variable:

PowerShell

$Env:windir

Output

C:\Windows

In this syntax, the dollar sign ( $ ) indicates a variable, and the drive name
( Env: )
indicates an environment variable followed by the variable name
( windir ).

You can create and update the value of environment variables with the following
syntax:

PowerShell

$Env:<variable-name> = "<new-value>"

For example, to create the Foo environment variable:

PowerShell
$Env:Foo = 'An example'

Because environment variables are always strings, you can use them like any
other
variable containing a string. For example:

PowerShell

"The 'Foo' environment variable is set to: $Env:Foo"

$Env:Foo += '!'

$Env:Foo

Output

The 'Foo' environment variable is set to: An example

An example!

Because an environment variable can't be an empty string, setting one to


$null or an
empty string removes it. For example:

PowerShell

$Env:Foo = ''

$Env:Foo | Get-Member -MemberType Properties

Output

Get-Member : You must specify an object for the Get-Member cmdlet.

At line:1 char:12

+ $env:foo | Get-Member

+ ~~~~~~~~~~

+ CategoryInfo : CloseError: (:) [Get-Member],


InvalidOperationException

+ FullyQualifiedErrorId :
NoObjectInGetMember,Microsoft.PowerShell.Commands.GetMemberCommand

Get-Member returned an error because the environment variable was removed.


You can

see that it doesn't return an error when you use it on an empty


string:

PowerShell

'' | Get-Member -MemberType Properties

Output
TypeName: System.String

Name MemberType Definition

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

Length Property int Length {get;}

For more information about variables in PowerShell, see about_Variables.

Using the Environment provider and Item


cmdlets
PowerShell's Environment provider gives you an interface for interacting
with
environment variables in a format that resembles a file system drive. It
lets you get, add,
change, clear, and delete environment variables and values
in PowerShell.

For example, to create the Foo environment variable with a value of Bar :

PowerShell

New-Item -Path Env:\Foo -Value 'Bar'

Output

Name Value

---- -----

Foo Bar

You can also copy the environment variable with Copy-Item , set the value of
an
environment variable with Set-Item , list environment variables with
Get-Item , and
delete the environment variable with Remove-Item .

PowerShell

Copy-Item -Path Env:\Foo -Destination Env:\Foo2 -PassThru

Set-Item -Path Env:\Foo2 -Value 'BAR'

Get-Item -Path Env:\Foo*

Remove-Item -Path Env:\Foo* -Verbose

Output

Name Value

---- -----

Foo2 Bar

Name Value

---- -----

Foo2 BAR

Foo Bar

VERBOSE: Performing the operation "Remove Item" on target "Item: Foo2".

VERBOSE: Performing the operation "Remove Item" on target "Item: Foo".

For more information on using the Environment provider to manage


environment
variables, see about_Environment_Provider.

Using the System.Environment methods


The System.Environment class provides the GetEnvironmentVariable and
SetEnvironmentVariable methods to get and modify environment variables.

The following example creates a new environment variable, Foo , with a value
of Bar and
then returns its value.

PowerShell

[Environment]::SetEnvironmentVariable('Foo','Bar')

[Environment]::GetEnvironmentVariable('Foo')

Output

Bar

You can remove an environment variable with the SetEnvironmentVariable


method by
specifying an empty string for the variable's value. For example,
to remove the Foo
environment variable:

PowerShell

[Environment]::SetEnvironmentVariable('Foo','')

[Environment]::GetEnvironmentVariable('Foo')

Output
For more information about the methods of the System.Environment class, see
Environment Methods.

Saving changes to environment variables


On Windows, there are three methods for making a persistent change to an
environment variable: setting them in your profile, using the
SetEnvironmentVariable
method, and using the System Control Panel.

Saving environment variables in your profile


Any environment variable you add or change in your PowerShell profile is
available in
any session that loads your profile. This method works for any
version of PowerShell on
any supported platform.

For example, to create the CompanyUri environment variable and update the
Path
environment variable to include the C:\Tools folder, add the following
lines to your
PowerShell profile:

PowerShell

$Env:CompanyUri = 'https://internal.contoso.com'

$Env:Path += ';C:\Tools'

You can get the path to your PowerShell profile with the $PROFILE automatic
variable.
For more information on profiles, see about_Profiles.

Saving environment variables with


SetEnvironmentVariable
On Windows, you can specify a scope for the SetEnvironmentVariable method
as the
third parameter to set the environment variable in that scope. The
machine and user
scopes both persist outside of the current process, allowing
you to save a new or
changed environment variable.

For example, to save a new environment variable Foo with the value Bar to
the machine
scope:

PowerShell

[Environment]::SetEnvironmentVariable('Foo', 'Bar', 'Machine')

You can delete an environment variable from the user or machine scope by
setting the
variable's value to an empty string.

PowerShell

[Environment]::SetEnvironmentVariable('Foo', '', 'Machine')

Saving environment variables with the System Control


Panel
In the System Control Panel, you can add or edit existing environment variables
in the
User and System (Machine) scopes. Windows writes these values to
the Registry so that
they persist across sessions and system restarts.

To make a persistent change to an environment variable on Windows using the


System
Control Panel:

1. Open the System Control Panel.


2. Select System.
3. Select Advanced System Settings.
4. Go to the Advanced tab.
5. Select Environment Variables....
6. Make your changes.

PowerShell environment variables


PowerShell features can use environment variables to store user preferences.
These
variables work like preference variables, but they're inherited by child
sessions of the
sessions in which they're created. For more information about
preference variables, see
about_Preference_Variables.

The environment variables that store preferences include:

PSExecutionPolicyPreference

Stores the execution policy set for the current session. This environment
variable
exists only when you set an execution policy for a single session.
You can do this in
two different ways.

Start a session from the command line using the ExecutionPolicy


parameter to
set the execution policy for the session.
Use the Set-ExecutionPolicy cmdlet. Use the Scope parameter with
a value of
Process .

For more information, see about_Execution_Policies.

PSModulePath

The $env:PSModulePath environment variable contains a list of folder


locations that
are searched to find modules and resources.

By default, the effective locations assigned to $env:PSModulePath are:

System-wide locations: These folders contain modules that ship with


PowerShell.
The modules are store in the $PSHOME\Modules location. Also,
This is the location
where the Windows management modules are installed.

User-installed modules: These are modules installed by the user.


Install-
Module has a Scope parameter that allows you to specify
whether the module is
installed for the current user or for all users. For
more information, see Install-
Module.
On Windows, the location of the user-specific CurrentUser scope is
the
$HOME\Documents\PowerShell\Modules folder. The location of the
AllUsers

scope is $env:ProgramFiles\PowerShell\Modules .

In addition, setup programs that install modules in other directories, such


as the
Program Files directory, can append their locations to the value of
$env:PSModulePath .

For more information, see about_PSModulePath.

PSModuleAnalysisCachePath

PowerShell provides control over the file that's used to cache data about
modules
and their cmdlets. The cache is read at startup while searching for a
command and
is written on a background thread sometime after a module is
imported.

The default location of the cache is:


$env:LOCALAPPDATA\Microsoft\Windows\PowerShell

The default filename for the cache is ModuleAnalysisCache .

7 Note
If command discovery isn't working correctly, for example IntelliSense
shows
commands that don't exist, you can delete the cache file. The cache
is
recreated the next time you start PowerShell.

To change the default location of the cache, set the environment variable
before
starting PowerShell. Changes to this environment variable only affect
child
processes. The value should name a full path (including filename) that
PowerShell
has permission to create and write files.

To disable the file cache, set this value to an invalid location, for
example:

PowerShell

# `NUL` here is a special device on Windows that cannot be written to

$env:PSModuleAnalysisCachePath = 'NUL'

This sets the path to the NUL device. PowerShell can't write to the
path but no
error is returned. You can see the errors reported using a
tracer:

PowerShell

Trace-Command -PSHost -Name Modules -Expression {

Import-Module Microsoft.PowerShell.Management -Force

PSDisableModuleAnalysisCacheCleanup

When writing out the module analysis cache, PowerShell checks for modules
that
no longer exist to avoid an unnecessarily large cache. Sometimes these
checks
aren't desirable, in which case you can turn them off by setting this
environment
variable value to 1 .

Setting this environment variable takes effect immediately in the current


process.

Other environment variables used by


PowerShell

Path information
PATH
The $env:PATH environment variable contains a list of folder locations that
the
operating system searches for executable files. On Windows, the list of
folder
locations is separated by the semi-colon ( ; ) character.

PATHEXT

The $env:PATHEXT variable contains a list of file extensions that Windows


considers
to be executable files. When a script file with one of the listed
extensions is
executed from PowerShell, the script runs in the current
console or terminal
session. If the file extension isn't listed, the script
runs in a new console session.

To ensure that scripts for another scripting language run in the current
console
session, add the file extension used by the scripting language. For
example, to run
Python scripts in the current console, add the .py
extension to the environment
variable. For Windows to support the .py
extension as an executable file you must
register the file extension using
the ftype and assoc commands of the CMD
command shell. PowerShell has no
direct method to register the file handler. For
more information, see the
documentation for the ftype command.

PowerShell scripts always start in the current console session. You don't
need to
add the .PS1 extension.

See also
about_Environment_Provider
about_Profiles
about_Variables
Environment Methods
about_Eventlogs
Article • 03/02/2023 • 5 minutes to read

Short description
This article describes how PowerShell logs events to the Windows Event log.

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

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.

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:

PowerShell

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:

PowerShell

Get-EventLog "Windows PowerShell" | Format-Table -GroupBy EventID

Or, type:

PowerShell

Get-EventLog "Windows PowerShell" |

Sort-Object EventID |

Group-Object EventID

To view all the classic event logs, type:

PowerShell

Get-EventLog -List

You can also use the Get-WmiObject cmdlet to use the event-related Windows
Management Instrumentation (WMI) classes to examine the event log. For example,
to
view all the properties of the event log file, type:

PowerShell

Get-WmiObject Win32_NTEventlogFile |

where LogFileName -EQ "Windows PowerShell" |

Format-List -Property *

To find the Win32 event-related WMI classes, type:

PowerShell

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 the start and stop of PowerShell

$LogEngineHealthEvent Logs PowerShell program errors

$LogProviderLifeCycleEvent Logs the start and stop of PowerShell providers

$LogProviderHealthEvent Logs PowerShell provider errors

$LogCommandLifeCycleEvent Logs the starting and completion of commands

$LogCommandHealthEvent Logs command errors

(For information about Windows PowerShell providers, see


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:

PowerShell

$LogCommandLifeCycleEvent

Or, type:

PowerShell

$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:
PowerShell

$LogProviderLifeCycleEvent = $false

You can disable any event, except for the events that indicate that the
Windows
PowerShell engine and the core providers are started. These events are
generated
before the Windows PowerShell profiles are run and before the host
program is ready to
accept commands.

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.

Logging Module Events


Beginning in Windows PowerShell 3.0, you can record execution events for the
cmdlets
and functions in Windows PowerShell modules and snap-ins by setting
the
LogPipelineExecutionDetails property of modules and snap-ins to TRUE. In
Windows
PowerShell 2.0, this feature is available only for snap-ins.

When the LogPipelineExecutionDetails property value is TRUE ( $true ), Windows


PowerShell writes cmdlet and function execution events in the session to the
Windows
PowerShell log in Event Viewer. The setting is effective only in the
current session.

To enable logging of execution events of cmdlets and functions in a module,


use the
following command sequence.

PowerShell

Import-Module <ModuleName>

$m = Get-Module <ModuleName>

$m.LogPipelineExecutionDetails = $true

To enable logging of execution events of cmdlets in a snap-in, use the


following
command sequence.

PowerShell

$m = Get-PSSnapin <SnapInName> [-Registered]

$m.LogPipelineExecutionDetails = $True

To disable logging, use the same command sequence to set the property value to
FALSE
( $false ).
You can also use the "Turn on Module Logging" Group Policy setting to enable
and
disable module and snap-in logging. The policy value includes a list of
module and
snap-in names. Wildcards are supported.

When "Turn on Module Logging" is set for a module, the value of the
LogPipelineExecutionDetails property of the module is TRUE in all sessions and
it cannot
be changed.

The Turn On Module Logging group policy setting is located in the following
Group
Policy paths:

Computer Configuration\

Administrative Templates\

Windows Components\

Windows PowerShell

User Configuration\

Administrative Templates\

Windows Components\

Windows PowerShell

The User Configuration policy takes precedence over the Computer Configuration
policy, and both policies take preference over the value of the
LogPipelineExecutionDetails property of modules and snap-ins.

For more information about this Group Policy setting, see


about_Group_Policy_Settings.

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.

Notes
Authors of module authors can add logging features to their modules. For more
information, see
Writing a Windows PowerShell Module.

See also
about_Group_Policy_Settings
about_Preference_Variables
Get-EventLog
Get-WmiObject
about_Execution_Policies
Article • 09/19/2022 • 9 minutes to read

Short description
Describes the PowerShell execution policies and explains how to manage them.

Long description
PowerShell's execution policy is a safety feature that controls the conditions
under which
PowerShell loads configuration files and runs scripts. This feature
helps prevent the
execution of malicious scripts.

On a Windows computer 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 policies for computers and users.

Execution policies for the local computer and current user are stored in the
registry. You
don't need to set execution policies in your 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 isn't a security system that restricts user actions. For
example, users
can easily bypass 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.

PowerShell execution policies


The PowerShell execution policies are as follows:

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 haven't yet
classified
as trusted or untrusted.
Risks running signed, but malicious, scripts.
Bypass
Nothing is blocked and there are no warnings or prompts.
This execution policy is designed for configurations in which a PowerShell
script is
built in to a larger application or for configurations in which
PowerShell is the
foundation for a program that has its own security model.

Default
Sets the default execution policy.
Restricted for Windows clients.
RemoteSigned for Windows servers.

RemoteSigned
The default execution policy for Windows server computers.
Scripts can run.
Requires a digital signature from a trusted publisher on scripts and
configuration
files that are downloaded from the internet which includes
email and instant
messaging programs.
Doesn't require digital signatures on scripts that are written on the local
computer
and not downloaded from the internet.
Runs scripts that are downloaded from the internet and not signed, if the
scripts
are unblocked, such as by using the Unblock-File cmdlet.
Risks running unsigned scripts from sources other than the internet and
signed
scripts that could be malicious.

Restricted
The default execution policy for Windows client computers.
Permits individual commands, but does not allow scripts.
Prevents running of all script files, including formatting and configuration
files
( .ps1xml ), module script files ( .psm1 ), and PowerShell profiles
( .ps1 ).

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 for Windows clients and
RemoteSigned for Windows Server.
Unrestricted
Unsigned scripts can run. There is a risk of running malicious scripts.
Warns the user before running scripts and configuration files that are
not from the
local intranet zone.

7 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 MachinePolicy, UserPolicy,


Process, CurrentUser, and
LocalMachine. LocalMachine is the
default when setting an execution policy.

The Scope values are listed in precedence order. 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.

MachinePolicy
Set by a Group Policy for all users of the computer.

UserPolicy
Set by a Group Policy for the current user of the computer.

Process
The Process scope only affects the current PowerShell session. The
execution policy is
saved in the environment variable
$env:PSExecutionPolicyPreference , rather than the
registry. When the
PowerShell session is closed, the variable and value are deleted.

CurrentUser
The execution policy affects only the current user. It's stored in the
HKEY_CURRENT_USER registry subkey.

LocalMachine
The execution policy affects all users on the current computer. It's stored in
the
HKEY_LOCAL_MACHINE registry subkey.

Managing the execution policy with PowerShell


To get the effective execution policy for the current PowerShell session, use
the Get-
ExecutionPolicy cmdlet.

The following command gets the effective execution policy:

PowerShell

Get-ExecutionPolicy

To get all of the execution policies that affect the current session and
display them in
precedence order:

PowerShell

Get-ExecutionPolicy -List

The result looks similar to the following sample output:

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
CurrentUser
scope:

PowerShell

Get-ExecutionPolicy -Scope CurrentUser

Change the execution policy


To change the PowerShell execution policy on your Windows computer, use the
Set-
ExecutionPolicy cmdlet. The change is effective immediately. You don't
need to restart
PowerShell.

If you set the execution policy for the scopes LocalMachine or the
CurrentUser, the
change is saved in the registry and remains effective
until you change it again.

If you set the execution policy for the Process scope, it's not saved in
the registry. The
execution policy is retained until the current process and
any child processes are closed.

7 Note

In Windows Vista and later versions of Windows, to run commands that


change the
execution policy for the local computer, LocalMachine scope,
start PowerShell with
the Run as administrator option.

To change your execution policy:

PowerShell

Set-ExecutionPolicy -ExecutionPolicy <PolicyName>

For example:

PowerShell

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned

To set the execution policy in a particular scope:


PowerShell

Set-ExecutionPolicy -ExecutionPolicy <PolicyName> -Scope <scope>

For example:

PowerShell

Set-ExecutionPolicy -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 the execution policy


To remove the execution policy for a particular scope, set the execution policy
to
Undefined.

For example, to remove the execution policy for all the users of the local
computer:

PowerShell

Set-ExecutionPolicy -ExecutionPolicy Undefined -Scope LocalMachine

To remove the execution policy for a Scope:

PowerShell

Set-ExecutionPolicy -ExecutionPolicy Undefined -Scope CurrentUser

If no execution policy is set in any scope, the effective execution policy is


Restricted,
which is the default for Windows clients.

Set a different policy for one session


You can use the ExecutionPolicy parameter of powershell.exe to set an
execution policy
for a new PowerShell session. The policy affects only the
current session and child
sessions.
To set the execution policy for a new session, start PowerShell at the command
line, such
as cmd.exe or from PowerShell, and then use the
ExecutionPolicy parameter of
powershell.exe to set the execution
policy.

For example:

PowerShell

powershell.exe -ExecutionPolicy AllSigned

The execution policy that you set isn't stored in the registry. Instead, it's
stored in the
$env:PSExecutionPolicyPreference environment variable. The
variable is deleted when

you close the session in which the policy is set. You


cannot change the policy by editing
the variable value.

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 doesn't take precedence over the
execution policy set by using a Group
Policy.

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 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 and remote signed scripts RemoteSigned

Allow only signed scripts AllSigned

If Turn on Script Execution is not configured, it has no effect. The


execution policy
set in PowerShell is effective.
The PowerShellExecutionPolicy.adm and PowerShellExecutionPolicy.admx files add
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.

For more information, see about_Group_Policy_Settings.

Execution policy precedence


When determining the effective execution policy for a session, PowerShell
evaluates the
execution policies in the following precedence order:

Group Policy: MachinePolicy

Group Policy: UserPolicy

Execution Policy: Process (or pwsh.exe -ExecutionPolicy)

Execution Policy: CurrentUser

Execution Policy: LocalMachine

Manage signed and unsigned scripts


In Windows, programs like Internet Explorer and Microsoft Edge add an alternate
data
stream to files that are downloaded. This marks the file as "coming from
the Internet". If
your PowerShell execution policy is RemoteSigned,
PowerShell won't run unsigned
scripts that are downloaded from the internet
which includes email and instant
messaging programs.

You can sign the script or elect to run an unsigned script without changing the
execution policy.

Beginning in PowerShell 3.0, you can use the Stream parameter of the
Get-Item cmdlet
to detect files that are blocked because they were downloaded
from the internet. Use
the Unblock-File cmdlet to unblock the scripts so that
you can run them in PowerShell.

For more information, see about_Signing,


Get-Item, and
Unblock-File.

7 Note

Other methods of downloading files may not mark the files as coming from the
Internet Zone. Some examples include:

curl.exe

Invoke-RestMethod

Invoke-WebRequest

Execution policy on Windows Server Core and


Window Nano Server
When PowerShell 5.1 is run on Windows Server Core or Windows Nano Server under
certain conditions, execution policies can fail with the following error:

Output

AuthorizationManager check failed.

At line:1 char:1

+ C:\scriptpath\scriptname.ps1

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : SecurityError: (:) [], PSSecurityException

+ FullyQualifiedErrorId : UnauthorizedAccess

PowerShell uses APIs in the Windows Desktop Shell ( explorer.exe ) to validate


the Zone
of a script file. The Windows Shell is not available on Windows Server
Core and
Windows Nano Server.

You could also get this error on any Windows system if the Windows Desktop
Shell is
unavailable or unresponsive. For example, during sign on, a PowerShell
logon script
could start execution before the Windows Desktop is ready,
resulting in failure.

Using an execution policy of ByPass or AllSigned does not require a


Zone check which
avoids the problem.

See also
about_Environment_Variables
about_Group_Policy_Settings
about_PowerShell_exe
about_Signing
Get-ExecutionPolicy
Set-ExecutionPolicy
Get-Item
Unblock-File
about_FileSystem_Provider
Article • 01/10/2023 • 11 minutes to read

Provider name
FileSystem

Drives
C: , D: , Temp: ...

Capabilities
Filter, ShouldProcess

Short description
Provides access to files and directories.

Detailed description
The PowerShell FileSystem provider lets you get, add, change, clear, and
delete files and
directories in PowerShell.

The FileSystem drives are a hierarchical namespace containing the


directories and files
on your computer. A FileSystem drive can be a logical
or physical drive, directory, or
mapped network share.

The FileSystem provider supports the following cmdlets, which are covered
in this
article.

Get-Location
Set-Location
Get-Item
Get-ChildItem
Invoke-Item
Move-Item
New-Item
Remove-Item
Get-ItemProperty
Set-ItemProperty
Clear-Item
Clear-ItemProperty
Remove-Item
Remove-ItemProperty
Get-Acl
Set-Acl
Get-AuthenticodeSignature
Set-AuthenticodeSignature
Add-Content
Clear-Content
Get-Content
Set-Content

Types exposed by this provider


Files are instances of the System.IO.FileInfo class. Directories are
instances of the
System.IO.DirectoryInfo class.

The PowerShell Extended Type System adds extra properties to these object types
to
provide additional information. Some information is platform specific. For
example, the
possible values of the LinkType property depend on the
platform and filesystem being
used. On Windows, NTFS supports HardLink ,
SymLink , and Junction values for
LinkType. Linux and macOS filesystems
only support HardLink and SymLink .

Navigating the FileSystem drives


The FileSystem provider exposes its data stores by mapping any logical
drives on the
computer as PowerShell drives. To work with a FileSystem
drive you can change your
location to a drive using the drive name followed by
a colon ( : ).

PowerShell

Set-Location C:

You can also work with the FileSystem provider from any other PowerShell
drive. To
reference a file or directory from another location, use the drive
name ( C: , D: , ...) in the
path.
7 Note

PowerShell uses aliases to allow you a familiar way to work with provider
paths.
Commands such as dir and ls are now aliases for
Get-ChildItem , cd is an alias
for Set-Location . and pwd is an
alias for Get-Location .

Getting files and directories


The Get-ChildItem cmdlet returns all files and directories in the
current location. You
can specify a different path to search and use built
in parameters to filter and control
the recursion depth.

PowerShell

Get-ChildItem

To read more about cmdlet usage, see Get-ChildItem.

Copying files and directories


The Copy-Item cmdlet copies files and directories to a location you specify.
Parameters
are available to filter and recurse, similar to Get-ChildItem .

The following command copies all of the files and directories under the path
C:\temp\
to the folder C:\Windows\Temp .

PowerShell

Copy-Item -Path C:\temp\* -Destination C:\Windows\Temp -Recurse -File

Copy-Item overwrites files in the destination directory without prompting for


confirmation.

This command copies the a.txt file from the C:\a directory to the C:\a\bb
directory.

PowerShell

Copy-Item -Path C:\a\a.txt -Destination C:\a\bb\a.txt

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 fails
unless you specify the Force parameter.

PowerShell

Copy-Item -Path C:\a\* -Destination C:\c -Recurse

For more information, see Copy-Item.

Moving files and directories


This command moves the c.txt file in the C:\a directory to the C:\a\aa
directory:

PowerShell

Move-Item -Path C:\a\c.txt -Destination C:\a\aa

By default, the cmdlet doesn't overwrite an existing file that has the same
name. To force
the cmdlet to overwrite an existing file, specify the Force
parameter.

You can't move a directory when that directory is the current location. When
you use
Move-Item to move the directory at the current location, you see
this error.

C:\temp> Move-Item -Path C:\temp\ -Destination C:\Windows\Temp

Move-Item : Cannot move item because the item at 'C:\temp\' is in use.

At line:1 char:1

+ Move-Item C:\temp\ C:\temp2\

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : InvalidOperation: (:) [Move-Item],


PSInvalidOperationException

+ FullyQualifiedErrorId :
InvalidOperation,Microsoft.PowerShell.Commands.MoveItemCommand

Managing file content

Get the content of a file


This command gets the contents of the "Test.txt" file and displays them in the
console.
PowerShell

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:

PowerShell

Get-Content -Path Test.txt | ConvertTo-Html

You can also retrieve the content of a file by prefixing its provider path with
the dollar
sign ( $ ). The path must be enclosed in curly braces due to
variable naming restrictions.
For more information, see about_Variables.

PowerShell

${C:\Windows\System32\Drivers\etc\hosts}

Add content to a file


This command appends the "test content" string to the Test.txt file:

PowerShell

Add-Content -Path test.txt -Value "test content"

The existing content in the Test.txt file isn't deleted.

Replace the content of a file


This command replaces the contents of the Test.txt file with the "test
content" string:

PowerShell

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.
Loop through the contents of a file
By default, the Get-Content cmdlet uses the end-of-line character as its
delimiter, so it
gets a file as a collection of strings, with each line as one
string in the file.

You can use the Delimiter parameter to specify an alternate delimiter. If


you set it to the
characters that denote the end of a section or the beginning
of the next section, you can
split the file into logical parts.

The first command gets the Employees.txt file and splits it into sections,
each of which
ends with the words "End of Employee Record" and it saves it in
the $e variable.

The second command uses array notation to get the first item in the collection
in $e . It
uses an index of 0, because PowerShell arrays are zero-based.

For more information about Get-Content cmdlet, see the help topic for the
Get-Content .

For more information about arrays, see about_Arrays.

PowerShell

$e = Get-Content c:\test\employees.txt -Delimited "End Of Employee Record"

$e[0]

Managing security descriptors

View the ACL for a file


This command returns a System.Security.AccessControl.FileSecurity object:

PowerShell

Get-Acl -Path test.txt | Format-List -Property *

For more information about this object, pipe the command to the
Get-Member cmdlet
or see the FileSecurity Class.

Creating files and directories

Create a directory
This command creates the logfiles directory on the C drive:

PowerShell

New-Item -Path c:\ -Name logfiles -Type directory

PowerShell also includes a mkdir function (alias md ) that uses the


New-Item cmdlet to
create a new directory.

Create a file
This command creates the log2.txt file in the C:\logfiles directory and
then adds the
"test log" string to the file:

PowerShell

New-Item -Path c:\logfiles -Name log2.txt -Type file

Create a file with content


Creates a file called log2.txt in the C:\logfiles directory and adds the
string "test log"
to the file.

PowerShell

New-Item -Path c:\logfiles -Name log2.txt -Type file -Value "test log"

Renaming files and directories

Rename a file
This command renames the a.txt file in the C:\a directory to b.txt :

PowerShell

Rename-Item -Path c:\a\a.txt -NewName b.txt

Rename a directory
This command renames the C:\a\cc directory to C:\a\dd :

PowerShell

Rename-Item -Path c:\a\cc -NewName dd

Deleting files and directories

Delete a file
This command deletes the Test.txt file in the current directory:

PowerShell

Remove-Item -Path test.txt

Delete files using wildcards


This command deletes all the files in the current directory that have the
.xml file name
extension:

PowerShell

Remove-Item -Path *.xml

Starting a program by invoking an associated


file

Invoke a file
The Get-Service cmdlet to get information about local services and pipes
the
information to the Export-Csv cmdlet to store the information in the
Services.csv file.

Then Invoke-Item opens the services.csv file in the program associated


with the .csv
extension:

PowerShell
Get-Service | Export-Csv -Path services.csv

Invoke-Item -Path services.csv

Getting files and folders with specified


attributes

Get System files


This command gets system files in the current directory and its subdirectories.

It uses the File parameter to get only files (not directories) and the
System parameter to
get only items with the "system" attribute.

It uses the Recurse parameter to get the items in the current directory and
all
subdirectories.

PowerShell

Get-ChildItem -File -System -Recurse

Get Hidden files


This command gets all files, including hidden files, in the current directory.

It uses the Attributes parameter with two values, !Directory+Hidden ,


which gets hidden
files, and !Directory , which gets all other files.

PowerShell

Get-ChildItem -Attributes !Directory,!Directory+Hidden

dir -att !d,!d+h is the equivalent of this command.

Get Compressed and Encrypted files


This command gets files in the current directory that are either compressed or
encrypted.

It uses the Attributes parameter with two values, Compressed and


Encrypted . The values
are separated by a comma , which represents the "OR"
operator.
PowerShell

Get-ChildItem -Attributes Compressed,Encrypted

Dynamic parameters
Dynamic parameters are cmdlet parameters that are added by a PowerShell
provider
and are available only when the cmdlet is being used in the
provider-enabled drive.

Encoding <FileSystemCmdletProviderEncoding>
Specifies the file encoding. The default is ASCII.

Ascii Uses ASCII (7-bit) character set.

BigEndianUnicode Uses UTF-16 with the big-endian byte order.


BigEndianUTF32 Uses UTF-32 with the big-endian byte order.

Byte Encodes a set of characters into a sequence of bytes.

Default Uses the encoding that corresponds to the system's active code page
(usually ANSI).
Oem Uses the encoding that corresponds to the system's current OEM code page.
String Same as Unicode .

Unicode Uses UTF-16 with the little-endian byte order.


Unknown Same as Unicode .

UTF7 Uses UTF-7.

UTF8 Uses UTF-8.


UTF32 Uses UTF-32 with the little-endian byte order.

Cmdlets supported
Add-Content

Get-Content
Set-Content

Delimiter <String>
Specifies the delimiter that Get-Content uses to divide the file into
objects while it reads.

The default is \n , the end-of-line character.


When reading a text file, Get-Content returns a collection of string
objects, each of
which ends with the delimiter character.

Entering a delimiter that doesn't exist in the file, Get-Content returns


the entire file as a
single, un-delimited object.

You can use this parameter to split a large file into smaller files by
specifying a file
separator, such as "End of Example", as the delimiter. The
delimiter is preserved (not
discarded) and becomes the last item in each file
section.

7 Note

Currently, when the value of the Delimiter parameter is an empty string,


Get-
Content doesn't return anything. This is a known issue. To force
Get-Content to

return the entire file as a single, undelimited string,


enter a value that doesn't exist
in the file.

Cmdlets supported

Get-Content

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

Attributes <FlagsExpression>
Gets files and folders with the specified attributes. This parameter supports
all attributes
and lets you specify complex combinations of attributes.

The Attributes parameter was introduced in Windows PowerShell 3.0.

The Attributes parameter supports the following attributes:


Archive
Compressed
Device
Directory
Encrypted
Hidden
Normal
NotContentIndexed
Offline
ReadOnly
ReparsePoint
SparseFile
System
Temporary

For a description of these attributes, see the FileAttributes


enumeration.

Use the following operators to combine attributes.

! - NOT
+ - AND

, - OR

No spaces are permitted between an operator and its attribute. However, spaces
are
permitted before commas.

Cmdlets supported

Get-ChildItem

Directory <SwitchParameter>
Gets directories (folders).

The Directory parameter was introduced in Windows PowerShell 3.0.

To get only directories, use the Directory parameter and omit the File
parameter. To
exclude directories, use the File parameter and omit the
Directory parameter, or use the
Attributes parameter.

Cmdlets supported
Get-ChildItem

File <SwitchParameter>
Gets files.

The File parameter was introduced in Windows PowerShell 3.0.

To get only files, use the File parameter and omit the Directory
parameter. To exclude
files, use the Directory parameter and omit the
File parameter, or use the Attributes
parameter.

Cmdlets supported

Get-ChildItem

Hidden <SwitchParameter>
Gets only hidden files and directories (folders). By default,
Get-ChildItem gets only
non-
hidden items.

The Hidden parameter was introduced in Windows PowerShell 3.0.

To get only hidden items, use the Hidden parameter, its h or ah aliases,
or the Hidden
value of the Attributes parameter. To exclude hidden
items, omit the Hidden parameter
or use the Attributes parameter.

Cmdlets supported
Get-ChildItem

ReadOnly <SwitchParameter>
Gets only read-only files and directories (folders).

The ReadOnly parameter was introduced in Windows PowerShell 3.0.

To get only read-only items, use the ReadOnly parameter, its ar alias, or
the ReadOnly
value of the Attributes parameter. To exclude read-only
items, use the Attributes
parameter.
Cmdlets supported
Get-ChildItem

System <SwitchParameter>
Gets only system files and directories (folders).

The System parameter was introduced in Windows PowerShell 3.0.

To get only system files and folders, use the System parameter, its as
alias, or the
System value of the Attributes parameter. To exclude
system files and folders, use the
Attributes parameter.

Cmdlets supported
Get-ChildItem

NewerThan <DateTime>
Returns $True when the LastWriteTime value of a file is greater than the
specified date.
Otherwise, it returns $False .

Enter a DateTime object, such as one that the Get-Date cmdlet


returns, or a string that
can be converted to a DateTime object, such as
"August 10, 2011 2:00 PM" .

Cmdlets supported

Test-Path

OlderThan <DateTime>
Returns $True when the LastWriteTime value of a file is less than the
specified date.
Otherwise, it returns $False .

Enter a DateTime object, such as one that the Get-Date cmdlet


returns, or a string that
can be converted to a DateTime object, such as
"August 10, 2011 2:00 PM" .

Cmdlets supported

Test-Path
Stream <String>
Manages alternate data streams. Enter the stream name. Wildcards are permitted
only in
Get-Item for and
Remove-Item commands in a
file system drive.

Cmdlets supported

Add-Content
Clear-Content

Get-Item
Get-Content

Remove-Item
Set-Content

Raw <SwitchParameter>
Ignores newline characters. Returns contents as a single item.

Cmdlets supported
Get-Content

ItemType <String>
This parameter allows you to specify the tye of item to create with New-Item

The available values of this parameter depend on the current provider you are
using.

In a FileSystem drive, the following values are allowed:

File
Directory
SymbolicLink
Junction
HardLink

Cmdlets supported
New-Item
Using the pipeline
Provider cmdlets accept pipeline input. You can use the pipeline to simplify
task by
sending provider data from one cmdlet to another provider cmdlet. To
read more about
how to use the pipeline with provider cmdlets, see the cmdlet
references provided
throughout this article.

Getting help
Beginning in Windows PowerShell 3.0, you can get customized help topics for
provider
cmdlets that explain how those cmdlets behave in a file system drive.

To get the help topics that are customized for the file system drive, run a
Get-Help
command in a file system drive or use the Path parameter of
Get-Help to specify a file
system drive.

PowerShell

Get-Help Get-ChildItem

PowerShell

Get-Help Get-ChildItem -Path c:

See also
about_Providers
about_For
Article • 09/19/2022 • 4 minutes to read

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

Support for multiple operations


The following syntaxes are supported for multiple assignment operations in the
Init
statement:

PowerShell

# Comma separated assignment expressions enclosed in parenthesis.

for (($i = 0), ($j = 0); $i -lt 10; $i++)

"`$i:$i"

"`$j:$j"

# Sub-expression using the semicolon to separate statements.

for ($($i = 0;$j = 0); $i -lt 10; $i++)

"`$i:$i"

"`$j:$j"

The following syntaxes are supported for multiple assignment operations in the
Repeat
statement:

PowerShell

# Comma separated assignment expressions.

for (($i = 0), ($j = 0); $i -lt 10; $i++, $j++)

"`$i:$i"

"`$j:$j"

# Comma separated assignment expressions enclosed in parenthesis.

for (($i = 0), ($j = 0); $i -lt 10; ($i++), ($j++))

"`$i:$i"

"`$j:$j"

# Sub-expression using the semicolon to separate statements.

for ($($i = 0;$j = 0); $i -lt 10; $($i++;$j++))

"`$i:$i"

"`$j:$j"

7 Note

Operations other than pre or post increment may not work with all syntaxes.

For multiple Conditions use logical operators as demonstrated by the


following
example.

PowerShell

for (($i = 0), ($j = 0); $i -lt 10 -and $j -lt 10; $i++,$j++)

"`$i:$i"

"`$j:$j"

For more information, see about_Logical_Operators.

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.

PowerShell

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

PowerShell

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.

PowerShell

$i=1

for (;;$i++)

Write-Host $i

This statement will still repeat indefinitely until you break out of the
command by
pressing CTRL+C.

You can terminate the For loop using a condition. You can place a
condition using the
Condition portion of the For statement. The For
loop terminates 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.

PowerShell

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

PowerShell

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 a For that uses
this alternative syntax.

PowerShell

for ($i = 0

$i -lt 10

$i++){

$i

This alternative form of the For statement works in PowerShell script files
and at the
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.

PowerShell

for ($i = 0; $i -le 20; $i += 2)

Write-Host $i

The For loop can also be written on one line as in the following example.

PowerShell

for ($i = 0; $i -lt 10; $i++) { Write-Host $i }

See also
about_Comparison_Operators
about_Foreach
about_Foreach
Article • 09/19/2022 • 4 minutes to read

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 part of the foreach statement enclosed in parenthesis represents a


variable and a
collection to iterate. 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.

PowerShell

$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, PowerShell exits
the loop.

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.

PowerShell

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):

PowerShell

foreach ($file in Get-ChildItem)

if ($file.length -gt 100KB)

Write-Host $file

In this example, the foreach loop uses a property of the $file variable to
perform a
comparison operation ( $file.length -gt 100KB ). 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, PowerShell returns the length
and the last access time
inside the statement list:

PowerShell
foreach ($file in Get-ChildItem)

if ($file.length -gt 100KB)

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:

PowerShell

$i = 0

foreach ($file in Get-ChildItem) {

if ($file.length -gt 100KB) {

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:

PowerShell

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

In the following example, the function defined parses PowerShell scripts and
script
modules and returns the location of functions contained within. The
example
demonstrates how to use the MoveNext method (which works similarly
to skip X on a
For loop) and the Current property of the $foreach
variable inside of a foreach script

block. The example function can find


functions in a script even if there are unusually- or
inconsistently-spaced
function definitions that span multiple lines.

For more information, see Using Enumerators.

PowerShell

function Get-FunctionPosition {

[CmdletBinding()]

[OutputType('FunctionPosition')]

param(

[Parameter(Position = 0, Mandatory,

ValueFromPipeline, ValueFromPipelineByPropertyName)]

[ValidateNotNullOrEmpty()]

[Alias('PSPath')]

[System.String[]]

$Path

process {

try {

$filesToProcess = if ($_ -is [System.IO.FileSystemInfo]) {

Write-Verbose "From pipeline"

$_

} else {

Write-Verbose "From parameter, $Path"

Get-Item -Path $Path

$parser = [System.Management.Automation.Language.Parser]

Write-Verbose "lets start the foreach loop on `$filesToProcess with


$($filesToProcess.count) as count"

foreach ($item in $filesToProcess) {

Write-Verbose "$item"

if ($item.PSIsContainer -or

$item.Extension -notin @('.ps1', '.psm1')) {

continue

$tokens = $errors = $null

$parser::ParseFile($item.FullName, ([REF]$tokens),

([REF]$errors)) | Out-Null

if ($errors) {

$msg = "File '{0}' has {1} parser errors." -f $item.FullName,

$errors.Count

Write-Warning $msg

:tokenLoop foreach ($token in $tokens) {

if ($token.Kind -ne 'Function') {

continue

$position = $token.Extent.StartLineNumber

do {

if (-not $foreach.MoveNext()) {

break tokenLoop

$token = $foreach.Current

} until ($token.Kind -in @('Generic', 'Identifier'))

$functionPosition = [pscustomobject]@{

Name = $token.Text

LineNumber = $position

Path = $item.FullName

Add-Member -InputObject $functionPosition `

-TypeName FunctionPosition -PassThru

catch {

throw

See also
about_Automatic_Variables
about_If
ForEach-Object
about_Format.ps1xml
Article • 09/19/2022 • 10 minutes to read

Short description
The Format.ps1xml files in PowerShell define the default display of objects
in the
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
PowerShell.

Long description
The Format.ps1xml files in PowerShell define the default display of objects
in 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 PowerShell.

When 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 doesn't affect which object
properties are
passed down the pipeline or how they're passed. Format.ps1xml
files can't be used to
customize the output format for hash tables.

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:

1. Certificate.Format.ps1xml

Objects in the Certificate store, such as X.509 certificates and certificate


stores.

2. DotNetTypes.Format.ps1xml

Other .NET Framework types, such as CultureInfo, FileVersionInfo, and


EventLogEntry objects.

3. FileSystem.Format.ps1xml

File system objects, such as files and directories.


4. Help.Format.ps1xml

Help views, such as detailed and full views, parameters, and examples.

5. PowerShellCore.Format.ps1xml

Objects generated by PowerShell core cmdlets, such as Get-Member and


Get-
History .

6. PowerShellTrace.Format.ps1xml

Trace objects, such as those generated by the Trace-Command cmdlet.

7. Registry.Format.ps1xml

Registry objects, such as keys and entries.

A formatting file can define four different views of each object:

Table
List
Wide
Custom

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.

When a formatting file includes more than one view of an object, PowerShell
applies the
first view that it finds.

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 PowerShell are digitally signed to
prevent
tampering because the formatting can include script blocks. 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 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 PowerShell, but it's useful
to place the files in the
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.
You can then delete all the other views in
the file so that the changes are obvious to
anyone examining the file.

After you save the changes, use the Update-FormatData cmdlet to add the new
file to
your PowerShell session. If you want your view to take precedence over
a view defined
in the built-in files, use the PrependPath parameter.
Update-FormatData affects only the
current session. To make the change to all
future sessions, add the Update-FormatData
command to your 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 in
the current
PowerShell session. 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:

PowerShell

$Parms = @{

Path = "$PSHOME\*Format.ps1xml"

Pattern = "System.Globalization.CultureInfo"

Select-String @Parms

Output

C:\Windows\System32\WindowsPowerShell\v1.0\DotNetTypes.format.ps1xml:113:

<Name>System.Globalization.CultureInfo</Name>

C:\Windows\System32\WindowsPowerShell\v1.0\DotNetTypes.format.ps1xml:115:

<TypeName>System.Globalization.CultureInfo</TypeName>

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 .

PowerShell

Copy-Item $PSHome\DotNetTypes.format.ps1xml MyDotNetTypes.Format.ps1xml

Open the MyDotNetTypes.Format.ps1xml file in any XML or text editor, such as


Visual
Studio Code. Find the System.Globalization.CultureInfo object
section. The following
XML defines the views of the CultureInfo object. The
object has only a TableControl
view.

XML

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

</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
<ViewDefinitions> and <Configuration> tags. If
there is a digital
signature, delete it from your custom Format.ps1xml file.

The MyDotNetTypes.Format.ps1xml file should now look like the following


sample:

XML

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

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 specify a

value of 45 characters as the <Width> .


XML

<TableHeaders>

<TableColumnHeader>

<Width>16</Width>

</TableColumnHeader>

<TableColumnHeader>

<Width>16</Width>

</TableColumnHeader>

<TableColumnHeader>

<Width>45</Width>

</TableColumnHeader>

<TableColumnHeader/>

</TableHeaders>

Add a new column item for Calendar in the table rows using the
<TableColumnItem> and
<PropertyName tags:

XML

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

Save and close the file. Use Update-FormatData to add the new format file to
the current
PowerShell session.

This example uses the PrependPath parameter to place the new file in a
higher
precedence order than the original file. For more information, see
Update-FormatData.

PowerShell

Update-FormatData -PrependPath $PSHOME\MyDotNetTypes.Format.ps1xml

To test the change, type Get-Culture and review the output that includes the
Calendar
property.

PowerShell

Get-Culture

Output

LCID Name Calendar DisplayName

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

1033 en-US System.Globalization.GregorianCalendar English (United States)

The XML in Format.ps1xml files


The full schema definition can be found in Format.xsd
in the PowerShell source code
repository on GitHub.

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> identifies the name of the view.

<ViewSelectedBy> specifies the object type or types to which the view


applies.
<GroupBy> specifies how items in the view will be combined in groups.

<TableControl> , <ListControl> , <WideControl> , and <CustomControl>


contain the
tags that specify how each item will be displayed.

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

GroupBy 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
<CustomControlName> tag that references
a custom control defined elsewhere
using a <Control> tag. The <Control> tag contains
a <Name> tag and a
<CustomControl> tag.
TableControlTag
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.

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

ListControl tag
The <ListControl> tag typically contains a <ListEntries> tag. The
<ListEntries> tag
contains a <ListEntry> tag. The <ListEntry> 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> and
<ListEntry> tags 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.

WideControl tag
The <WideControl> tag typically contains a <WideEntries> tag. The
<WideEntries> tag
contains one or more <WideEntry> tags. A <WideEntry> tag
contains one <WideItem>
tag.

A <WideItem> tag must include either a <PropertyName> tag or a


<ScriptBlock> tag. A
<PropertyName> tag specifies the property to display at
the specified location in the view.
A <ScriptBlock> tag specifies a script to
evaluate and display at the specified location in
the view.

A <WideItem> tag can contain a <FormatString> tag that specifies how to


display the
property.

CustomControl tag
The <CustomControl> tag lets you use a script block to define a format. A
<CustomControl> tag typically contains a <CustomEntries> tag that contains
multiple
<CustomEntry> tags. Each <CustomEntry> tag contains a
<CustomItem> tag that can

contain a variety of tags that specify contents and


formatting of the specified location in
the view, including <Text> ,
<Indentation> , <ExpressionBinding> , and <NewLine> tags.

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, see 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
FormatViewBinding

For more information, see


Trace-Command and
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, see
about_Signing.

Sample XML for a Format-Table custom view


The following sample creates a Format-Table custom view for the
System.IO.DirectoryInfo and System.IO.FileInfo objects created by
Get-ChildItem . The
custom view is named mygciview and adds the
CreationTime column to the table.

The custom view is created from an edited version of the


FileSystem.Format.ps1xml file
that's stored in $PSHOME on PowerShell 5.1.

After your custom .ps1xml file is saved, use Update-FormatData to include


the view in a
PowerShell session. For this example, the custom view must use
the table format,
otherwise, Format-Table fails.

Use Format-Table with the View parameter to specify the custom view's
name and
format the table's output. For an example of how the command is run,
see Format-Table.

PowerShell

$Parms = @{

Path = "$PSHOME\*Format.ps1xml"

Pattern = "System.IO.DirectoryInfo"

Select-String @Parms

Copy-Item $PSHome\FileSystem.format.ps1xml .\MyFileSystem.Format.ps1xml

Update-FormatData -PrependPath $PSHOME\Format\MyFileSystem.Format.ps1xml

7 Note

To fit the XML sample within line width limitations, it was necessary to
compress
some indentation and use line breaks within the code.

XML

<?xml version="1.0" encoding="utf-8" ?>

<Configuration>

<SelectionSets>

<SelectionSet>

<Name>FileSystemTypes</Name>

<Types>

<TypeName>System.IO.DirectoryInfo</TypeName>

<TypeName>System.IO.FileInfo</TypeName>

</Types>

</SelectionSet>

</SelectionSets>

<Controls>

<Control>

<Name>FileSystemTypes-GroupingFormat</Name>

<CustomControl>

<CustomEntries>

<CustomEntry>

<CustomItem>

<Frame>

<LeftIndent>4</LeftIndent>

<CustomItem>

<Text AssemblyName="System.Management.Automation"

BaseName="FileSystemProviderStrings"

ResourceId="DirectoryDisplayGrouping"/>

<ExpressionBinding>
<ScriptBlock>

$_.PSParentPath.Replace("Microsoft.PowerShell.Core\FileSystem::", "")

</ScriptBlock>

</ExpressionBinding>

<NewLine/>

</CustomItem>

</Frame>

</CustomItem>

</CustomEntry>

</CustomEntries>

</CustomControl>

</Control>

</Controls>

<ViewDefinitions>

<View>

<Name>mygciview</Name>

<ViewSelectedBy>

<SelectionSetName>FileSystemTypes</SelectionSetName>

</ViewSelectedBy>

<GroupBy>

<PropertyName>PSParentPath</PropertyName>

<CustomControlName>FileSystemTypes-GroupingFormat</CustomControlName>

</GroupBy>

<TableControl>

<TableHeaders>

<TableColumnHeader>

<Label>Mode</Label>

<Width>7</Width>

<Alignment>left</Alignment>

</TableColumnHeader>

<TableColumnHeader>

<Label>LastWriteTime</Label>

<Width>25</Width>

<Alignment>right</Alignment>

</TableColumnHeader>

<TableColumnHeader>

<Label>CreationTime</Label>

<Width>25</Width>

<Alignment>right</Alignment>

</TableColumnHeader>

<TableColumnHeader>

<Label>Length</Label>

<Width>14</Width>

<Alignment>right</Alignment>

</TableColumnHeader>

<TableColumnHeader/>

</TableHeaders>

<TableRowEntries>

<TableRowEntry>

<Wrap/>

<TableColumnItems>

<TableColumnItem>

<PropertyName>Mode</PropertyName>

</TableColumnItem>

<TableColumnItem>

<ScriptBlock>

[String]::Format("{0,10} {1,8}",

$_.LastWriteTime.ToString("d"),

$_.LastWriteTime.ToString("t"))

</ScriptBlock>

</TableColumnItem>

<TableColumnItem>

<ScriptBlock>

[String]::Format("{0,10} {1,8}",

$_.CreationTime.ToString("d"),

$_.LastWriteTime.ToString("t"))

</ScriptBlock>

</TableColumnItem>

<TableColumnItem>

<PropertyName>Length</PropertyName>

</TableColumnItem>

<TableColumnItem>

<PropertyName>Name</PropertyName>

</TableColumnItem>

</TableColumnItems>

</TableRowEntry>

</TableRowEntries>

</TableControl>

</View>

</ViewDefinitions>

</Configuration>

See also
Trace-Command
Export-FormatData
Get-FormatData
Update-FormatData
Get-TraceSource
Format Schema XML Reference
Writing a PowerShell Formatting File
about_Functions
Article • 01/23/2023 • 12 minutes to read

Short description
Describes how to create and use functions in PowerShell.

Long description
A function is a list of PowerShell 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.

Functions can be as simple as:

PowerShell

function Get-PowerShellProcess { Get-Process PowerShell }

A function can also be as complex as a cmdlet or an application.

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. You can also specify a return value using
the return
keyword. The return keyword doesn't affect or suppress other
output returned from
your function. However, the return keyword exits the
function at that line. For more
information, see about_Return.

The function's statement list can contain different types of statement lists
with the
keywords begin , process , end , and clean . These statement lists
handle input from the
pipeline differently.

The filter keyword is used to create 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.

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

Within script files and script-based modules, functions must be defined


before they
can be called.

Syntax
The following are the syntax for a function:

Syntax

function [<scope:>]<name> [([type]$parameter1[,[type]$parameter2])]

begin {<statement list>}

process {<statement list>}

end {<statement list>}

Syntax

function [<scope:>]<name>

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 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 don't have to be complicated to be useful. The simplest functions
have the
following format:

Syntax

function <function-name> {statements}

For example, the following function starts PowerShell with the Run as
Administrator
option.

PowerShell

function Start-PSAdmin {Start-Process PowerShell -Verb RunAs}

To use the function, type: Start-PSAdmin

To add statements to the function, type each statement on a separate line, or


use a
semicolon ; to separate the statements.

For example, the following function finds all .jpg files in the current
user's directories
that were changed after the start date.

PowerShell

function Get-NewPix

$start = Get-Date -Month 1 -Day 1 -Year 2010

$allpix = Get-ChildItem -Path $env:UserProfile\*.jpg -Recurse

$allpix | Where-Object {$_.LastWriteTime -gt $Start}

You can create a toolbox of useful small functions. Add these functions to your
PowerShell profile, as described in about_Profiles and later in this
topic.

Function Names
You can assign any name to a function, but functions that you share with others
should
follow the naming rules that have been established for all PowerShell
commands.

Functions names should consist of a verb-noun pair where the verb identifies
the action
that the function performs and the noun identifies the item on which
the cmdlet
performs its action.
Functions should use the standard verbs that have been approved for all
PowerShell
commands. These verbs help us to keep our command names consistent
and easy for
users to understand.

For more information about the standard PowerShell verbs, see


Approved Verbs.

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:

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:

Syntax

function <name> [([type]$parameter1[,[type]$parameter2])] {

<statement list>

Below is an example of this alternative syntax.

PowerShell

function Add-Numbers([int]$one, [int]$two) {

$one + $two

While the first method is preferred, there is no difference between these two
methods.

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 Get-SmallFiles . 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:

PowerShell

function Get-SmallFiles {

Param($Size)

Get-ChildItem $HOME | Where-Object {

$_.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:

PowerShell

Get-SmallFiles -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:

PowerShell

Get-SmallFiles 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
Get-SmallFiles example:

PowerShell

function Get-SmallFiles ($Size = 100) {

Get-ChildItem $HOME | Where-Object {

$_.Length -lt $Size -and !$_.PSIsContainer

If you type Get-SmallFiles without a value, the function assigns 100 to


$size . If you
provide a value, the function uses that value.

Optionally, you can provide a brief help string that describes the default
value of your
parameter, by adding the PSDefaultValue attribute to the
description of your parameter,
and specifying the Help property of
PSDefaultValue. To provide a help string that
describes the default value
(100) of the Size parameter in the Get-SmallFiles function,
add the
PSDefaultValue attribute as shown in the following example.

PowerShell

function Get-SmallFiles {

param (

[PSDefaultValue(Help = '100')]

$Size = 100

For more information about the PSDefaultValue attribute class, see


PSDefaultValue
Attribute Members.

Positional Parameters
A positional parameter is a parameter without a parameter name. 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 Get-Extension function adds the .txt filename extension to a


filename
that you supply:

PowerShell

function Get-Extension {

$name = $args[0] + ".txt"

$name

PowerShell
Get-Extension myTextFile

Output

myTextFile.txt

Switch Parameters
A switch is a parameter that doesn't 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:

PowerShell

function Switch-Item {

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 .

PowerShell

Switch-Item -on

Output

Switch on

PowerShell

Switch-Item

Output

Switch off

You can also assign a Boolean value to a switch when you run the function,
as shown in
the following example:

PowerShell

Switch-Item -on:$true

Output

Switch on

PowerShell

Switch-Item -on:$false

Output

Switch off

Using Splatting to Represent Command


Parameters
You can use splatting to represent the parameters of a command. This feature is
introduced in Windows PowerShell 3.0.

Use this technique in functions that call commands in the session. You don't
need to
declare or enumerate the command parameters, or change the function
when command
parameters change.

The following sample function calls the Get-Command cmdlet. The command uses
@Args
to represent the parameters of Get-Command .

PowerShell

function Get-MyCommand { Get-Command @Args }

You can use all the parameters of Get-Command when you call the
Get-MyCommand
function. The parameters and parameter values are passed to the
command using
@Args .

PowerShell
Get-MyCommand -Name Get-ChildItem

Output

CommandType Name ModuleName

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

Cmdlet Get-ChildItem Microsoft.PowerShell.Management

The @Args feature uses the $Args automatic parameter, which represents
undeclared
cmdlet parameters and values from remaining arguments.

For more information, see about_Splatting.

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 these keywords:

Syntax

function <name> {

begin {<statement list>}

process {<statement list>}

end {<statement list>}

) Important

If your function defines any one of these named statement lists, all your
code must
be inside one of those blocks. Any code outside the blocks isn't
recognized. If your
function doesn't use any of these blocks, all the
statements are treated like an 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.
The following function uses the process keyword. The function displays
values from the
pipeline:

PowerShell

function Get-Pipeline

process {"The value is: $_"}

1,2,4 | Get-Pipeline

Output

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.

PowerShell

function Get-PipelineBeginEnd

begin {"Begin: The input is $input"}

end {"End: The input is $input" }

If this function is run using the pipeline, it displays the following


results:

PowerShell

1,2,4 | Get-PipelineBeginEnd

Output

Begin: The input is

End: The input is 1 2 4

When the begin statement runs, the function doesn't have the input from the
pipeline.
The end statement runs after the function has the values.

If the function has a process keyword, each object in $input is removed


from $input
and assigned to $_ . The following example has a process
statement list:

PowerShell

function Get-PipelineInput

process {"Processing: $_ " }

end {"End: The input is: $input" }

In this example, each object that's 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.

PowerShell

1,2,4 | Get-PipelineInput

Output

Processing: 1

Processing: 2

Processing: 4

End: The input is:

For more information, see Using Enumerators

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:

PowerShell

filter Get-ErrorLog ([switch]$Message)

if ($Message) { Out-Host -InputObject $_.Message }

else { $_ }

It can be used as follows:

PowerShell

Get-WinEvent -LogName System -MaxEvents 100 | Get-ErrorLog -Message

Function Scope
A function exists in the scope in which it's 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 isn't available outside
of that script.

You can specify the scope of a function. For example, the function is added to
the global
scope in the following example:

PowerShell

function global:Get-DependentSvs {

Get-Service | Where-Object {$_.DependentServices}

When a function is in the global scope, you can use the function in scripts,
in functions,
and at the command line.

Functions create a new scope. The items created in a function, such as


variables, exist
only in the function scope.

For more information, see about_Scopes.

Finding and Managing Functions Using the


Function: Drive
All the functions and filters in PowerShell are automatically stored in the
Function:
drive. This drive is exposed by the 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
PowerShell:

PowerShell

Get-ChildItem 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 PowerShell, type:

PowerShell

(Get-ChildItem function:help).Definition

You can also use the following syntax.

PowerShell

$function:help

For more information about the Function: drive, see the help topic for the
Function
provider. Type Get-Help Function .

Reusing Functions in New Sessions


When you type a function at the PowerShell command prompt, the function becomes
part of the current session. The function is available until the session ends.

To use your function in all PowerShell sessions, add the function to your
PowerShell
profile. For more information about profiles, see
about_Profiles.

You can also save your function in a PowerShell script file. Type your function
in a text
file, and then save the file with the .ps1 filename 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 Get-MyDisks function, type:

PowerShell

Get-Help Get-MyDisks

You can write help for a function using either of the two following methods:

Comment-Based Help for Functions

Create a help topic 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's 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
comment-based help keyword. Without this keyword, Get-Help
can't find the
function help topic and calls to Get-Help for the function
return only
autogenerated help.

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.

See also
about_Automatic_Variables
about_Comment_Based_Help
about_Function_Provider
about_Functions_Advanced
about_Functions_Advanced_Methods
about_Functions_Advanced_Parameters
about_Functions_CmdletBindingAttribute
about_Functions_OutputTypeAttribute
about_Parameters
about_Profiles
about_Scopes
about_Script_Blocks
about_Functions_Advanced
Article • 01/23/2023 • 2 minutes to read

Short description
Introduces advanced functions that are a way to create cmdlets using scripts.

Long description
A cmdlet is a single command that participates in the pipeline semantics of
PowerShell.
This includes binary cmdlets, advanced script functions, CDXML, and
Workflows.

Advanced functions allow you create cmdlets that are written as a PowerShell
function.
Advanced functions make it easier to create cmdlets without having to
write and
compile a binary cmdlet. Binary cmdlets are .NET classes that are
written in a .NET
language such as C#.

Advanced functions use the CmdletBinding attribute to identify them as


functions that
act like cmdlets. The CmdletBinding attribute is similar to
the Cmdlet attribute that's
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 like the verb-noun pair of
a compiled cmdlet.
However, functions aren't required to have a verb-noun name.

PowerShell

function Send-Greeting

[CmdletBinding()]

Param(

[Parameter(Mandatory=$true)]

[string] $Name

Process

Write-Host ("Hello " + $Name + "!")

The parameters of the function are declared 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's used by compiled
cmdlets to process
the data that's 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 doesn't throw an exception when an array


of strings is bound to a Boolean parameter.
The ValidateSet attribute and the ValidatePattern attribute can't pass named
parameters.
Advanced functions can't be used in transactions.

See also
about_Functions
about_Functions_Advanced_Methods
about_Functions_Advanced_Parameters
about_Functions_CmdletBindingAttribute
about_Functions_OutputTypeAttribute
about_Functions_Advanced_Methods
Article • 01/23/2023 • 5 minutes to read

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

All the methods and properties of the PSCmdlet class are available to
advanced
functions. For more information, see
System.Management.Automation.PSCmdlet.

For more information about the CmdletBinding attribute, see


about_Functions_CmdletBindingAttribute. For the
CmdletBindingAttribute class, see
System.Management.Automation.Cmdlet.CmdletBindingAttribute.

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. You aren't required to use any of
these blocks in your functions.

7 Note

These blocks are also available to functions that don't use the
CmdletBinding
attribute.
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.

PowerShell

Function Test-ScriptCmdlet

[CmdletBinding(SupportsShouldProcess=$True)]

Param ($Parameter1)
begin{}

process{}

end{}

7 Note

Using either a begin or end block requires that you define all three
blocks. When
using any block, all PowerShell code must be inside one
of the blocks.

begin

This block is used to provide optional one-time preprocessing for the function.
The
PowerShell runtime uses the code in this block once for each instance of
the function in
the pipeline.

process

This block is used to provide record-by-record processing for the function. You
can use
a process block without defining the other blocks. The number of
process block
executions depends on how you use the function and what input
the function receives.

The automatic variable $_ or $PSItem contains the current object in the


pipeline for use
in the process block. The $input automatic variable
contains an enumerator that's only
available to functions and script blocks.
For more information, see
about_Automatic_Variables.

Calling the function at the beginning, or outside of a pipeline, executes the


process block once.

Within a pipeline, the process block executes once for each input object
that
reaches the function.
If the pipeline input that reaches the function is empty, the process block
does
not execute.
The begin and end blocks still execute.

) Important

If a function parameter is set to accept pipeline input, and a process


block isn't
defined, record-by-record processing will fail. In this case,
your function will only
execute once, regardless of the input.

end

This block is used to provide optional one-time post-processing for the


function.

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 only be
called only from
within the Process{} block of the function. The
CmdletBinding attribute must also
declare that the function supports
ShouldProcess (as shown in the previous example).

For more information about this method, see


System.Management.Automation.Cmdlet.ShouldProcess.

For more information about how to request confirmation, see


Requesting Confirmation.

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.

Error methods
Functions can call two different methods when errors occur. When a
non-terminating
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 can't

continue, it should call the


ThrowTerminatingError method. You can also use the Throw
statement for
terminating errors and the Write-Error cmdlet for non-terminating errors.

For more information, see


System.Management.Automation.Cmdlet.ThrowTerminatingError.

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.

WriteDebug
To provide information that can be used to troubleshoot a function, make the
function
call the WriteDebug method. The WriteDebug method displays debug
messages to the
user. For more information, see
System.Management.Automation.Cmdlet.WriteDebug.

WriteError
Functions should call this method when non-terminating errors occur and the
function
is designed to continue processing records. For more information, see
System.Management.Automation.Cmdlet.WriteError.

7 Note

If a terminating error occurs, the function should call the


ThrowTerminatingError
method.

WriteObject
The WriteObject method allows the function to send an object to the next
command in
the pipeline. In most cases, WriteObject is the method to use when
the function returns
data. For more information, see
System.Management.Automation.PSCmdlet.WriteObject.

WriteProgress
For functions with actions that 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.

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 aren't displayed. For more information, see
System.Management.Automation.PSCmdlet.WriteVerbose.

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.

7 Note

You can also display warning messages by configuring the $WarningPreference


variable or by using the Verbose and Debug command-line options. for more
information about the $WarningPreference variable, see
about_Preference_Variables.

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.

For example, the ParameterSetName property allows you to see the


parameter set that's
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_Automatic_Variables
about_Functions
about_Functions_Advanced
about_Functions_Advanced_Parameters
about_Functions_CmdletBindingAttribute
about_Functions_OutputTypeAttribute
about_Preference_Variables
about_Functions_Advanced_Parameters
Article • 05/15/2023

Short description
Explains how to add parameters to advanced functions.

Long description
You can add parameters to the advanced functions that you write, and use
parameter
attributes and arguments to limit the parameter values that function
users submit with
the parameter.

The parameters that you add to your function are available to users in addition
to the
common parameters that PowerShell adds automatically to all cmdlets and
advanced
functions. For more information about the PowerShell common
parameters, see
about_CommonParameters.

Beginning in PowerShell 3.0, you can use splatting with @Args to represent
the
parameters in a command. Splatting is valid on simple and advanced
functions. For
more information, see about_Functions and
about_Splatting.

Type conversion of parameter values


When you supply strings as arguments to parameters that expect a different
type,
PowerShell implicitly converts the strings to the parameter target type.
Advanced
functions perform culture-invariant parsing of parameter values.

By contrast, a culture-sensitive conversion is performed during parameter


binding for
compiled cmdlets.

In this example, we create a cmdlet and a script function that take a


[datetime]
parameter. The current culture is changed to use German settings.
A German-formatted
date is passed to the parameter.

PowerShell

# Create a cmdlet that accepts a [datetime] argument.

Add-Type @'

using System;

using System.Management.Automation;

[Cmdlet("Get", "Date_Cmdlet")]

public class GetFooCmdlet : Cmdlet {

[Parameter(Position=0)]

public DateTime Date { get; set; }

protected override void ProcessRecord() {

WriteObject(Date);

'@ -PassThru | % Assembly | Import-Module

[cultureinfo]::CurrentCulture = 'de-DE'

$dateStr = '19-06-2018'

Get-Date_Cmdlet $dateStr

Output

Dienstag, 19. Juni 2018 00:00:00

As shown above, cmdlets use culture-sensitive parsing to convert the string.

PowerShell

# Define an equivalent function.

function Get-Date_Func {

param(

[DateTime] $Date

process {

$Date

[cultureinfo]::CurrentCulture = 'de-DE'

# This German-format date string doesn't work with the invariant culture.

# E.g., [datetime] '19-06-2018' breaks.

$dateStr = '19-06-2018'

Get-Date_Func $dateStr

Advanced functions use culture-invariant parsing, which results in the


following error.

Output

Get-Date_Func : Cannot process argument transformation on parameter 'Date'.


Cannot convert

value "19-06-2018" to type "System.DateTime". Error: "String was not


recognized as a valid

DateTime."

At line:13 char:15

+ Get-Date_Func $dateStr

+ ~~~~~~~~

+ CategoryInfo : InvalidData: (:) [Get-Date_Func],


ParameterBindingArgumentTransformationException

+ FullyQualifiedErrorId : ParameterArgumentTransformationError,Get-
Date_Func

Static parameters
Static parameters are parameters that are always available in the function.
Most
parameters in PowerShell cmdlets and scripts are static parameters.

The following example shows the declaration of a ComputerName parameter


that has
the following characteristics:

It's mandatory (required).


It takes input from the pipeline.
It takes an array of strings as input.

PowerShell

Param(

[Parameter(Mandatory=$true,

ValueFromPipeline=$true)]

[string[]]

$ComputerName

Switch parameters
Switch parameters are parameters that take no parameter value. Instead, they
convey a
Boolean true-or-false value through their presence or absence, so that
when a switch
parameter is present it has a true value and when absent it
has a false value.

For example, the Recurse parameter of Get-ChildItem is a switch


parameter.

To create a switch parameter in a function, specify the switch type in the


parameter
definition.

For example, your function may have an option to output data as a byte array:

PowerShell
Param([switch]$AsByteArray)

Switch parameters are easy to use and are preferred over Boolean parameters,
which
have a less natural syntax for PowerShell.

For example, to use a switch parameter, the user types the parameter in the
command.

-IncludeAll

To use a Boolean parameter, the user types the parameter and a Boolean value.

-IncludeAll $true

When creating switch parameters, choose the parameter name carefully. Be sure
that
the parameter name communicates the effect of the parameter to the user.
Avoid
ambiguous terms, such as Filter or Maximum that might imply a
value is required.

Switch parameter design considerations


Switch parameters shouldn't be given default values. They should always
default to
false.

Switch parameters are excluded from positional parameters by default. Even


when
other parameters are implicitly positional, switch parameters aren't.
You can
override that in the Parameter attribute, but it will confuse
users.

Switch parameters should be designed so that setting them moves a command


from its default behavior to a less common or more complicated mode. The
simplest behavior of a command should be the default behavior that doesn't
require the use of switch parameters.

Switch parameters shouldn't be mandatory. The only case where it's necessary
to
make a switch parameter mandatory is when it's needed to differentiate a
parameter set.

Explicitly setting a switch from a boolean can be done with


-MySwitch:$boolValue
and in splatting with
$params = @{ MySwitch = $boolValue } .

Switch parameters are of type SwitchParameter , which implicitly converts to


Boolean. The parameter variable can be used directly in a conditional
expression.
For example:

if ($MySwitch) { ... }
There's no need to write if ($MySwitch.IsPresent) { ... }

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 drive, or in a particular path of the
provider drive. For
example, the Encoding parameter is available on the
Add-Content , Get-Content , and
Set-Content cmdlets only when it's used in
a file system drive.

You can also create a parameter that appears only when another parameter is
used in
the function command or when another parameter has a certain value.

Dynamic parameters can be useful, but use them only when necessary, because
they can
be difficult for users to discover. To find a dynamic parameter, the
user must be in the
provider path, use the ArgumentList parameter of the
Get-Command cmdlet, or use the
Path parameter of Get-Help .

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.

The following example shows a function with standard parameters named Name
and
Path, and an optional dynamic parameter named KeyCount. The
KeyCount parameter is
in the ByRegistryPath parameter set and has a type
of Int32 . The KeyCount parameter
is available in the Get-Sample
function only when the value of the Path parameter starts
with HKLM: ,
indicating that it's being used in the HKEY_LOCAL_MACHINE registry drive.

PowerShell

function Get-Sample {

[CmdletBinding()]

Param([string]$Name, [string]$Path)

DynamicParam

if ($Path.StartsWith("HKLM:"))

$parameterAttribute =
[System.Management.Automation.ParameterAttribute]@{

ParameterSetName = "ByRegistryPath"

Mandatory = $false

$attributeCollection =
[System.Collections.ObjectModel.Collection[System.Attribute]]::new()

$attributeCollection.Add($parameterAttribute)

$dynParam1 =
[System.Management.Automation.RuntimeDefinedParameter]::new(

'KeyCount', [Int32], $attributeCollection

$paramDictionary =
[System.Management.Automation.RuntimeDefinedParameterDictionary]::new()

$paramDictionary.Add('KeyCount', $dynParam1)

return $paramDictionary

For more information, see the documentation for the


RuntimeDefinedParameter
type.

Attributes of parameters
This section describes the attributes that you can add to function parameters.

All attributes are optional. However, if you omit the CmdletBinding


attribute, then to be
recognized as an advanced function, the function must
include the Parameter attribute.

You can add one or multiple attributes in each parameter declaration. There's
no limit to
the number of attributes that you can add to a parameter
declaration.

Parameter attribute
The Parameter attribute is used to declare the attributes of function
parameters.

The Parameter attribute is optional, and you can omit it if none of the
parameters of
your functions need attributes. But, to be recognized as an
advanced function, rather
than a simple function, a function must have either
the CmdletBinding attribute or the
Parameter attribute, or both.

The Parameter attribute has arguments that define the characteristics of


the parameter,
such as whether the parameter is mandatory or optional.
Use the following syntax to declare the Parameter attribute, an argument,
and an
argument value. The parentheses that enclose the argument and its value
must follow
Parameter with no intervening space.

PowerShell

Param(

[Parameter(Argument=value)]

$ParameterName

Use commas to separate arguments within the parentheses. Use the following
syntax to
declare two arguments of the Parameter attribute.

PowerShell

Param(

[Parameter(Argument1=value1,

Argument2=value2)]

$ParameterName

The boolean argument types of the Parameter attribute default to False


when omitted
from the Parameter attribute. Set the argument value to
$true or just list the argument
by name. For example, the following
Parameter attributes are equivalent.

PowerShell

Param(

[Parameter(Mandatory=$true)]

# Boolean arguments can be defined using this shorthand syntax

Param(

[Parameter(Mandatory)]

If you use the Parameter attribute without arguments, as an alternative to


using the
CmdletBinding attribute, the parentheses that follow the
attribute name are still
required.

PowerShell

Param(

[Parameter()]

$ParameterName

Mandatory argument
The Mandatory argument indicates that the parameter is required. If this
argument isn't
specified, the parameter is optional.

The following example declares the ComputerName parameter. It uses the


Mandatory
argument to make the parameter mandatory.

PowerShell

Param(

[Parameter(Mandatory)]

[string[]]

$ComputerName

Position argument
The Position argument determines whether the parameter name is required when
the
parameter is used in a command. When a parameter declaration includes the
Position
argument, the parameter name can be omitted and PowerShell
identifies the unnamed
parameter value by its position, or order, in the list
of unnamed parameter values in the
command.

If the Position argument isn't specified, the parameter name, or a parameter


name alias
or abbreviation, must precede the parameter value whenever the
parameter is used in a
command.

By default, all function parameters are positional. PowerShell assigns position


numbers
to parameters in the order the parameters are declared in the function.
To disable this
feature, set the value of the PositionalBinding argument of
the CmdletBinding
attribute to $False . The Position argument takes
precedence over the value of the
PositionalBinding argument of the
CmdletBinding attribute. For more information, see

PositionalBinding in
about_Functions_CmdletBindingAttribute.

The value of the Position argument is specified as an integer. A position


value of 0
represents the first position in the command, a position value
of 1 represents the second
position in the command, and so on.
If a function has no positional parameters, PowerShell assigns positions to
each
parameter based on the order the parameters are declared. However, as a
best practice,
don't rely on this assignment. When you want parameters to be
positional, use the
Position argument.

The following example declares the ComputerName parameter. It uses the


Position
argument with a value of 0. As a result, when -ComputerName is
omitted from command,
its value must be the first or only unnamed parameter
value in the command.

PowerShell

Param(

[Parameter(Position=0)]

[string[]]

$ComputerName

ParameterSetName argument

The ParameterSetName argument specifies the parameter set a parameter belongs


to. If
no parameter set is specified, the parameter belongs to all the
parameter sets defined
by the function. To be unique, each parameter set must
have at least one parameter that
isn't a member of any other parameter set.

7 Note

For a cmdlet or function, there is a limit of 32 parameter sets.

The following example declares a ComputerName parameter in the Computer


parameter
set, a UserName parameter in the User parameter set, and a
Summary parameter in
both parameter sets.

PowerShell

Param(

[Parameter(Mandatory,

ParameterSetName="Computer")]
[string[]]

$ComputerName,

[Parameter(Mandatory,

ParameterSetName="User")]

[string[]]

$UserName,

[Parameter()]

[switch]

$Summary

You can specify only one ParameterSetName value in each argument and only one
ParameterSetName argument in each Parameter attribute. To include a
parameter in
more than one parameter set, add additional Parameter
attributes.

The following example explicitly adds the Summary parameter to the


Computer and
User parameter sets. The Summary parameter is optional in
the Computer parameter set

and mandatory in the User parameter set.

PowerShell

Param(

[Parameter(Mandatory,

ParameterSetName="Computer")]
[string[]]

$ComputerName,

[Parameter(Mandatory,

ParameterSetName="User")]

[string[]]

$UserName,

[Parameter(ParameterSetName="Computer")]

[Parameter(Mandatory, ParameterSetName="User")]

[switch]

$Summary

For more information about parameter sets, see


About Parameter Sets.

ValueFromPipeline argument
The ValueFromPipeline argument indicates that the parameter accepts input
from a
pipeline object. Specify this argument if the function accepts the
entire object, not just a
property of the object.

The following example declares a ComputerName parameter that's mandatory


and
accepts an object that's passed to the function from the pipeline.

PowerShell
Param(

[Parameter(Mandatory,

ValueFromPipeline)]

[string[]]

$ComputerName

ValueFromPipelineByPropertyName argument
The ValueFromPipelineByPropertyName argument indicates that the parameter
accepts
input from a property of a pipeline object. The object property must
have the same
name or 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 function's ComputerName parameter.

The following example declares a ComputerName parameter that's mandatory


and
accepts input from the object's ComputerName property that's passed to
the function
through the pipeline.

PowerShell

Param(

[Parameter(Mandatory,

ValueFromPipelineByPropertyName)]

[string[]]

$ComputerName

Consider an implementation of a function using this argument:

PowerShell

function Test-ValueFromPipelineByPropertyName{

param(

[Parameter(Mandatory, ValueFromPipelineByPropertyName)]

[string[]]

$ComputerName

Write-Output -InputObject "Saw that ComputerName was '$ComputerName'"

Then a demonstration of piping an object with the ComputerName property


would be:
PowerShell

[pscustomobject]@{ ComputerName = "HelloWorld" } |

Test-ValueFromPipelineByPropertyName

Output

Saw that ComputerName was 'HelloWorld'

7 Note

A typed parameter that accepts pipeline input ( by Value ) or


( by PropertyName )
enables use of delay-bind script blocks on the
parameter.

The delay-bind script block is run automatically during


ParameterBinding. The
result is bound to the parameter. Delay binding
doesn't work for parameters
defined as type ScriptBlock or
System.Object. The script block is passed through
without being
invoked.

You can read about delay-bind script blocks here


about_Script_Blocks.md.

ValueFromRemainingArguments argument

The ValueFromRemainingArguments argument indicates that the parameter accepts


all the
parameter's values in the command that aren't assigned to other
parameters of the
function.

There's a known issue for using collections with


ValueFromRemainingArguments where
the passed-in collection is treated as a
single element.

The following example demonstrates this known issue. The Remaining


parameter
should contain one at index 0 and two at index 1.
Instead, both elements are combined
into a single entity.

PowerShell

function Test-Remainder

param(

[string]

[Parameter(Mandatory, Position=0)]

$Value,

[string[]]

[Parameter(Position=1, ValueFromRemainingArguments)]

$Remaining)

"Found $($Remaining.Count) elements"

for ($i = 0; $i -lt $Remaining.Count; $i++)

"${i}: $($Remaining[$i])"

Test-Remainder first one,two

Output

Found 1 elements

0: one two

7 Note

This issue is resolved in PowerShell 6.2.

HelpMessage argument
The HelpMessage argument specifies a string that contains a brief description
of the
parameter or its value. If you run the command without the mandatory
parameter,
PowerShell prompts you for input. To see the help message, type !?
at the prompt and
hit Enter .

The following example declares a mandatory ComputerName parameter and a


help
message that explains the expected parameter value.

PowerShell

Param(

[Parameter(Mandatory,

HelpMessage="Enter one or more computer names separated by commas.")]

[string[]]

$ComputerName

Example output:

Output

cmdlet at command pipeline position 1

Supply values for the following parameters:

(Type !? for Help.)

ComputerName[0]: !?

Enter one or more computer names separated by commas.

ComputerName[0]: localhost

ComputerName[1]:

If there is no comment-based help for the


function then this message is displayed in the
Get-Help -Full output.

This argument has no effect on optional parameters.

Alias attribute
The Alias attribute establishes an alternate name for the parameter.
There's no limit to
the number of aliases that you can assign to a parameter.

The following example shows a parameter declaration that adds the CN and
MachineName aliases to the mandatory ComputerName parameter.

PowerShell

Param(

[Parameter(Mandatory)]

[Alias("CN","MachineName")]

[string[]]

$ComputerName

SupportsWildcards attribute
The SupportsWildcards attribute is used to indicate that the parameter
accepts wildcard
values. The following example shows a parameter declaration
for a mandatory Path
parameter that supports wildcard values.

PowerShell

Param(

[Parameter(Mandatory)]

[SupportsWildcards()]

[string[]]

$Path

Using this attribute doesn't automatically enable wildcard support. The cmdlet
developer must implement the code to handle the wildcard input. The wildcards
supported can vary according to the underlying API or PowerShell provider. For
more
information, see about_Wildcards.

ArgumentCompleter attribute
The ArgumentCompleter attribute allows you to add tab completion values to
a specific
parameter. An ArgumentCompleter attribute must be defined for
each parameter that
needs tab completion. Like DynamicParameters, the
available values are calculated at
runtime when the user presses Tab
after the parameter name.

For more information, see


about_Functions_Argument_Completion.

Parameter and variable validation attributes


Validation attributes direct PowerShell to test the parameter values that users
submit
when they call the advanced function. If the parameter values fail the
test, an error is
generated and the function isn't called. Parameter validation
is only applied to the input
provided and any other values like default values
aren't validated.

You can also use the validation attributes to restrict the values that users
can specify for
variables.

PowerShell

[AllowNull()][int]$number = 7

Validation attributes can be applied to any variable, not just parameters. You
can define
validation for any variable within a script.

7 Note

When using any attributes with a typed variable, it's best practice to
declare the
attribute before the type.

If you declare a type with a line break before the attribute and variable
name, the
type is treated as its own statement.

PowerShell

[string]

[ValidateLength(1,5)] $Text = 'Okay'

Output

IsPublic IsSerial Name BaseType

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

True True String


System.Object

If you declare a validation attribute after a type, the value being assigned
is
validated before type conversion, which can lead to unexpected validation
failures.

PowerShell

[string][ValidateLength(1,5)]$TicketIDFromInt = 43

[string][ValidateLength(1,5)]$TicketIDFromString = '43'

[ValidateLength(1,5)][string]$TicketIDAttributeFirst = 43

Output

The attribute cannot be added because variable TicketIDFromInt with

value 43 would no longer be valid.

At line:1 char:1

+ [string][ValidateLength(1,5)]$TicketIDFromInt = 43

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : MetadataError: (:) [], ValidationMetadata

Exception

+ FullyQualifiedErrorId : ValidateSetFailure

AllowNull validation attribute


The AllowNull attribute allows the value of a mandatory parameter to be
$null . The
following example declares a hashtable ComputerInfo parameter
that can have a null
value.

PowerShell

Param(

[Parameter(Mandatory)]

[AllowNull()]

[hashtable]

$ComputerInfo

7 Note
The AllowNull attribute doesn't work if the type converter is set to
string as the
string type won't accept a null value. You can use the
AllowEmptyString attribute
for this scenario.

AllowEmptyString validation attribute


The AllowEmptyString attribute allows the value of a mandatory parameter to
be an
empty string ( "" ). The following example declares a ComputerName
parameter that
can have an empty string value.

PowerShell

Param(

[Parameter(Mandatory)]

[AllowEmptyString()]

[string]

$ComputerName

AllowEmptyCollection validation attribute


The AllowEmptyCollection attribute allows the value of a mandatory
parameter to be an
empty collection @() . The following example declares a
ComputerName parameter that
can have an empty collection value.

PowerShell

Param(

[Parameter(Mandatory)]

[AllowEmptyCollection()]

[string[]]

$ComputerName

ValidateCount validation attribute


The ValidateCount attribute specifies the minimum and maximum number of
parameter
values that a parameter accepts. PowerShell generates an error if the
number of
parameter values in the command that calls the function is outside
that range.

The following parameter declaration creates a ComputerName parameter that


takes
one to five parameter values.
PowerShell

Param(

[Parameter(Mandatory)]

[ValidateCount(1,5)]

[string[]]

$ComputerName

ValidateLength validation attribute


The ValidateLength attribute specifies the minimum and maximum number of
characters in a parameter or variable value. PowerShell generates an error if
the length
of a value specified for a parameter or a variable is outside of the
range.

In the following example, each computer name must have one to ten characters.

PowerShell

Param(

[Parameter(Mandatory)]

[ValidateLength(1,10)]

[string[]]

$ComputerName

In the following example, the value of the variable $text must be a minimum
of one
character in length, and a maximum of ten characters.

PowerShell

[ValidateLength(1,10)][string] $text = 'valid'

ValidatePattern validation attribute


The ValidatePattern attribute specifies a regular expression that's
compared to the
parameter or variable value. PowerShell generates an error if
the value doesn't match
the regular expression pattern.

In the following example, the parameter value must contain a four-digit number,
and
each digit must be a number zero to nine.

PowerShell
Param(

[Parameter(Mandatory)]

[ValidatePattern("[0-9][0-9][0-9][0-9]")]

[string[]]

$ComputerName

In the following example, the value of the variable $ticketID must be exactly
a four-
digit number, and each digit must be a number zero to nine.

PowerShell

[ValidatePattern("^[0-9][0-9][0-9][0-9]$")][string]$ticketID = 1111

ValidateRange validation attribute


The ValidateRange attribute specifies a numeric range for each parameter or
variable
value. PowerShell generates an error if any value is outside that
range.

In the following example, the value of the Attempts parameter must be


between zero
and ten.

PowerShell

Param(

[Parameter(Mandatory)]

[ValidateRange(0,10)]

[Int]

$Attempts

In the following example, the value of the variable $number must be between
zero and
ten.

PowerShell

[ValidateRange(0,10)][int]$number = 5

ValidateScript validation attribute


The ValidateScript attribute specifies a script that's used to validate a
parameter or
variable value. PowerShell pipes the value to the script, and
generates an error if the
script returns $false or if the script throws an
exception.
When you use the ValidateScript attribute, the value that's being validated
is mapped to
the $_ variable. You can use the $_ variable to refer to the
value in the script.

In the following example, the value of the EventDate parameter must be


greater than or
equal to the current date.

PowerShell

Param(

[Parameter(Mandatory)]

[ValidateScript({$_ -ge (Get-Date)})]

[DateTime]

$EventDate

In the following example, the value of the variable $date must be less than
or equal to
the current date and time.

PowerShell

[ValidateScript({$_ -le (Get-Date)})][DateTime]$date = (Get-Date)

7 Note

If you use ValidateScript, you can't pass a $null value to the


parameter. When you
pass a null value ValidateScript can't validate the
argument.

ValidateSet attribute
The ValidateSet attribute specifies a set of valid values for a parameter
or variable and
enables tab completion. PowerShell generates an error if a
parameter or variable value
doesn't match a value in the set. In the following
example, the value of the Detail
parameter can only be Low, Average, or
High.

PowerShell

Param(

[Parameter(Mandatory)]

[ValidateSet("Low", "Average", "High")]

[string[]]

$Detail

In the following example, the value of the variable $flavor must be either
Chocolate,
Strawberry, or Vanilla.

PowerShell

[ValidateSet("Chocolate", "Strawberry", "Vanilla")]

[string]$flavor = "Strawberry"

The validation occurs whenever that variable is assigned even within the
script. For
example, the following results in an error at runtime:

PowerShell

Param(

[ValidateSet("hello", "world")]

[string]$Message

$Message = "bye"

This example returns the following error at runtime:

Output

The attribute cannot be added because variable Message with value bye would
no

longer be valid.

At line:1 char:1

+ [ValidateSet("hello", "world")][string]$Message = 'bye'

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : MetadataError: (:) [],


ValidationMetadataException

+ FullyQualifiedErrorId : ValidateSetFailure

Using ValidateSet also enable tab expansion of values for that parameter. For
more
information, see about_Tab_Expansion.

Dynamic ValidateSet values using classes


You can use a Class to dynamically generate the values for ValidateSet
at runtime. In the
following example, the valid values for the variable
$Sound are generated via a Class
named SoundNames that checks three
filesystem paths for available sound files:

PowerShell
Class SoundNames : System.Management.Automation.IValidateSetValuesGenerator
{

[string[]] GetValidValues() {
$SoundPaths = '/System/Library/Sounds/',

'/Library/Sounds','~/Library/Sounds'

$SoundNames = ForEach ($SoundPath in $SoundPaths) {

If (Test-Path $SoundPath) {

(Get-ChildItem $SoundPath).BaseName

return [string[]] $SoundNames

The [SoundNames] class is then implemented as a dynamic ValidateSet value


as follows:

PowerShell

Param(

[ValidateSet([SoundNames])]

[string]$Sound

7 Note

The IValidateSetValuesGenerator class was introduced in PowerShell 6.0

ValidateNotNull validation attribute


The ValidateNotNull attribute specifies that the parameter value can't be
$null . When
the value is $null , PowerShell raises an exception.

The ValidateNotNull attribute is designed to be used when the parameter is


optional
and the type is undefined or has a type converter that can't
implicitly convert a null
value like object. If you specify a type that
that implicitly converts a null value, such as a
string, the null value is
converted to an empty string even when using the
ValidateNotNull attribute.
For this scenario use the ValidateNotNullOrEmpty attribute.

In the following example, the value of the ID parameter can't be $null .

PowerShell

Param(

[Parameter()]

[ValidateNotNull()]

$ID

ValidateNotNullOrEmpty validation attribute


The ValidateNotNullOrEmpty attribute specifies that the assigned value
can't be any of
the following values:

$null

an empty string ( "" )


an empty array ( @() )

When the value is invalid, PowerShell raises an exception.

PowerShell

Param(

[Parameter(Mandatory)]

[ValidateNotNullOrEmpty()]

[string[]]

$UserName

ValidateDrive validation attribute


The ValidateDrive attribute specifies that the parameter value must
represent the path,
that's referring to allowed drives only. PowerShell
generates an error if the parameter
value refers to drives other than the
allowed. Existence of the path, except for the drive
itself, isn't verified.

If you use relative path, the current drive must be in the allowed drive list.

PowerShell

Param(

[ValidateDrive("C", "D", "Variable", "Function")]

[string]$Path

ValidateUserDrive validation attribute


The ValidateUserDrive attribute specifies that the parameter value must
represent in the
User drive. PowerShell generates an error if the path refers
to a different drive. The
validation attribute only tests for the existence of
the drive prefix of the path.

If you use relative path, the current drive must be User .

PowerShell

function Test-UserDrivePath{

[OutputType([bool])]

Param(

[Parameter(Mandatory, Position=0)][ValidateUserDrive()][string]$Path

$True

Test-UserDrivePath -Path C:\

Output

Test-UserDrivePath: Cannot validate argument on parameter 'Path'. The path

argument drive C does not belong to the set of approved drives: User.

Supply a path argument with an approved drive.

PowerShell

Test-UserDrivePath -Path 'User:\A_folder_that_does_not_exist'

Output

Test-UserDrivePath: Cannot validate argument on parameter 'Path'. Cannot

find drive. A drive with the name 'User' does not exist.

You can define User drive in Just Enough Administration (JEA) session
configurations.
For this example, we create the User: drive.

PowerShell

New-PSDrive -Name 'User' -PSProvider FileSystem -Root $env:HOMEPATH

Output

Name Used (GB) Free (GB) Provider Root

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

User 75.76 24.24 FileSystem C:\Users\ExampleUser

PowerShell
Test-UserDrivePath -Path 'User:\A_folder_that_does_not_exist'

Output

True

See also
about_Automatic_Variables
about_Functions
about_Functions_Advanced
about_Functions_Advanced_Methods
about_Functions_CmdletBindingAttribute
about_Functions_OutputTypeAttribute
about_Functions_Argument_Completion
Article • 09/19/2022 • 4 minutes to read

Short description
Argument completion is a feature of PowerShell that provide hints, enables
discovery,
and speeds up input entry of argument values.

Long description
This article describes the different ways you can implement argument completers
for
PowerShell functions. Argument completers provide the possible values for a
parameter.
The available values are calculated at runtime when the user presses
the Tab key after
the parameter name. There are several ways to
define an argument completer for a
parameter.

7 Note

Tab is the default key binding on Windows. This keybinding can be


changed by the
PSReadLine module or the application that is hosting
PowerShell. The keybinding is
different on non-Windows platforms. For more
information, see
about_PSReadLine.

ValidateSet attribute
The ValidateSet attribute specifies a set of valid values for a parameter
or variable and
enables tab completion. PowerShell generates an error if a
parameter or variable value
doesn't match a value in the set. In the following
example, the value of the Fruit
parameter can only be Apple,
Banana, or Pear.

PowerShell

Param(

[Parameter(Mandatory=$true)]

[ValidateSet('Apple', 'Banana', 'Pear')]

[string[]]

$Fruit

In the following example, the value of the variable $flavor must be either
Chocolate,
Strawberry, or Vanilla. The ValidateSet attribute can
be used on any variable, not just
parameters.

PowerShell

[ValidateSet('Chocolate', 'Strawberry', 'Vanilla')]

[string]$flavor = 'Strawberry'

The validation occurs whenever that variable is assigned even within the
script.

PowerShell

Param(

[ValidateSet('hello', 'world')]

[string]$Message

$Message = 'bye'

This example returns the following error at runtime:

MetadataError: The attribute cannot be added because variable Message with

value bye would no longer be valid.

For more information about tab expansion, see


about_Tab_Expansion.

Dynamic ValidateSet values using classes


You can use a Class to dynamically generate the values for ValidateSet
at runtime. In the
following example, the valid values for the variable
$Sound are generated via a Class
named SoundNames that checks three
filesystem paths for available sound files:

PowerShell

Class SoundNames : System.Management.Automation.IValidateSetValuesGenerator


{

[string[]] GetValidValues() {
$SoundPaths = '/System/Library/Sounds/',

'/Library/Sounds',

'~/Library/Sounds'

$SoundNames = ForEach ($SoundPath in $SoundPaths) {

If (Test-Path $SoundPath) {

(Get-ChildItem $SoundPath).BaseName

return [string[]] $SoundNames

The [SoundNames] class is then implemented as a dynamic ValidateSet value


as follows:

PowerShell

Param(

[ValidateSet([SoundNames])]

[string]$Sound

7 Note

The IValidateSetValuesGenerator class was introduced in PowerShell 6.0.

ArgumentCompleter attribute
The ArgumentCompleter attribute allows you to add tab completion values to
a specific
parameter. An ArgumentCompleter attribute must be defined for
each parameter that
needs tab completion.

To add an ArgumentCompleter attribute, you need to define a script block


that
determines the values. The script block must take the following
parameters in the order
specified below. The parameter's names don't matter as
the values are provided
positionally.

The syntax is as follows:

PowerShell

function MyArgumentCompleter {

Param(

[Parameter(Mandatory)]

[ArgumentCompleter( {

param ( $commandName,

$parameterName,

$wordToComplete,

$commandAst,

$fakeBoundParameters )

# Perform calculation of tab completed values here.

} )]

$ParamName

ArgumentCompleter script block


The script block parameters are set to the following values:

$commandName (Position 0) - This parameter is set to the name of the


command for

which the script block is providing tab completion.


$parameterName (Position 1) - This parameter is set to the parameter whose
value
requires tab completion.
$wordToComplete (Position 2) - This parameter is set to value the user has
provided
before they pressed Tab . Your script block should use
this value to determine tab
completion values.
$commandAst (Position 3) - This parameter is set to the Abstract Syntax
Tree (AST)
for the current input line. For more information, see the
AST type
documentation.
$fakeBoundParameters (Position 4) - This parameter is set to a hashtable
containing
the $PSBoundParameters for the cmdlet, before the user pressed
Tab . For more
information, see
about_Automatic_Variables.

The ArgumentCompleter script block must unroll the values using the
pipeline, such as
ForEach-Object , Where-Object , or another suitable method.
Returning an array of values

causes PowerShell to treat the entire array as


one tab completion value.

The following example adds tab completion to the Value parameter. If only
the Value
parameter is specified, all possible values, or arguments, for
Value are displayed. When
the Type parameter is specified, the
Value parameter only displays the possible values
for that type.

In addition, the -like operator ensures that if the user types the following
command
and uses Tab completion, only Apple is returned.

Test-ArgumentCompleter -Type Fruits -Value A

PowerShell

function MyArgumentCompleter{

param ( $commandName,

$parameterName,

$wordToComplete,

$commandAst,

$fakeBoundParameters )

$possibleValues = @{

Fruits = @('Apple', 'Orange', 'Banana')

Vegetables = @('Tomato', 'Squash', 'Corn')

if ($fakeBoundParameters.ContainsKey('Type')) {

$possibleValues[$fakeBoundParameters.Type] | Where-Object {

$_ -like "$wordToComplete*"

} else {

$possibleValues.Values | ForEach-Object {$_}

function Test-ArgumentCompleter {

[CmdletBinding()]

param (

[Parameter(Mandatory=$true)]

[ValidateSet('Fruits', 'Vegetables')]

$Type,

[Parameter(Mandatory=$true)]

[ArgumentCompleter({ MyArgumentCompleter @args })]

$Value

Register-ArgumentCompleter
The Register-ArgumentCompleter cmdlet registers a custom argument completer.
An
argument completer allows you to provide dynamic tab completion, at run time
for any
command that you specify.

For more information, see


Register-ArgumentCompleter.

See also
about_Functions_Advanced_Parameters
about_Tab_Expansion
Register-ArgumentCompleter
about_Functions_CmdletBindingAttribut
e
Article • 09/19/2022 • 4 minutes to read

Short description
Describes the attribute that makes a function work like a compiled cmdlet.

Long description
The CmdletBinding attribute is an attribute of functions that makes them
operate like
compiled cmdlets written in C#. It provides access to the features
of cmdlets.

PowerShell binds the parameters of functions that have the CmdletBinding


attribute in
the same way that it binds the parameters of compiled cmdlets. The
$PSCmdlet
automatic variable is available to functions with the
CmdletBinding attribute, but the
$Args variable is not available.

In functions that have the CmdletBinding attribute, unknown parameters and


positional
arguments that have no matching positional parameters cause
parameter binding to
fail.

7 Note

Compiled cmdlets use the required Cmdlet attribute, which is similar


to the
CmdletBinding attribute that is described in this topic.

Syntax
The following example shows the format of a function that specifies all the
optional
arguments of the CmdletBinding attribute. A brief description of
each argument follows
this example.

PowerShell

[CmdletBinding(ConfirmImpact=<String>,

DefaultParameterSetName=<String>,

HelpURI=<URI>,

SupportsPaging=<Boolean>,

SupportsShouldProcess=<Boolean>,

PositionalBinding=<Boolean>)]

Param ($Parameter1)
Begin{}

Process{}

End{}

The boolean argument types of the CmdletBinding attribute default to


False when
omitted from the CmdletBinding attribute. Set the argument
value to $true or just list
the argument by name. For example, the following
CmdletBinding attributes are
equivalent.

PowerShell

[CmdletBinding(SupportsPaging=$true)]

Param ($Parameter1)
Begin{}

Process{}

End{}

# Boolean arguments can be defined using this shorthand syntax

[CmdletBinding(SupportsPaging)]

Param ($Parameter1)
Begin{}

Process{}

End{}

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.
For more information about confirmation requests, see
Requesting Confirmation.

DefaultParameterSetName
The DefaultParameterSetName argument specifies the name of the parameter
set that
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.

HelpURI
The HelpURI argument specifies the internet address of the online version
of the help
topic that describes the function. The value of the HelpURI
argument must begin with
"http" or "https".

The HelpURI argument value is used for the value of the HelpURI
property of the
CommandInfo object that Get-Command returns for the
function.

However, when help files are installed on the computer and the value of the
first link in
the RelatedLinks section of the help file is a URI, or the
value of the first .Link directive
in comment-based help is a URI, the URI in
the help file is used as the value of the
HelpUri property of the function.

The Get-Help cmdlet uses the value of the HelpURI property to locate the
online
version of the function help topic when the Online parameter of
Get-Help is specified in
a command.

SupportsPaging
The SupportsPaging argument adds the First, Skip, and
IncludeTotalCount parameters
to the function. These parameters allow users
to select output from a very large result
set. This argument is designed for
cmdlets and functions that return data from large
data stores that support data
selection, such as an SQL database.

This argument was introduced in Windows PowerShell 3.0.

First: Gets only the first 'n' objects.


Skip: Ignores the first 'n' objects and then gets the remaining objects.
IncludeTotalCount: Reports the number of objects in the data set (an
integer)
followed by the objects. If the cmdlet cannot determine the total
count, it returns
"Unknown total count".
PowerShell includes NewTotalCount, a helper method that gets the total
count value to
return and includes an estimate of the accuracy of the total
count value.

The following sample function shows how to add support for the paging
parameters to
an advanced function.

PowerShell

function Get-Numbers {

[CmdletBinding(SupportsPaging)]

param()

$FirstNumber = [Math]::Min($PSCmdlet.PagingParameters.Skip, 100)

$LastNumber = [Math]::Min($PSCmdlet.PagingParameters.First +

$FirstNumber - 1, 100)

if ($PSCmdlet.PagingParameters.IncludeTotalCount) {

$TotalCountAccuracy = 1.0

$TotalCount = $PSCmdlet.PagingParameters.NewTotalCount(100,

$TotalCountAccuracy)

Write-Output $TotalCount

$FirstNumber .. $LastNumber | Write-Output

SupportsShouldProcess
The SupportsShouldProcess argument adds Confirm and WhatIf
parameters to the
function. The Confirm parameter prompts the user before
it runs the command on each
object in the pipeline. The WhatIf parameter
lists the changes that the command would
make, instead of running the command.

PositionalBinding
The PositionalBinding argument determines whether parameters in the
function are
positional by default. The default value is $True . You can use
the PositionalBinding
argument with a value of $False to disable
positional binding.

The PositionalBinding argument is introduced in Windows PowerShell 3.0.

When parameters are positional, the parameter name is optional.


PowerShell associates
unnamed parameter values with the function parameters
according to the order or
position of the unnamed parameter values in the
function command.
When parameters are not positional (they are "named"), the parameter
name (or an
abbreviation or alias of the name) is required in the command.

When PositionalBinding is $True , function parameters are positional by


default.
PowerShell assigns position number to the parameters in the order in
which they are
declared in the function.

When PositionalBinding is $False , function parameters are not positional


by default.
Unless the Position argument of the Parameter attribute is
declared on the parameter,
the parameter name (or an alias or abbreviation)
must be included when the parameter
is used in a function.

The Position argument of the Parameter attribute takes precedence over


the
PositionalBinding default value. You can use the Position argument
to specify a position
value for a parameter. For more information about the
Position argument, see
about_Functions_Advanced_Parameters.

Notes
The SupportsTransactions argument is not supported in advanced functions.

Keywords
about_Functions_CmdletBinding_Attribute

See also
about_Functions
about_Functions_Advanced
about_Functions_Advanced_Methods
about_Functions_Advanced_Parameters
about_Functions_OutputTypeAttribute
about_Functions_OutputTypeAttribute
Article • 04/17/2023

Short description
Describes an attribute that reports the type of object that the function
returns.

Long description
The OutputType attribute lists the .NET types of objects that the functions
returns. You
can use its optional ParameterSetName parameter to list different
output types for each
parameter set.

The OutputType attribute is supported on simple and advanced functions.


It's
independent of the CmdletBinding attribute.

The OutputType attribute provides the value of the OutputType property


of the
System.Management.Automation.FunctionInfo object that the
Get-Command cmdlet
returns.

The OutputType attribute value is only a documentation note. It's not


derived from the
function code or compared to the actual function output. As
such, the value might be
inaccurate.

Syntax
The OutputType attribute of functions has the following syntax:

[OutputType([<TypeLiteral>], ParameterSetName="<Name>")]

[OutputType("<TypeNameString>", ParameterSetName="<Name>")]

The ParameterSetName parameter is optional.

You can list multiple types in the OutputType attribute.

[OutputType([<Type1>],[<Type2>],[<Type3>])]

You can use the ParameterSetName parameter to indicate that different


parameter sets
return different types.

[OutputType([<Type1>], ParameterSetName=("<Set1>","<Set2>"))]

[OutputType([<Type2>], ParameterSetName="<Set3>")]

Place the OutputType attribute statements in the attributes list that


precedes the Param
statement.

The following example shows the placement of the OutputType attribute in a


simple
function.

PowerShell

function SimpleFunction2

[OutputType([<Type>])]

Param ($Parameter1)

<function body>

The following example shows the placement of the OutputType attribute in


advanced
functions.

PowerShell

function AdvancedFunction1

[OutputType([<Type>])]

Param (

[parameter(Mandatory=$true)]

[String[]]

$Parameter1

<function body>

function AdvancedFunction2

[CmdletBinding(SupportsShouldProcess=<Boolean>)]

[OutputType([<Type>])]

Param (

[parameter(Mandatory=$true)]

[String[]]

$Parameter1

<function body>

Examples

Example 1: Create a function that has the OutputType of


String
PowerShell

function Send-Greeting

[OutputType([String])]

Param ($Name)

"Hello, $Name"

To see the resulting output type property, use the Get-Command cmdlet.

PowerShell

(Get-Command Send-Greeting).OutputType

Output

Name Type

---- ----

System.String System.String

Example 2: Use the OutputType attribute to indicate


dynamic output types
The following advanced function uses the OutputType attribute to indicate
that the
function returns different types depending on the parameter set used
in the function
command.

PowerShell

function Get-User

[CmdletBinding(DefaultParameterSetName="ID")]

[OutputType("System.Int32", ParameterSetName="ID")]

[OutputType([String], ParameterSetName="Name")]

Param (

[parameter(Mandatory=$true, ParameterSetName="ID")]

[Int[]]

$UserID,

[parameter(Mandatory=$true, ParameterSetName="Name")]

[String[]]

$UserName

<function body>

Example 3: Shows when an actual output differs from the


OutputType
The following example demonstrates that the output type property value
displays the
value of the OutputType attribute, even when it's inaccurate.

The Get-Time function returns a string that contains the short form of the
time in any
DateTime object. However, the OutputType attribute reports
that it returns a
System.DateTime object.

PowerShell

function Get-Time

[OutputType([DateTime])]

Param (

[parameter(Mandatory=$true)]

[Datetime]$DateTime

$DateTime.ToShortTimeString()

The GetType() method confirms that the function returns a string.

PowerShell

(Get-Time -DateTime (Get-Date)).GetType().FullName

Output

System.String

However, the OutputType property, which gets its value from the
OutputType attribute,
reports that the function returns a DateTime
object.

PowerShell

(Get-Command Get-Time).OutputType

Output

Name Type

---- ----

System.DateTime System.DateTime

Example 4: A function that shouldn't have output


The following example shows a custom function that should perform an action
but not
return anything.

PowerShell

function Invoke-Notepad

[OutputType([System.Void])]

Param ()

& notepad.exe | Out-Null

Notes
The value of the OutputType property of a FunctionInfo object is an
array of
System.Management.Automation.PSTypeName objects, which each have
Name and
Type properties.

To get only the name of each output type, use a command with the following
format.

PowerShell

(Get-Command Get-Date).OutputType | Select-Object -ExpandProperty Name

Or its shorter version.

PowerShell

(Get-Command Get-Date).OutputType.Name

The value of the OutputType property can be null. Use a null value when the
output isn't
a .NET type, such as a WMI object or a formatted view of an
object.

See also
about_Functions
about_Functions_Advanced
about_Functions_Advanced_Methods
about_Functions_Advanced_Parameters
about_Functions_CmdletBindingAttribute
about_Function_Provider
Article • 01/17/2023 • 5 minutes to read

Provider name
Function

Drives
Function:

Capabilities
ShouldProcess

Short description
Provides access to the functions defined in PowerShell.

Detailed description
The PowerShell Function provider lets you get, add, change, clear, and
delete the
functions and filters in 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.

The Function drive is a flat namespace that contains only the function
and filter objects.
Neither functions nor filters have child items.

The Function provider supports the following cmdlets, which are covered
in this article.

Get-Location
Set-Location
Get-Item
New-Item
Remove-Item
Clear-Item

Types exposed by this provider


Each function is an instance of the
System.Management.Automation.FunctionInfo
class.
Each filter is an instance of the
System.Management.Automation.FilterInfo
class.

Navigating the Function drive


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 PowerShell drive. To
reference a function

from another location, use the drive name ( Function: ) in


the path.

PowerShell

Set-Location Function:

To return to a file system drive, type the drive name. For example, type:

PowerShell

Set-Location C:

You can also work with the Function provider from any other PowerShell
drive. To
reference an function from another location, use the drive name
Function: in the path.

7 Note

PowerShell uses aliases to allow you a familiar way to work with provider
paths.
Commands such as dir and ls are now aliases for
Get-ChildItem,
cd is an alias for
Set-Location. and pwd is
an alias for Get-Location.

Getting functions
This command gets the list of all the functions in the current session. You can
use this
command from any PowerShell drive.

PowerShell
Get-ChildItem -Path Function:

The Function provider has no containers, so the above command has the
same effect
when used with Get-ChildItem .

PowerShell

Get-ChildItem -Path Function:

You can retrieve a function's definition by accessing the Definition


property, as shown
below.

PowerShell

(Get-Item -Path function:more).Definition

You can also retrieve a function's definition using its provider path prefixed
by the dollar
sign ( $ ).

PowerShell

$function:more

To retrieve the definition for a function that has a dash ( - ) in the name,
wrap the value
after the dollar sign in curly braces.

PowerShell

${function:Clear-Host}

Getting selected functions


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.

PowerShell

Get-Item -Path man | Format-Table -Wrap -Autosize

Working with Function provider paths


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.

PS C:\> Get-Item -Path Function:c:

PS Function:\> Get-Item -Path .\c:

Creating a function
This command uses the New-Item cmdlet to create a function called Win32: .
The
expression in braces is the script block that is represented by the
function name.

PowerShell

New-Item -Path Function:Win32: -Value {Set-Location C:\Windows\System32}

You can also create a function by typing it at the PowerShell command line. For
example,
tpe Function:Win32: {Set-Location C:\Windows\System32} . If you are
in the Function:
drive, you can omit the drive name.

Deleting a function
This command deletes the more: function from the current session.

PowerShell

Remove-Item Function:more:

Changing a function
This command uses the Set-Item cmdlet to change the prompt function so that
it
displays the time before the path.

PowerShell
Set-Item -Path Function:prompt -Value {

'PS '+ (Get-Date -Format t) + " " + (Get-Location) + '> '

Rename a function
This command uses the Rename-Item cmdlet to change the name of the help
function
to gh .

PowerShell

Rename-Item -Path Function:help -NewName gh

Copying a function
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 .

PowerShell

Copy-Item -Path Function:prompt -Destination Function:oldPrompt

Dynamic parameters
Dynamic parameters are cmdlet parameters that are added by a 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.

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

Using the pipeline


Provider cmdlets accept pipeline input. You can use the pipeline to simplify
task by
sending provider data from one cmdlet to another provider cmdlet.
To read more about
how to use the pipeline with provider cmdlets, see the
cmdlet references provided
throughout this article.

Getting help
Beginning in Windows PowerShell 3.0, you can get customized help topics for
provider
cmdlets that explain how those cmdlets behave in a file system drive.

To get the help topics that are customized for the file system drive, run a
Get-Help
command in a file system drive or use the -Path
parameter of Get-Help to specify a file
system drive.

PowerShell

Get-Help Get-ChildItem

PowerShell

Get-Help Get-ChildItem -Path function:

See also
about_Functions
about_Providers
about_Group_Policy_Settings
Article • 09/19/2022 • 5 minutes to read

Short description
Describes the Group Policy settings for Windows PowerShell

Long description
Windows PowerShell includes Group Policy settings to help you define
consistent
configuration values for Windows computers in an enterprise
environment.

The PowerShell Group Policy settings are in the following Group Policy paths:

Computer Configuration\

Administrative Templates\

Windows Components\

Windows PowerShell

User Configuration\

Administrative Templates\

Windows Components\

Windows PowerShell

Group policy settings in the User Configuration path take precedence over Group
Policy
settings in the Computer Configuration path.

The policies are as follows:

Turn on Module Logging: Sets the LogPipelineExecutionDetails property of


modules.
Turn on PowerShell Script Block Logging: Enables detailed logging of all
PowerShell scripts.
Turn on Script Execution: Sets the PowerShell execution policy.
Turn on PowerShell Transcription: enables capturing of input and output of
PowerShell commands into text-based transcripts.
Set the default source path for Update-Help : Sets the source for Updatable
Help to
a directory, not the Internet.
For more information about acquiring other templates and configuring Group
policy,
see
How to create and manage the Central Store for Group Policy Administrative
Templates in Windows .

Turn on module logging


The Turn on Module Logging policy setting turns on logging for selected
PowerShell
modules. The setting is effective in all sessions on all affected
computers.

If you enable this policy setting and specify one or more modules, pipeline
execution
events for the specified modules are recorded in the Windows
PowerShell log in Event
Viewer.

If you disable this policy setting, logging of execution events is disabled for
all
PowerShell modules.

If this policy setting is not configured, the LogPipelineExecutionDetails


property of each
module determines whether the execution events of a module are
logged. By default,
the LogPipelineExecutionDetails property of all modules
is set to False.

To turn on module logging for a module, use the following command format. The
module must be imported into the session and the setting is effective only in
the current
session.

PowerShell

Import-Module <Module-Name>

(Get-Module <Module-Name>).LogPipelineExecutionDetails = $true

To turn on module logging for all sessions on a particular computer, add the
previous
commands to the 'All Users' PowerShell profile
( $Profile.AllUsersAllHosts ).

For more information about module logging, see about_Modules.

Turn on PowerShell script block logging


The Turn on PowerShell Script Block Logging policy setting enables logging
of all
PowerShell script input to the Microsoft-Windows-PowerShell/Operational
event log. If
you enable this policy setting, PowerShell Core will log the
processing of commands,
script blocks, functions, and scripts - whether invoked
interactively, or through
automation.
If you disable this policy setting, logging of PowerShell script input is
disabled. If you
enable the Script Block Invocation Logging, PowerShell
additionally logs events when
invocation of a command, script block, function,
or script starts or stops. Enabling
Invocation Logging generates a high volume
of event logs.

Turn on script execution


The Turn on Script Execution policy setting sets the execution policy for
computers and
users, which determines which scripts are permitted to run.

If you enable the policy setting, you can select from among the following
policy settings.

Allow only signed scripts allows scripts to execute only if they are
signed by a
trusted publisher. This policy setting is equivalent to the
AllSigned execution
policy.

Allow local scripts and remote signed scripts allows all local scripts to
run. Scripts
that originate from the Internet must be signed by a trusted
publisher. This policy
setting is equivalent to the RemoteSigned execution
policy.

Allow all scripts allows all scripts to run. This policy setting is
equivalent to the
Unrestricted execution policy.

If you disable this policy setting, no scripts are allowed to run. This policy
setting is
equivalent to the Restricted execution policy.

If you disable or do not configure this policy setting, the execution policy
that is set for
the computer or user by the Set-ExecutionPolicy cmdlet
determines whether scripts are
permitted to run. The default value is
Restricted.

For more information, see about_Execution_Policies.

Turn on PowerShell transcription


The Turn on PowerShell Transcription policy setting lets you capture the
input and
output of PowerShell Core commands into text-based transcripts. If
you enable this
policy setting, PowerShell Core will enable transcription
logging for PowerShell Core and
any other applications that leverage the
PowerShell Core engine. By default, PowerShell
Core will record transcript
output to each users' My Documents directory, with a file
name that includes
'PowerShell_transcript', along with the computer name and time
started.
Enabling this policy is equivalent to calling the Start-Transcript cmdlet on
each
PowerShell Core session.
If you disable this policy setting, transcription logging of PowerShell-based
applications
is disabled by default, although transcripting can still be
enabled through the Start-
Transcript cmdlet.

If you use the OutputDirectory setting to enable transcription logging to a


shared
location, be sure to limit access to that directory to prevent users
from viewing the
transcripts of other users or computers.

Set the default source path for Update-Help


The Set the Default Source Path for Update-Help policy setting sets a
default value for
the SourcePath parameter of the Update-Help cmdlet.
This setting prevents users from
using the Update-Help cmdlet to download
help files from the Internet.

7 Note

This Group Policy setting appears under Computer Configuration and User
Configuration. However, only the Group Policy setting under Computer
Configuration is effective. The Group Policy setting under User
Configuration is
ignored.

The Update-Help cmdlet downloads and installs the newest help files for
PowerShell
modules and installs them on the computer. By default, Update-Help
downloads new
help files from an Internet location specified by the module.

However, you can use the Save-Help cmdlet to download the newest help files
to a file
system location, such as a network share, and then use the
Update-Help cmdlet to get
the help files from the file system location and
install them on the computer. The
SourcePath parameter of the Update-Help
cmdlet specifies the file system location.

By providing a default value for the SourcePath parameter, this Group


Policy setting
implicitly adds the SourcePath parameter to all
Update-Help commands. Users can
override the particular file system location
specified as the default value by entering a
different file system location.
But they cannot remove the SourcePath parameter from
the Update-Help
command.

If you enable this policy setting, you can specify a default value for the
SourcePath
parameter. Enter a file system location.

If this policy setting is disabled or not configured, there is no default value


for the
SourcePath parameter of the Update-Help cmdlet. Users can
download help from the
Internet or from any file system location.

For more information, see about_Updatable_Help.

Keywords
about_Group_Policies
about_GroupPolicy

See also
about_Execution_Policies
about_Modules
about_Updatable_Help
Get-ExecutionPolicy
Set-ExecutionPolicy
Update-Help
Save-Help
Get-Module
about_Hash_Tables
Article • 12/16/2022 • 10 minutes to read

Short description
Describes how to create, use, and sort hashtables in PowerShell.

Long description
A hashtable, also known as a dictionary or associative array, is a compact data
structure
that stores one or more key-value pairs. For example, a hash table
might contain a series
of IP addresses and computer names, where the IP
addresses are the keys and the
computer names are the values, or vice versa.

In PowerShell, each hashtable is a Hashtable


[System.Collections.Hashtable] object.
You can use the properties and methods
of Hashtable objects in PowerShell.

Beginning in PowerShell 3.0, you can use the [ordered] attribute to create an
[System.Collections.Specialized.OrderedDictionary] object in PowerShell.

Ordered dictionaries differ from hashtables in that the keys always appear in
the order
in which you list them. The order of keys in a hashtable isn't
determined.

The keys and value in hashtables are also .NET objects. They're most often
strings or
integers, but they can have any object type. You can also create
nested hashtables, in
which the value of a key is another hashtable.

Hashtables are frequently used because they're efficient for finding and
retrieving data.
You can use hashtables to store lists and to create calculated
properties in PowerShell.
And, PowerShell has a cmdlet,
ConvertFrom-StringData , that converts strings to a
hashtable.

Syntax
The syntax of a hashtable is as follows:

PowerShell

@{ <name> = <value>; [<name> = <value> ] ...}

The syntax of an ordered dictionary is as follows:

PowerShell

[ordered]@{ <name> = <value>; [<name> = <value> ] ...}

The [ordered] type accelerator was introduced in PowerShell 3.0.

Creating hashtables
To create a hashtable, follow these guidelines:

Begin the hashtable with an at sign ( @ ).


Enclose the hashtable in braces ( {} ).
Enter one or more key-value pairs for the content of the hashtable.
Use an equal sign ( = ) to separate each key from its value.
Use a semicolon ( ; ) or a line break to separate the key-value pairs.
Keys that contain spaces must be enclosed in quotation marks. Values must be
valid PowerShell expressions. Strings must appear in quotation marks, even if
they
don't include spaces.
To manage the hashtable, save it in a variable.
When assigning an ordered hashtable to a variable, place the [ordered] type
before the @ symbol. If you place it before the variable name, the command
fails.

To create an empty hashtable in the value of $hash, type:

PowerShell

$hash = @{}

You can also add keys and values to a hashtable when you create it. For
example, the
following statement creates a hashtable with three keys.

PowerShell

$hash = @{ Number = 1; Shape = "Square"; Color = "Blue"}

Creating ordered dictionaries


You can create an ordered dictionary by adding an object of the
OrderedDictionary
type, but the easiest way to create an ordered dictionary
is use the [ordered] attribute.
The [ordered] attribute is introduced in PowerShell 3.0.

Place the attribute immediately before the "@" symbol.

PowerShell

$hash = [ordered]@{ Number = 1; Shape = "Square"; Color = "Blue"}

You can use ordered dictionaries in the same way that you use hashtables.
Either type
can be used as the value of parameters that take a hashtable or
dictionary (iDictionary).

You can't use the [ordered] attribute to convert or cast a hashtable. If you
place the
ordered attribute before the variable name, the command fails with
the following error
message.

PowerShell

[ordered]$hash = @{}

At line:1 char:1

+ [ordered]$hash = @{}

+ ~~~~~~~~~~~~~~

The ordered attribute can be specified only on a hash literal node.

+ CategoryInfo : ParserError: (:) [],


ParentContainsErrorRecordException

+ FullyQualifiedErrorId : OrderedAttributeOnlyOnHashLiteralNode

To correct the expression, move the [ordered] attribute.

PowerShell

$hash = [ordered]@{}

You can cast an ordered dictionary to a hashtable, but you can't recover the
ordered
attribute, even if you clear the variable and enter new values. To
re-establish the order,
you must remove and recreate the variable.

PowerShell

[hashtable]$hash = [ordered]@{

Number = 1; Shape = "Square"; Color = "Blue"}

$hash

Output

Name Value

---- -----

Color Blue

Shape Square

Number 1

Displaying hashtables
To display a hashtable that's saved in a variable, type the variable name. By
default, a
hashtables is displayed as a table with one column for keys and one
for values.

PowerShell

$hash

Output

Name Value

---- -----

Shape Square

Color Blue

Number 1

hashtables have Keys and Values properties. Use dot notation to display
all the keys or
all the values.

PowerShell

$hash.keys

Output

Number

Shape

Color

PowerShell

$hash.values

Output

Square

Blue

Each key name is also a property of the hashtable, and its value is the value
of the key
name property. Use the following format to display the property
values.

Syntax

$hashtable.<key>

<value>

For example:

PowerShell

$hash.Number

$hash.Color

Blue

hashtables have a Count property that indicates the number of key-value


pairs in the
hashtable.

PowerShell

$hash.count

hashtable tables aren't arrays, so you can't use an integer as an index


into the hashtable,
but you can use a key name to index into the hashtable.
If the key is a string value,
enclose the key name in quotation marks.

For example:

PowerShell

$hash["Number"]

Handling property name collisions


If the key name collides with one of the property names of the HashTable
type, you can
use the psbase intrinsic member
to access those properties. For example, if the key
name is keys and you want
to return the collection of the HashTable keys, use this
syntax:
PowerShell

$hashtable.psbase.Keys

This applies for other types which implement the


System.Collections.IDictionary
interface, like OrderedDictionary.

Iterating over keys and values


You can iterate over the keys in a hashtable to process the values in several
ways. Each
of the examples in this section has identical output. They iterate
over the $hash variable
defined here:

PowerShell

$hash = [ordered]@{ Number = 1; Shape = "Square"; Color = "Blue"}

7 Note

In these examples, $hash is defined as an


ordered dictionary to ensure the output
is
always in the same order. These examples work the same for normal hashtables,
but the order of the output isn't predictable.

Each example returns a message for every key and its value:

Output

The value of 'Number' is: 1

The value of 'Shape' is: Square

The value of 'Color' is: Blue

This example uses a foreach block to iterate over the keys.

PowerShell

foreach ($Key in $hash.Keys) {

"The value of '$Key' is: $($hash[$Key])"

This example uses ForEach-Object to iterate over the keys.

PowerShell
$hash.Keys | ForEach-Object {

"The value of '$_' is: $($hash[$_])"

This example uses the GetEnumerator method to send each key-value pair
through the
pipeline to ForEach-Object .

PowerShell

$hash.GetEnumerator() | ForEach-Object {

"The value of '$($_.Key)' is: $($_.Value)"

This example uses the GetEnumerator and ForEach methods to iterate over
each key-
value pair.

PowerShell

$hash.GetEnumerator().ForEach({"The value of '$($_.Key)' is: $($_.Value)"})

Adding and Removing Keys and Values


To add keys and values to a hashtable, use the following command format.

PowerShell

$hash["<key>"] = "<value>"

For example, to add a "Time" key with a value of "Now" to the hashtable, use
the
following statement format.

PowerShell

$hash["Time"] = "Now"

You can also add keys and values to a hashtable using the Add method of the
System.Collections.Hashtable object. The Add method has the following
syntax:

PowerShell

Add(Key, Value)

For example, to add a Time key with a value of Now to the hashtable, use
the following
statement format.

PowerShell

$hash.Add("Time", "Now")

And, you can add keys and values to a hashtable using the addition operator
( + ) to add
a hashtable to an existing hashtable. For example, the following
statement adds a Time
key with a value of Now to the hashtable in the
$hash variable.

PowerShell

$hash = $hash + @{Time="Now"}

You can also add values that are stored in variables.

PowerShell

$t = "Today"

$now = (Get-Date)

$hash.Add($t, $now)

You can't use a subtraction operator to remove a key-value pair from a hash
table, but
you can use the Remove method of the Hashtable object. The Remove
method takes the
key as its value.

The Remove method has the following syntax:

Remove(Key)

For example, to remove the Time=Now key-value pair from the hashtable in the
value of
the $hash variable, type:

PowerShell

$hash.Remove("Time")

You can use all of the properties and methods of Hashtable objects in
PowerShell,
including Contains , Clear , Clone , and CopyTo . For more
information about Hashtable
objects, see
System.Collections.Hashtable.

Object Types in HashTables


The keys and values in a hashtable can have any .NET object type, and a single
hashtable
can have keys and values of multiple types.

The following statement creates a hashtable of process name strings and process
object
values and saves it in the $p variable.

PowerShell

$p = @{"PowerShell" = (Get-Process PowerShell);

"Notepad" = (Get-Process notepad)}

You can display the hashtable in $p and use the key-name properties to
display the
values.

PowerShell

$p

Name Value

---- -----

PowerShell System.Diagnostics.Process (PowerShell)

Notepad System.Diagnostics.Process (notepad)

$p.PowerShell

Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName

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

441 24 54196 54012 571 5.10 1788 PowerShell

$p.keys | foreach {$p.$_.handles}

441

251

The keys in a hashtable can also be any .NET type. The following statement adds
a key-
value pair to the hashtable in the $p variable. The key is a
Service object that represents
the WinRM service, and the value is the
current status of the service.

PowerShell

$p = $p + @{(Get-Service WinRM) = ((Get-Service WinRM).Status)}

You can display and access the new key-value pair using the same methods that
you use
for other pairs in the hashtable.

PowerShell

$p

Name Value

---- -----

PowerShell System.Diagnostics.Process (PowerShell)

Notepad System.Diagnostics.Process (notepad)

System.ServiceProcess.Servi... Running

$p.keys

PowerShell

Notepad

Status Name DisplayName

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

Running winrm Windows Remote Management (WS-Manag...

$p.keys | foreach {$_.name}

winrm

The keys and values in a hashtable can also be Hashtable objects. The following
statement adds key-value pair to the hashtable in the $p variable in which
the key is a
string, Hash2, and the value is a hashtable with three key-value
pairs.

PowerShell

$p = $p + @{"Hash2"= @{a=1; b=2; c=3}}

You can display and access the new values using the same methods.

PowerShell

$p

Name Value

---- -----

PowerShell System.Diagnostics.Process (PowerShell)

Notepad System.Diagnostics.Process (notepad)

System.ServiceProcess.Servi... Running

Hash2 {a, b, c}

$p.Hash2

Name Value

---- -----

a 1

b 2

c 3

$p.Hash2.b

Sorting Keys and Values


The items in a hashtable are intrinsically unordered. The key-value pairs might
appear in
a different order each time that you display them.

Although you can't sort a hashtable, you can use the GetEnumerator method of
hashtables to enumerate the keys and values, and then use the Sort-Object
cmdlet to
sort the enumerated values for display.

For example, the following commands enumerate the keys and values in the hash
table
in the $p variable and then sort the keys in alphabetical order.

PowerShell

$p.GetEnumerator() | Sort-Object -Property key

Name Value

---- -----

Notepad System.Diagnostics.Process (notepad)

PowerShell System.Diagnostics.Process (PowerShell)

System.ServiceProcess.Servi... Running

The following command uses the same procedure to sort the hash values in
descending
order.

PowerShell

$p.getenumerator() | Sort-Object -Property Value -Descending

Name Value

---- -----

PowerShell System.Diagnostics.Process (PowerShell)

Notepad System.Diagnostics.Process (notepad)

System.ServiceProcess.Servi... Running

Creating Objects from hashtables


Beginning in PowerShell 3.0, you can create an object from a hashtable of
properties
and property values.

The syntax is as follows:

PowerShell

[<class-name>]@{

<property-name>=<property-value>

<property-name>=<property-value>

This method works only for classes that have a constructor that has no
parameters. The
object properties must be public and settable.

For more information, see about_Object_Creation.

ConvertFrom-StringData
The ConvertFrom-StringData cmdlet converts a string or a here-string of
key-value pairs
into a hashtable. 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 hashtable 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 hashtable.

The following command creates a here-string of the key-value pairs and then
saves it in
the $string variable.

PowerShell

$string = @"

Msg1 = Type "Windows".

Msg2 = She said, "Hello, World."

Msg3 = Enter an alias (or "nickname").

"@

This command uses the ConvertFrom-StringData cmdlet to convert the


here-string into a
hashtable.
PowerShell

ConvertFrom-StringData $string

Name Value

---- -----

Msg3 Enter an alias (or "nickname").

Msg2 She said, "Hello, World."

Msg1 Type "Windows".

For more information about here-strings, see


about_Quoting_Rules.

See also
about_Arrays
about_Intrinsic_Members
about_Object_Creation
about_Quoting_Rules
about_Script_Internationalization
Import-LocalizedData
ConvertFrom-StringData
System.Collections.Hashtable
about_Hidden
Article • 09/19/2022 • 3 minutes to read

Short description
Describes the hidden keyword, which hides class members from default
Get-Member
results.

Long description
When you use the hidden keyword in a script, you hide the members of a class
by
default. Hidden members do not display in the default results of the
Get-Member cmdlet,
IntelliSense, or tab completion results. To display members
that you have hidden with
the hidden keyword, add the Force parameter to a
Get-Member command.

The hidden keyword can hide:

methods (including constructors)


events
alias properties
other member types (including static members)

Hidden members are not displayed in tab completion or IntelliSense unless the
completion occurs in the class that defines the hidden member.

The new attribute, System.Management.Automation.HiddenAttribute, enables C#


code
to have the same semantics within PowerShell.

The hidden keyword is useful for creating properties and methods within a
class that
you do not necessarily want users of the class to see or readily be
able to edit.

The hidden keyword has no effect on how you can view or make changes to
members
of a class. Like all language keywords in PowerShell, hidden is not
case-sensitive, and
hidden members are still public.

The hidden keyword, along with custom classes, was introduced in Windows
PowerShell
5.0.

EXAMPLE
The following example shows how to use the hidden keyword in a class
definition. The
Car class method, Drive, has a property, rides, that
does not need to be viewed or
changed as it merely tallies the number of times
that Drive is called on the Car class.
That metric that is not important
to users of the class (consider, for example, that when
you are buying a car,
you do not ask the seller on how many drives the car has been
taken).

Because there is little need for users of the class to change this property, we
can hide
the property from Get-Member and automatic completion results by
using the hidden
keyword.

Add the hidden keyword by entering it on the same statement line as the
property and
its data type. Although the keyword can be in any order on this
line, starting the
statement with the hidden keyword makes it easier for you
later to identify all members
that you have hidden.

PowerShell

class Car

# Properties

[String] $Color

[String] $ModelYear

[int] $Distance

# Method

[int] Drive ([int]$miles)

$this.Distance += $miles

$this.rides++

return $this.Distance

# Hidden property of the Drive method

hidden [int] $rides = 0

Now, create a new instance of the Car class, and save it in a variable,
$TestCar .

PowerShell

$TestCar = [Car]::new()

After you create the new instance, pipe the contents of the $TestCar variable
to Get-
Member . Observe that the rides property is not among the members
listed in the Get-
Member command results.
Output

PS C:\Windows\system32> $TestCar | Get-Member

TypeName: Car

Name MemberType Definition


---- ---------- ----------
Drive Method int Drive(int miles)

Equals Method bool Equals(System.Object obj)

GetHashCode Method int GetHashCode()

GetType Method type GetType()

ToString Method string ToString()

Color Property string Color {get;set;}

Distance Property int Distance {get;set;}

ModelYear Property string ModelYear {get;set;}

Now, try running Get-Member again, but this time, add the -Force parameter.
Note that
the results contain the hidden rides property, among other members
that are hidden by
default.

Output

PS C:\Windows\system32> $TestCar | Get-Member -Force

TypeName: Car

Name MemberType Definition

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

pstypenames CodeProperty System.Collections.ObjectModel.Collection`1

psadapted MemberSet psadapted {Color, ModelYear, Distance,

psbase MemberSet psbase {Color, ModelYear, Distance,...

psextended MemberSet psextended {}

psobject MemberSet psobject {BaseObject, Members,...

Drive Method int Drive(int miles)

Equals Method bool Equals(System.Object obj)

GetHashCode Method int GetHashCode()

GetType Method type GetType()

get_Color Method string get_Color()

get_Distance Method int get_Distance()

get_ModelYear Method string get_ModelYear()

get_rides Method int get_rides()

set_Color Method void set_Color(string )

set_Distance Method void set_Distance(int )

set_ModelYear Method void set_ModelYear(string )

set_rides Method void set_rides(int )

ToString Method string ToString()

Color Property string Color {get;set;}

Distance Property int Distance {get;set;}

ModelYear Property string ModelYear {get;set;}

rides Property int rides {get;set;}

See also
about_Classes
about_Language_Keywords
about_Wildcards
Get-Member
about_History
Article • 09/19/2022 • 2 minutes to read

Short description
Describes how to get and run commands in the command history.

Long description
When you enter a command at the command prompt, 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.

PowerShell has two different history providers: the built-in history and the
history
managed by the PSReadLine module. The histories are managed
separately, but both
histories are available in sessions where PSReadLine
is loaded.

Using the PSReadLine history


The PSReadLine history tracks the commands used in all PowerShell sessions.
The history
is written to a central file per host. That history file is
available to all sessions and
contains all past history. The history is not
deleted when the session ends. Also, that
history cannot be managed by the
*-History cmdlets. For more information, see
about_PSReadLine.

Using the built-in session history


The built-in history only tracks the commands used in the current session. The
history is
not available to other sessions and is deleted when the session ends.

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


Cmdlet Alias Description

Add-History Adds a command to the command history.

Clear-History clhy Deletes commands from the command history.

Keyboard Shortcuts for Managing History


In the PowerShell console, you can use the following shortcuts to manage the
command
history.

UpArrow - Displays the previous command.


DownArrow - Displays the next command.
F7 - Displays the command history.
ESC - To hide the history.
F8 - Finds a command. Type one or more characters then press
F8 . Press F8

again the next instance.


F9 - Find a command by history ID. Type the history ID then press
F9 . Press F7

to find the ID.


# <string> Tab - Search the history for
*<string>* and returns the most recent
match. If you press Tab
repeatedly, it cycles through the matching items in your
history.

7 Note

These key bindings are implemented by the console host application. Other
applications, such as Visual Studio Code or Windows Terminal, can have
different
key bindings. The bindings can be overridden by the PSReadLine
module.
PSReadLine loads automatically when you start a PowerShell session.
With
PSReadLine loaded, F7 and F9 are not bound to any
function. PSReadLine does
not provide equivalent functionality. For more
information, see about_PSReadLine.

MaximumHistoryCount
The $MaximumHistoryCount preference variable determines the maximum number of
commands that PowerShell saves in the command history. The default value is
4096.

For example, the following command lowers the $MaximumHistoryCount to 100


commands:

PowerShell
$MaximumHistoryCount = 100

To apply the setting, restart PowerShell.

To save the new variable value for all your PowerShell sessions, add the
assignment
statement to a PowerShell profile. For more information about
profiles, see
about_Profiles.

For more information about the $MaximumHistoryCount preference variable, see


about_Preference_Variables.

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_Preference_Variables
about_Profiles
about_PSReadLine
about_Variables
about_If
Article • 09/19/2022 • 2 minutes to read

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:

PowerShell

if (<test1>)

{<statement list 1>}

[elseif (<test2>)

{<statement list 2>}]

[else

{<statement list 3>}]

When you run an If statement, PowerShell evaluates the <test1> conditional


expression as true or false. If <test1> is true, <statement list 1> runs,
and PowerShell
exits the If statement. If <test1> is false, PowerShell
evaluates the condition specified
by the <test2> conditional statement.

For more information about boolean evaluation, see


about_Booleans.

If <test2> is true, <statement list 2> runs, and PowerShell exits the If
statement. If
both <test1> and <test2> evaluate to false, the
<statement list 3 > code block runs,
and 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:

PowerShell

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:

PowerShell

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:

PowerShell

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_Booleans
about_Comparison_Operators
about_Switch
About intrinsic members
Article • 01/25/2023 • 3 minutes to read

Short description
Provides information about PowerShell's intrinsic members that are available to
all
PowerShell objects.

Detailed description
When objects are created, PowerShell adds some "hidden" properties and methods
to
each object. These properties and methods are known as intrinsic members.
These
intrinsic members are normally hidden from view. These hidden members can
be seen
using the Force parameter of Get-Member.

Object views
The intrinsic members include a set of MemberSet properties that represent
a view of
the object. For more information about MemberSet properties, see
PSMemberSet.

Every PowerShell object includes the following properties.

psbase

The psbase MemberSet contains the members of the base object without
extension or adaptation. Depending on the object type it's either a .NET
instance
wrapped by a [psobject] instance or, if there's no wrapper, it's
the input object
itself.

psadapted

The psadapted MemberSet shows the base object plus the adapted members,
if
present. Adapted members are added by the Extended Type System (ETS).

psextended

The psextended MemberSet only shows the members added by the


Types.ps1xml
files and the Add-Member cmdlet. Any object can be
extended at runtime using
the Add-Member cmdlet.
psobject

The psobject MemberSet a rich source of reflection for any object that
includes
methods, properties, and other information about the object.

Examples
For this example, $hash is a hashtable containing information about a user.
The Force
parameter of Get-Member shows us the intrinsic members of the
object.

PowerShell

$hash | Get-Member -Force -Type MemberSet, CodeProperty

Output

TypeName: System.Collections.Hashtable

Name MemberType Definition

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

pstypenames CodeProperty
System.Collections.ObjectModel.Collection`1[[System.String,
System.Private.CoreLib, Version=7…

psadapted MemberSet psadapted {Item, IsReadOnly, IsFixedSize,


IsSynchronized, Keys, Values, SyncRoot, Count, Add,…

psbase MemberSet psbase {Item, IsReadOnly, IsFixedSize,


IsSynchronized, Keys, Values, SyncRoot, Count, Add, Cl…

psextended MemberSet psextended {}

psobject MemberSet psobject {Members, Properties, Methods,


ImmediateBaseObject, BaseObject, TypeNames, get_Membe…

Using psobject is similar to using Get-Member , but provides more


flexibility. For
example, you can enumerate the properties of an object and
their values.

PowerShell

$hash.psobject.Properties | Select-Object Name, MemberType, Value

Output

Name MemberType Value

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

IsReadOnly Property False

IsFixedSize Property False

IsSynchronized Property False

Keys Property {Age, Name}

Values Property {33, Bob}

SyncRoot Property {[Age, 33], [Name, Bob]}

Count Property 2

Compare that to the object created by converting the hashtable to a


PSCustomObject.

PowerShell

$user = [pscustomobject]$hash

$user.psobject.Properties | Select-Object Name, MemberType, Value

Output

Name MemberType Value

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

Age NoteProperty 33

Name NoteProperty Bob

Notice that the keys from the hashtable have been converted to properties in
the
PSCustomObject. The new properties are now part of the psextended
MemberSet.

PowerShell

$user | Get-Member -Force -Type MemberSet, CodeProperty

Output

TypeName: System.Management.Automation.PSCustomObject

Name MemberType Definition

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

pstypenames CodeProperty
System.Collections.ObjectModel.Collection`1[[System.String,
System.Private.CoreLib, Version=7…

psadapted MemberSet psadapted {ToString, GetType, Equals, GetHashCode}

psbase MemberSet psbase {ToString, GetType, Equals, GetHashCode}

psextended MemberSet psextended {Age, Name}

psobject MemberSet psobject {Members, Properties, Methods,


ImmediateBaseObject, BaseObject, TypeNames, get_Membe…

Type information
The pstypenames CodeProperty lists the object type hierarchy in order of
inheritance.
For example:
PowerShell

$file = Get-Item C:\temp\test.txt

$file.pstypenames

Output

System.IO.FileInfo

System.IO.FileSystemInfo

System.MarshalByRefObject

System.Object

The Output starts with the most specific object type, System.IO.FileInfo , and
continues
down to the most generic type, System.Object .

Methods
PowerShell adds two hidden methods to all PowerShell objects. These methods are
not
visible using the Get-Member -Force command or tab completion.

ForEach() and Where()


The ForEach() and Where() methods are available to all PowerShell objects.
However,
they're most useful when working with collections. For more
information on how to use
these methods, see about_Arrays.

Properties
The Count and Length properties are available to all PowerShell
objects. These are
similar to each other but may work differently depending on
the data type. For more
information about these properties, see
about_Properties.

Array indexing scalar types


When an object isn't an indexed collection, using the index operator to access
the first
element returns the object itself. Index values beyond the first
element return $null .

PS> (2)[0]

PS> (2)[-1]

PS> (2)[1] -eq $null

True

PS> (2)[0,0] -eq $null

True

For more information, see about_Operators.

New() method for types


Beginning in PowerShell 5.0, PowerShell adds a static New() method for all
.NET types.
The following examples produce the same result.

PowerShell

$expression = New-Object -TypeName regex -ArgumentList 'pattern'

$expression = [regex]::new('pattern')

Using the new() method performs better than using New-Object .

For more information, see about_Classes.


about_Jobs
Article • 09/19/2022 • 8 minutes to read

Short description
Provides information about how PowerShell background jobs run a command or
expression in the background without interacting with the current session.

Long description
PowerShell concurrently runs commands and scripts through jobs. There are three
jobs
types provided by PowerShell to support concurrency.

RemoteJob - Commands and scripts run on a remote session. For information,


see

about_Remote_Jobs.
BackgroundJob - Commands and scripts run in a separate process on the local

machine.
PSTaskJob or ThreadJob - Commands and scripts run in a separate thread
within

the same process on the local machine. For more information, see
about_Thread_Jobs.

Running scripts remotely, on a separate machine or in a separate process,


provides
great isolation. Any errors that occur in the remote job don't affect
other running jobs or
the parent session that started the job. However, the
remoting layer adds overhead,
including object serialization. All objects are
serialized and deserialized as they're passed
between the parent session and
the remote (job) session. Serialization of large complex
data objects can
consume large amounts of compute and memory resources and
transfer large
amounts of data across the network.

Thread-based jobs aren't as robust as remote and background jobs, because they
run in
the same process on different threads. If one job has a critical error
that crashes the
process, then all other jobs in the process are terminated.

However, thread-based jobs require less overhead. They don't use the remoting
layer or
serialization. The result objects are returned as references to live
objects in the current
session. Without this overhead, thread-based jobs run
faster and use fewer resources
than the other job types.

) Important
The parent session that created the job also monitors the job status and
collects
pipeline data. The job child process is terminated by the parent
process once the
job reaches a finished state. If the parent session is
terminated, all running child
jobs are terminated along with their child
processes.

There are two ways work around this situation:

1. Use Invoke-Command to create jobs that run in disconnected sessions. For


more
information, see about_Remote_Jobs.
2. Use Start-Process to create a new process rather than a job. For more
information, see
Start-Process.

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 creates a background job on a
remote

computer. You can use Invoke-Command to run any job command


remotely,
including Start-Job .

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

PowerShell

Start-Job -ScriptBlock {Get-Process}

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.

The Start-Job command returns an object that represents the job. The job
object
contains useful information about the job, but it doesn't contain the
job results.

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

PowerShell

$job = Start-Job -ScriptBlock {Get-Process}

Getting job objects


The Get-Job cmdlet returns objects that represent the background jobs that
were
started in the current session. Without parameters, Get-Job returns all
of the jobs that
were started in the current session.

PowerShell

Get-Job

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.

Output

Id Name PSJobTypeName State HasMoreData Location Command

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

1 Job1 BackgroundJob Complete True localhost Get-Process

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

PowerShell

$job = Get-Job -Id 1

Getting the results of a job


When you run a background job, the results don't appear immediately. To get
the
results of a background job, use the Receive-Job cmdlet.

The following example, the Receive-Job cmdlet gets the results of the job
using job
object in the $job variable.

PowerShell

Receive-Job -Job $job

Output

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

PowerShell

$results = Receive-Job -Job $job

Getting and keeping partial job results


The Receive-Job cmdlet gets the results of a background job. If the job is
complete,
Receive-Job gets all job results. 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.

By default, Receive-Job deletes the results from the cache where job results
are stored.
When you run Receive-Job again, you get only the new
results that arrived after the first
run.

The following commands show the results of Receive-Job commands run


before the job
is complete.

PowerShell
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

Use the Keep parameter to prevent Receive-Job from deleting the job
results that are
returned. The following commands show the effect of using the
Keep parameter on a
job that's not yet complete.

PowerShell

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 complete, 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 the background jobs in
the current session.

PowerShell
Get-Job

The results appear in a table. The status of the job appears in the State
column.

Output

Id Name PSJobTypeName State HasMoreData Location Command

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

1 Job1 BackgroundJob Complete True localhost Get-Process

2 Job2 BackgroundJob Running True localhost Get-EventLog -Log ...

3 Job3 BackgroundJob Complete True localhost dir -Path C:\* -Re...

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. Use the State property
to determine when the job is
complete.

You can also use the Wait parameter of the Receive-Job cmdlet. When use
use this
parameter, the cmdlet doesn't return the command prompt until the job
is completed
and all results are available.

You can also use the Wait-Job cmdlet to wait for any or all of the results of
the job.
Wait-Job lets you wait for one or more specific job or for all jobs.
The following

command uses the Wait-Job cmdlet to wait for a job with ID


10.

PowerShell

Wait-Job -ID 10

As a result, the 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.

PowerShell

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.

PowerShell

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

PowerShell

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

PowerShell

Remove-Job -Job $job

Investigating a failed job


Jobs can fail for many reasons. the job object contains a Reason property
that contains
information about the cause of the failure.

The following example starts a job without the required credentials.

PowerShell

$job = Start-Job -ScriptBlock {New-Item -Path HKLM:\Software\MyCompany}

Get-Job $job

Id Name PSJobTypeName State HasMoreData Location Command

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

1 Job1 BackgroundJob Failed False localhost New-Item -Path HKLM:...

Inspect the Reason property to find the error that caused the job to fail.

PowerShell
$job.ChildJobs[0].JobStateInfo.Reason

In this case, the job failed because the remote computer required explicit
credentials to
run the command. The Reason property contains the following
message:

Connecting to remote server failed with the following error message: "Access
is
denied".

See also
about_Job_Details
about_PSSessions
about_Remote
about_Remote_Jobs
about_Thread_Jobs
Invoke-Command
Get-Job
Receive-Job
Remove-Job
Start-Job
Stop-Job
Wait-Job
about_Job_Details
Article • 09/19/2022 • 9 minutes to read

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

This topic is a supplement to the about_Jobs,


about_Thread_Jobs,
and
about_Remote_Jobs topics.

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 PowerShell command prompt is suppressed


until the command is complete. But a background job does not suppress the
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 PowerShell 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 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 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
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 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 InstanceId that differ
from the parent job so that you can manage
the parent and child jobs
individually or as a unit.

To get the parent and child jobs of a job, use the IncludeChildJobs
parameter of the
Get-Job cmdlet. The IncludeChildJob parameter was
introduced in Windows PowerShell
3.0.

PowerShell
PS> Get-Job -IncludeChildJob

Id Name PSJobTypeName State HasMoreData Location Command

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

1 Job1 RemoteJob Failed True localhost Get-Process

2 Job2 Completed True Server01 Get-Process

3 Job3 Failed False localhost Get-Process

To get the parent job and only the child jobs with a particular State
value, use the
ChildJobState parameter of the Get-Job cmdlet. The
ChildJobState parameter was
introduced in Windows PowerShell 3.0.

PowerShell

PS> Get-Job -ChildJobState Failed

Id Name PSJobTypeName State HasMoreData Location Command

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

1 Job1 RemoteJob Failed True localhost Get-Process

3 Job3 Failed False localhost Get-Process

To get the child jobs of a job on all versions of PowerShell,


use the ChildJob property of
the parent job.

PowerShell

PS> (Get-Job Job1).ChildJobs

Id Name PSJobTypeName State HasMoreData Location Command

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

2 Job2 Completed True Server01 Get-Process

3 Job3 Failed False localhost Get-Process

You can also use a Get-Job command on the child job, as shown in the
following
command:

PowerShell

PS> Get-Job Job3

Id Name PSJobTypeName State HasMoreData Location Command

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

3 Job3 Failed False 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 using the AsJob parameter of
Invoke-Command .

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.

PowerShell

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.

PowerShell

PS> $j | Format-List Name, ChildJobs

Name : Job3

ChildJobs : {Job4, Job5, Job6}

When you display the parent job, it shows that the job failed.

PowerShell

PS> $j

Id Name PSJobTypeName State HasMoreData Location

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

3 Job3 RemotingJob Failed False localhost,Server...

But when you run a Get-Job command that gets the child jobs, the output
shows that
only one child job failed.

PowerShell

PS> Get-Job -IncludeChildJobs

Id Name PSJobTypeName State HasMoreData Location Command

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

3 Job3 RemotingJob Failed False localhost,Server...

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.

PowerShell

PS> Receive-Job -Name Job6 -Keep | Format-Table ComputerName,

>> DateTime -AutoSize

ComputerName DateTime

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

Server02 Thursday, March 13, 2008 4:16:03 PM

The child jobs feature of PowerShell background jobs gives you


more control over the
jobs that you run.

Job types
PowerShell supports different types of jobs for different tasks. Beginning in
Windows
PowerShell 3.0, developers can write "job source adapters" that add
new job types to
PowerShell and include the job source adapters in modules.
When you import the
module, you can use the new job type in your session.

For example, the PSScheduledJob module adds scheduled jobs and the PSWorkflow
module adds workflow jobs.

Custom jobs types might differ significantly from standard PowerShell


background jobs.
For example, scheduled jobs are saved on disk; they do not
exist only in a particular
session. Workflow jobs can be suspended and
resumed.

The cmdlets that you use to manage custom jobs depend on the job type. For
some,
you use the standard job cmdlets, such as Get-Job and Start-Job . Others
come with
specialized cmdlets that manage only a particular type of job. For
detailed information
about custom job types, see the help topics about the job
type.

To find the job type of a job, use the Get-Job cmdlet. Get-Job returns
different job
objects for different types of jobs. The value of the
PSJobTypeName property of the job
objects that Get-Job returns indicates
the job type.

The following table lists the job types that come with PowerShell.

Job Type Description

BackgroundJob Started using the Start-Job cmdlet.

RemoteJob Started using the AsJob parameter of the

Invoke-Command cmdlet.

PSWorkflowJob Started using the AsJob parameter of a workflow.

PSScheduledJob An instance of a scheduled job started by a job trigger.

CIMJob Started using the AsJob parameter of a cmdlet from a

CDXML module.

WMIJob Started using the AsJob parameter of a cmdlet from a

WMI module.

PSEventJob Created using Register-ObjectEvent and specifying an

action with the Action parameter.

NOTE: Before using the Get-Job cmdlet to get jobs of a particular type, verify
that the
module that adds the job type is imported into the current session.
Otherwise, Get-Job
does not get jobs of that type.

Examples
The following commands create a local background job, a remote background job,
a
workflow job, and a scheduled job. Then, it uses the Get-Job cmdlet to get
the jobs.
Get-Job does not get the scheduled job, but it gets any started
instances of the
scheduled job.
Start a background job on the local computer.

PowerShell

PS> Start-Job -Name LocalData {Get-Process}

Id Name PSJobTypeName State HasMoreData Location Command

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

2 LocalData BackgroundJob Running True localhost Get-Process

Start a background job that runs on a remote computer.

PowerShell

PS> Invoke-Command -ComputerName Server01 {Get-Process} `

-AsJob -JobName RemoteData

Id Name PSJobTypeName State HasMoreData Location Command

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

2 RemoteData RemoteJob Running True Server01 Get-Process

Create a scheduled job

PowerShell

PS> Register-ScheduledJob -Name ScheduledJob -ScriptBlock `

{Get-Process} -Trigger (New-JobTrigger -Once -At "3 PM")

Id Name JobTriggers Command Enabled

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

1 ScheduledJob 1 Get-Process True

Create a workflow.

PowerShell

PS> workflow Test-Workflow {Get-Process}

Run the workflow as a job.

PowerShell

PS> Test-Workflow -AsJob -JobName TestWFJob

Id Name PSJobTypeName State HasMoreData Location Command

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

2 TestWFJob PSWorkflowJob NotStarted True localhost Get-Process

Get the jobs. The Get-Job command does not get scheduled jobs, but it gets
instances
of the scheduled job that are started.

PowerShell

PS> Get-Job

Id Name PSJobTypeName State HasMoreData Location Command

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

2 LocalData BackgroundJob Completed True localhost Get-Process

4 RemoteData RemoteJob Completed True Server01 Get-Process

6 TestWFJob PSWorkflowJob Completed True localhost WorkflowJob

8 ScheduledJob PSScheduledJob Completed True localhost Get-Process

To get scheduled jobs, use the Get-ScheduledJob cmdlet.

PowerShell

PS> Get-ScheduledJob

Id Name JobTriggers Command Enabled

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

1 ScheduledJob 1 Get-Process True

See also
about_Jobs
about_Remote
about_Remote_Jobs
about_Thread_Jobs
Invoke-Command
Get-Job
Remove-Job
Start-Job
Stop-Job
Wait-Job
Enter-PSSession
Exit-PSSession
New-PSSession
about_Join
Article • 09/19/2022 • 2 minutes to read

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.

PowerShell

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

PowerShell
-join "a", "b", "c"

-join ("a", "b", "c")

abc

$z = "a", "b", "c"

-join $z

abc

Examples
The following statement joins three strings:

PowerShell

-join ("Windows", "PowerShell", "2.0")

WindowsPowerShell2.0

The following statement joins three strings delimited by a space:

PowerShell

"Windows", "PowerShell", "2.0" -join " "

Windows PowerShell 2.0

The following statements use a multiple-character delimiter to join three


strings:

PowerShell

$a = "WIND", "S P", "ERSHELL"

$a -join "OW"

WINDOWS POWERSHELL

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:

PowerShell

$a = @'

'@

(-split $a) -join " "

a b c

See also
about_Operators
about_Comparison_Operators
about_Split
about_Language_Keywords
Article • 09/19/2022 • 7 minutes to read

Short description
Describes the keywords in the PowerShell scripting language.

Long description
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

class about_Classes

continue about_Continue, about_Trap

data about_Data_Sections

define Reserved for future use

do about_Do, about_While

dynamicparam about_Functions_Advanced_Parameters

else about_If

elseif about_If

end about_Functions, about_Functions_Advanced_Methods

enum about_Enum

exit Described in this topic

filter about_Functions

finally about_Try_Catch_Finally
Keyword Reference

for about_For

foreach about_ForEach

from Reserved for future use

function about_Functions, about_Functions_Advanced

hidden about_Hidden

if about_If

in about_ForEach

param about_Functions

process about_Functions, about_Functions_Advanced

return about_Return

static about_Classes

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

using about_Using, about_Classes

var Reserved for future use

while about_While, about_Do

The following keywords are used by PowerShell workflows:

Keyword Reference

inlinescript about_InlineScript

parallel about_Parallel

sequence about_Sequence

workflow about_Workflows
For more information about workflows, see
Running PowerShell Commands in a
Workflow.

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:

Syntax

function <name> {

dynamicparam {<statement list>}

begin {<statement list>}

process {<statement list>}

end {<statement list>}

break
Causes a script to exit a loop.

Syntax:

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:

Syntax

try {<statement list>}

catch [[<error type>]] {<statement list>}

class
Specifies a new class in PowerShell.

Syntax:

Syntax

class <class-name> {

[[hidden] [static] <property-definition> ...]

[<class-name>([argument-list>]) {<constructor-statement-list>} ...]

[[hidden] [static] <method-definition> ...]

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:

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:

Syntax

data <variable> [-supportedCommand <cmdlet-name>] {<permitted content>}

do
Used with the while or until keyword as a looping construct. PowerShell
runs the
statement list at least one time, unlike a loop that uses while .

Syntax for while :

Syntax

do {<statement list>} while (<condition>)

Syntax for until :

Syntax

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

Syntax:

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:

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:

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:

Syntax

function <name> {

dynamicparam {<statement list>}

begin {<statement list>}

process {<statement list>}

end {<statement list>}

enum
enum is used to declare an enumeration; a distinct type that consists of a
set of named

labels called the enumerator list.

Syntax:

Syntax

enum <enum-name> {

<label> [= <int-value>]

...

exit
Causes PowerShell to exit a script or a PowerShell instance.

Syntax:

Syntax

exit

exit <exitcode>

When you use powershell.exe with the File parameter, the .ps1 (script)
file itself should
include instructions for handling any errors or exceptions
that occur while the script is
running. You should only use the exit statement
to indicate the post-execution status
of the script.

Any number between [int]::MinValue and [int]::MaxValue is allowed.

In PowerShell, the exit statement sets the value of the $LASTEXITCODE


variable. In the
Windows Command Shell ( cmd.exe ), the exit statement sets the
value of the
%ERRORLEVEL% environment variable.

Any argument that is non-numeric or outside the platform-specific range is


translated to
the value of 0 .

In the following example, the user sets the error level variable value to 4
by adding exit
4 to the script file test.ps1 .

Windows Command Prompt

C:\scripts\test>type test.ps1

exit 4

C:\scripts\test>powershell -file ./test.ps1

C:\scripts\test>echo %ERRORLEVEL%

When you run powershell.exe -File <path to a script> and the script file terminates
with an exit command, the exit code is set to the numeric argument used with
the
exit command. If the script has no exit statement, the exit code is
always 0 when the

script completes without error or 1 when the script


terminates from an unhandled
exception.

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:

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:

Syntax

try {<statement list>}

catch [<error type>] {<statement list>}

finally {<statement list>}

for
Defines a loop with a condition.

Syntax:

Syntax

for (<initialize>; <condition>; <iterate>) { <statement list> }

foreach
Defines a loop using each member of a collection.

Syntax:

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. You can also 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:

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:

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:

Syntax

if (<condition>) {<statement list>}

hidden
Hides class members from the default results of the Get-Member cmdlet,
IntelliSense, and
tab completion results.

Syntax:

Syntax

hidden [data type] $member_name

in
Used in a foreach statement to create a loop that uses each member of a
collection.

Syntax:

Syntax
foreach (<item> in <collection>){<statement list>}

param
Defines the parameters in a function.

Syntax:

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:

Syntax

function <name> {

dynamicparam {<statement list>}

begin {<statement list>}

process {<statement list>}

end {<statement list>}

return
Causes PowerShell to leave the current scope, such as a script or function, and
writes the
optional expression to the output.

Syntax:
Syntax

return [<expression>]

static
Specifies the property or method defined is common to all instances of the
class in
which it is defined.

See class for usage examples.

switch
To check multiple conditions, use a switch statement. The switch statement
is
equivalent to a series of if statements, but it is simpler.

The switch statement lists each condition and an optional action. If a


condition obtains,
the action is performed.

Syntax 1:

Syntax

switch [-regex|-wildcard|-exact][-casesensitive] ( <value> )

<string>|<number>|<variable>|{ <expression> } {<statement list>}

<string>|<number>|<variable>|{ <expression> } {<statement list>}

...

default {<statement list>}

Syntax 2:

Syntax

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:

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:

Syntax

trap [[<error type>]] {<statement list>}

try
Defines a statement list to be checked for errors while the statements run. If
an error
occurs, 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:

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:
Syntax

do {<statement list>} until (<condition>)

using
Allows you to indicate which namespaces are used in the session. Type names,
classes,
and members require less typing to reference them. You can also
include classes from
modules.

Namespace syntax:

Syntax

using namespace <.Net-framework-namespace>

Module syntax:

Syntax

using module <module-name>

Assembly syntax:

Syntax

using assembly <.NET-assembly-path>

using assembly <.NET-framework-namespace>

For more information, see about_Using.

while
The while statement is a looping construct where the condition is tested
before the
statements are executed. If the condition is false, then the
statements do not execute.

Statement syntax:

Syntax

while (<condition>) {

<statements>

When used in a do statement, while is part of a looping construct where


the statement
list is executed at least one time.

do loop Syntax:

Syntax

do {<statement list>} while (<condition>)

See also
about_Special_Characters
about_Wildcards
about_Language_Modes
Article • 01/19/2023 • 6 minutes to read

Short description
Explains language modes and their effect on PowerShell sessions.

Long description
The language mode of a PowerShell session determines which elements of the
PowerShell language can be used in the session.

PowerShell supports the following language modes:

FullLanguage

RestrictedLanguage
ConstrainedLanguage (introduced in PowerShell 3.0)

NoLanguage

What is a language mode?


The language mode determines the language elements that are permitted in the
session.

The language mode is a property of the session configuration (or "endpoint")


that's
used to create the session. All sessions that use a particular session
configuration have
the language mode of the session configuration.

All PowerShell sessions have a language mode. Sessions are created using the
session
configurations on the target computer. The language mode set in the
session
configuration determines the language mode of the session. To specify
the session
configuration of a PSSession, use the ConfigurationName
parameter of cmdlets that
create a session.

Finding the language mode of a session


You can find the language mode of a FullLanguage or ConstrainedLanguage
session by
getting the value of the LanguageMode property of the session
state.
For example:

PowerShell

$ExecutionContext.SessionState.LanguageMode

ConstrainedLanguage

However, in sessions with RestrictedLanguage and NoLanguage modes, you


can't use the
member-access operator ( . ) to get property values.
Instead, the error message reveals
the language mode.

When you run the $ExecutionContext.SessionState.LanguageMode command in a


RestrictedLanguage session, PowerShell returns the

PropertyReferenceNotSupportedInDataSection and
VariableReferenceNotSupportedInDataSection error messages.

PropertyReferenceNotSupportedInDataSection: Property references aren't


allowed in restricted language mode or a Data section.
VariableReferenceNotSupportedInDataSection: A variable that can't be
referenced in restricted language mode or a Data section is being
referenced.

When you run the $ExecutionContext.SessionState.LanguageMode command in a


NoLanguage session, PowerShell returns the ScriptsNotAllowed error message.

ScriptsNotAllowed: The syntax isn't supported by this runspace. This


might be
because it's in no-language mode.

Finding the language mode of a session


configuration
When a session configuration is created using a session configuration file, the
session
configuration has a LanguageMode property. You can find the
language mode by
getting the value of the LanguageMode property.

PowerShell

(Get-PSSessionConfiguration -Name Test).LanguageMode

FullLanguage

On other session configurations, you can find the language mode indirectly by
finding
the language mode of a session that's created using the session
configuration.
Setting the language mode
The language mode in a PowerShell session can be set through the built-in
$ExecutionContext variable.

PowerShell

$ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage"

However, doing this is only useful for experimenting with language modes.
Language
modes are intended to provide added security to PowerShell sessions
for specific
contexts.

Languages modes are set when you use a system application control policy or
create a
session configuration.

Using a system application control policy


PowerShell automatically runs in ConstrainedLanguage mode when it's running
under a
system application control policy. The application control
policies detected are
AppLocker and Windows Defender Application Control (WDAC)
on Windows platforms.

PowerShell applies other restrictions besides language modes when it detects an


application control policy. For example, there are additional restrictions to
dot-sourcing
and module importing under a policy.

When a PowerShell session is started under a policy, it runs in


ConstrainedLanguage
mode. This mode allows for a usable interactive shell
experience while limiting access to
features and APIs that could be abused by a
malicious actor. Users can run cmdlets and
native commands and have access to
basic language elements. Access to PowerShell,
.NET, and COM APIs is
restricted.

Any script or script-based module executed in this session runs in


ConstrainedLanguage
mode. However, any script or script-based module allowed
by the policy runs in
FullLanguage mode without any constraints. This way, a
system locked down by policy

can have scripts that are trusted by the policy


and run with few constraints.

Using a session configuration


PowerShell remoting optionally supports creating custom session configurations.
You
can set the language mode you want for that custom configuration.
PowerShell Just
Enough Administration (JEA) configurations use NoLanguage
mode to restrict sessions to
command invocations only. With JEA, the remote
session can be restricted to specific
users. The JEA users are limited to
running a defined set of commands and can't directly
access APIs, the file
system, or other system resources.

For more information, see JEA Session configurations and


New-
PSSessionConfigurationFile.

Language mode features and limitations


This section describes the language modes in PowerShell sessions.

FullLanguage mode
The FullLanguage mode permits all language elements in the session.
FullLanguage is
the default language mode for default sessions on all
versions of Windows.

RestrictedLanguage mode
The RestrictedLanguage mode was created for Windows RT, which is no longer
supported. This mode is also used to process modules manifests loaded by
Import-
Module .

In RestrictedLanguage mode, users can run commands (cmdlets, functions, CIM


commands, and workflows), but can't use script blocks.

By default, only the following variables are permitted in


RestrictedLanguage mode:

$PSCulture
$PSUICulture

$True
$False

$Null

Module manifests are loaded in RestrictedLanguage mode and may use these
additional
variables:

$PSScriptRoot
$PSEdition

$EnabledExperimentalFeatures

Only the following comparison operators are permitted:


-eq (equal)

-gt (greater-than)
-lt (less-than)

Assignment statements, property references, and method calls aren't permitted.

ConstrainedLanguage mode
ConstrainedLanguage mode is designed to allow basic language elements such as
loops,

conditionals, string expansion, and access to object properties. The


restrictions prevent
operations that could be abused by a malicious actor.

The ConstrainedLanguage mode permits all cmdlets and a subset of PowerShell


language
elements, but limits the object types that can be used.

The features of ConstrainedLanguage mode are as follows:

All cmdlets in Windows modules are fully functional and have complete access
to
system resources, except as noted.
All elements of the PowerShell scripting language are permitted.
All modules included in Windows can be imported and all commands that the
modules export run in the session.
In PowerShell Workflow, you can write and run script workflows (workflows
written
in the PowerShell language).
XAML-based workflows aren't supported and you can't run XAML in a script
workflow using Invoke-Expression -Language XAML . Also, workflows can't call
other
workflows, although nested workflows are permitted.
The Add-Type cmdlet can load signed assemblies, but it can't load arbitrary
C#
code or Win32 APIs.
The New-Object cmdlet can be used only on allowed types (listed below).
Only allowed types can be used in PowerShell. Other types aren't permitted.
Type
conversion is permitted, but only when the result is an allowed type.
Cmdlet parameters that convert string input to types work only when the
resulting
type is an allowed type.
The ToString() method and the .NET methods of allowed types can be invoked.
Users can get all properties of allowed types. Users can set the values of
properties
only on allowed types.

The following .NET types are permitted in ConstrainedLanguage mode. Users can
get
properties, invoke methods, and convert objects to these types.

Allowed Types:
[adsi]

[adsisearcher]
[Alias]

[AllowEmptyCollection]
[AllowEmptyString]

[AllowNull]

[ArgumentCompleter]
[ArgumentCompletions]

[array]
[bigint]

[bool]

[byte]
[char]

[cimclass]
[cimconverter]

[ciminstance]

[CimSession]
[cimtype]

[CmdletBinding]
[cultureinfo]

[datetime]
[decimal]

[double]

[DscLocalConfigurationManager]
[DscProperty]

[DscResource]
[ExperimentAction]

[Experimental]

[ExperimentalFeature]
[float]

[guid]
[hashtable]

[int]

[int16]
[int32]

[int64]
[ipaddress]

[IPEndpoint]
[long]

[mailaddress]
[Microsoft.PowerShell.Commands.ModuleSpecification]

[NullString]
[Object[]]

[ObjectSecurity]

[ordered]
[OutputType]

[Parameter]
[PhysicalAddress]

[pscredential]

[pscustomobject]
[PSDefaultValue]

[pslistmodifier]
[psobject]

[psprimitivedictionary]

[PSTypeNameAttribute]
[ref]

[regex]
[sbyte]

[securestring]
[semver]

[short]

[single]
[string]

[SupportsWildcards]
[switch]

[timespan]

[uint]
[uint16]

[uint32]
[uint64]

[ulong]

[uri]
[ushort]

[ValidateCount]
[ValidateDrive]

[ValidateLength]
[ValidateNotNull]

[ValidateNotNullOrEmpty]
[ValidatePattern]

[ValidateRange]
[ValidateScript]

[ValidateSet]

[ValidateTrustedData]
[ValidateUserDrive]

[version]
[void]

[WildcardPattern]

[wmi]
[wmiclass]

[wmisearcher]
[X500DistinguishedName]

[X509Certificate]

[xml]

Only the following COM object types are permitted:

Scripting.Dictionary
Scripting.FileSystemObject

VBScript.RegExp

NoLanguage mode
PowerShell NoLanguage mode disables PowerShell scripting language completely.
You
can't run scripts or use variables. You can only run native commands and
cmdlets.

Beginning in PowerShell 7.2, the New-Object cmdlet is disabled in


NoLanguage mode
when system lockdown is configured.

See also
about_Session_Configuration_Files
about_Session_Configurations
about_Line_Editing
Article • 09/19/2022 • 2 minutes to read

Short description
Describes how to edit commands at the PowerShell command prompt.

Long description
The PowerShell console has some useful keyboard shortcuts to help you edit
commands
at the PowerShell command prompt.

Add a line
To add a line, press Shift + Enter .

You can add multiple lines. Each additional line begins with >> , the
continuation
prompt. Press Enter to execute the command.

Move left and right


To move the cursor one character to the left, press the LeftArrow .

To move the cursor one word to the left, press


Ctrl + LeftArrow .

To move the cursor one character to the right, press the RightArrow .

To move the cursor one word to the right, press


Ctrl + RightArrow .

Move to a line's beginning or end


To move to the beginning of a line, press Home .

To move to the end of a line, press End .

If lines were added, press Home or End twice to move to


the beginning or end of the
lines.

Delete characters
To delete the character behind the cursor's position, press
Backspace .

To delete the character at the cursor's position, press Delete .

Delete characters from a line


To delete all the characters from the cursor's position to the end of a line,
press Ctrl +
End .

To delete all the characters from the cursor's position to the beginning of a
line, press
Ctrl + Home .

If lines were added, characters are deleted from the current line and the lines
that were
added.

Insert and overstrike mode


To change to overwrite mode, press Insert . To return to insert mode,
press Insert

again.

Tab completion
To complete a cmdlet name, a parameter, or a path, press the Tab
key. To scroll through
a list of values, press the Tab key again.

See also
about_Command_Syntax
about_Path_Syntax
about_PSReadline
about_Locations
Article • 09/19/2022 • 3 minutes to read

Short description
Describes how to access items from the working location in PowerShell.

Long description
The current working location is the default location to which commands point.
In other
words, this is the location that PowerShell uses if you do not supply
an explicit path to
the item or location that is affected by the command.

7 Note

PowerShell supports multiple runspaces per process. Each runspace has its own
current directory. This is not the same as the current directory of the
process:
[System.Environment]::CurrentDirectory .

In most cases, the current working location is a drive accessed through the
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:

PowerShell

C:\Program Files\Windows PowerShell

As a result, all commands are processed from this location unless another path
is
explicitly provided.

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:

PowerShell

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:

PowerShell

Get-ChildItem C:

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:

PowerShell

Get-ChildItem C:\Windows

In 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:

PowerShell

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:

PowerShell

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.

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:

PowerShell

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:

PowerShell

Get-ChildItem ..\"program files"

In this case, 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\PowerShell , the root of
your drive is C. Therefore, the
following command lists all items in the C:\Windows
directory:

PowerShell

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:

PowerShell

Get-ChildItem system

If you specify a file name rather than a directory name, PowerShell returns
details about
that file (assuming that file is located in the current working
location).

See also
about_Path_Syntax
about_Providers
Set-Location
about_Logging
Article • 09/19/2022 • 3 minutes to read

Short description
PowerShell logs internal operations from the engine, providers, and cmdlets.

Long description
PowerShell logs details about PowerShell operations, such as starting and
stopping the
engine and providers, and executing PowerShell commands.

7 Note

Windows PowerShell versions 3.0, 4.0, 5.0, and 5.1 include EventLog
cmdlets for the
Windows event logs. In those versions, to display the list of
EventLog cmdlets type:
Get-Command -Noun EventLog . For more
information, see the cmdlet documentation

and about_EventLogs for your


version of Windows PowerShell.

Viewing the PowerShell event log entries on


Windows
PowerShell logs can be viewed using the Windows Event Viewer. The event log is
located in the Application and Services Logs group and is named
Microsoft-Windows-
PowerShell . The associated ETW provider GUID is
{A0C1853B-5C40-4B15-8766-
3CF1C58F985A} .

When Script Block Logging is enabled, PowerShell logs the following events to
the
Microsoft-Windows-PowerShell/Operational log:

Field Value

EventId 4104 / 0x1008

Channel Operational

Level Verbose

Opcode Create
Field Value

Task CommandStart

Keyword Runspace

Enabling Script Block Logging


When you enable Script Block Logging, PowerShell records the content of all
script
blocks that it processes. Once enabled, any new PowerShell session logs
this
information.

7 Note

It's recommended to enable Protected Event Logging, as described below, when


using Script Block Logging for anything other than diagnostics purposes.

Script Block Logging can be enabled via Group Policy or a registry setting.

Using Group Policy


To enable automatic transcription, enable the Turn on PowerShell Script Block Logging
feature in Group Policy through Administrative Templates -> Windows Components ->
Windows PowerShell .

Using the Registry


Run the following function:

PowerShell

function Enable-PSScriptBlockLogging

$basePath = 'HKLM:\Software\Policies\Microsoft\Windows' +

'\PowerShell\ScriptBlockLogging'

if(-not (Test-Path $basePath))

$null = New-Item $basePath -Force

Set-ItemProperty $basePath -Name EnableScriptBlockLogging -Value "1"

Protected Event Logging


Increasing the level of logging on a system increases the possibility that
logged content
may contain sensitive data. For example, with script logging
enabled, credentials or
other sensitive data used by a script can be written to
the event log. When a machine
that has logged sensitive data is compromised,
the logs can provide an attacker with
information needed to extend their reach.

To protect this information, Windows 10 introduces Protected Event Logging.


Protected
Event Logging lets participating applications encrypt sensitive data
written to the event
log. Later, you can decrypt and process these logs on a
more secure and centralized log
collector.

Event log content is protected using the IETF Cryptographic Message Syntax
(CMS)
standard. CMS uses public key cryptography. The keys used to encrypt
content and
decrypt content are kept separate.

The public key can be shared widely and isn't sensitive data. Any content
encrypted with
this public key can only be decrypted by the private key. For
more information about
Public Key Cryptography, see
Wikipedia - Public Key Cryptography .

To enable a Protected Event Logging policy, deploy a public key to all machines
that
have event log data to protect. The corresponding private key is used to
post-process
the event logs at a more secure location such as a central event
log collector, or SIEM
aggregator. You can set up SIEM in Azure. For more
information, see Generic SIEM
integration.

Enabling Protected Event Logging via Group Policy


To enable Protected Event Logging, enable the Enable Protected Event Logging
feature
in Group Policy through Administrative Templates -> Windows Components -> Event
Logging . This setting requires an encryption certificate, which you
can provide in one of

several forms:

The content of a base-64 encoded X.509 certificate (for example, as offered


by the
Export option in Certificate Manager).

The thumbprint of a certificate that can be found in the Local Machine


certificate
store (can be deployed by PKI infrastructure).
The full path to a certificate (can be local, or a remote share).
The path to a directory containing a certificate or certificates (can be
local, or a
remote share).
The subject name of a certificate that can be found in the Local Machine
certificate
store (can be deployed by PKI infrastructure).

The resulting certificate must have Document Encryption as an enhanced key


usage
( 1.3.6.1.4.1.311.80.1 ), and either Data Encipherment or Key Encipherment key usages
enabled.

2 Warning

The private key shouldn't be deployed to the machines logging events. It


should be
kept in a secure location where you decrypt the messages.

Decrypting Protected Event Logging messages


The following script will retrieve and decrypt, assuming that you have the
private key:

PowerShell

Get-WinEvent Microsoft-Windows-PowerShell/Operational |

Where-Object Id -eq 4104 | Unprotect-CmsMessage

See also
Generic SIEM integration
PowerShell the Blue Team
about_Logical_Operators
Article • 09/19/2022 • 2 minutes to read

Short description
Describes the operators that connect statements in PowerShell.

Long description
The 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.

PowerShell

($a -gt $b) -and (($a -lt 20) -or ($b -lt 20))

PowerShell supports the following logical operators.

Logical AND ( -and ) - TRUE when both statements are TRUE.

PowerShell

(1 -eq 1) -and (1 -eq 2) # Result is False

Logical OR ( -or ) - TRUE when either statement is TRUE.

PowerShell

(1 -eq 1) -or (1 -eq 2) # Result is True

Logical EXCLUSIVE OR ( -xor ) - TRUE when only one statement is TRUE

PowerShell

(1 -eq 1) -xor (2 -eq 2) # Result is False

Logical not ( -not ) or ( ! ) - Negates the statement that follows.

PowerShell

-not (1 -eq 1) # Result is False

!(1 -eq 1) # Result is False

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:

Syntax

<statement> {-AND | -OR | -XOR} <statement>

{! | -NOT} <statement>

Statements that use the logical operators return Boolean (TRUE or FALSE)
values.

The 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 isn't evaluated. If
the left operand in a statement
that contains the or statement is TRUE, the
right operand isn't evaluated. As a result, you
can use these statements in
the same way that you would use the If statement.

See also
about_Operators
about_Comparison_operators
about_If
Compare-Object
about_Member-Access_Enumeration
Article • 09/19/2022 • 6 minutes to read

Short description
Describes the automatic enumeration of list collection items when using the
member-
access operator.

Long description
Starting in PowerShell 3.0, the member-access enumeration feature improves the
convenience of using the member-access operator ( . ) on list collection
objects. When
you use the member-access operator to access a member that does
not exist on a
collection, PowerShell automatically enumerates the items in the
collection and attempts
to access the specified member on each item.

Member-access enumeration helps you write simpler and shorter code. Instead of
piping a collection object to ForEach-Object or using the ForEach()
intrinsic method to
access members on
each item in the collection, you can use the member-access
operator on the
collection object.

These commands are functionally identical with the last one demonstrating use of
the
member-access operator:

PowerShell

Get-Service -Name event* | ForEach-Object -Process { $_.DisplayName }

(Get-Service -Name event*).ForEach({ $_.DisplayName })

(Get-Service -Name event*).DisplayName

Output

Windows Event Log

COM+ Event System

Windows Event Log

COM+ Event System

Windows Event Log

COM+ Event System

7 Note

You can use the member-access operator to get the values of a property on
items
in a collection but you can't use it to set them directly. For more
information, see
about_Arrays.

When you use the member-access operator on any object and the specified member
exists on that object, the member is invoked. For property members, the operator
returns the value of that property. For method members, the operator calls that
method
on the object.

When you use the member-access operator on a list collection object that doesn't
have
the specified member, PowerShell automatically enumerates the items in
that collection
and uses the member-access operator on each enumerated item.

You can check if an object is a list collection by seeing whether its type
implements the
IList interface:

PowerShell

$List = @('a', 'b')

$Hash = @{ a = 'b' }

$List.GetType().ImplementedInterfaces.Name -contains 'IList'

$Hash.GetType().ImplementedInterfaces.Name -contains 'IList'

Output

True

False

During member-access enumeration for a property, the operator returns the value
of
the property for each item that has that property. If no items have the
specified
property, the operator returns $null .

During member-access enumeration for a method, the operator attempts to call the
method on each item in the collection. If any item in the collection does does
not have
the specified method, the operator returns the MethodNotFound
exception.

2 Warning

During member-access enumeration for a method, the method is called on each


item in the collection. If the method you are calling makes changes, the
changes
are made for every item in the collection. If an error occurs during
enumeration, the
method is called only on the items enumerated before the
error. For additional
safety, consider manually enumerating the items and
explicitly handling any errors.

The following examples detail the behavior of the member-access operator under
all
possible scenarios.

Accessing members of a non-list object


When you use the member-access operator on an object that is not a list collection
and
that has the member, the command returns the value of the property or
output of the
method for that object.

PowerShell

$MyString = 'abc'

$MyString.Length

$MyString.ToUpper()

Output

ABC

When you use the member-access operator on a non-list object that does not have
the
member, the command returns $null if you specify a property or a
MethodNotFound
error if you specify a method.

PowerShell

$MyString = 'abc'

$null -eq $MyString.DoesNotExist

$MyString.DoesNotExist()

Output

True

Method invocation failed because [System.String] does not contain a method

named 'DoesNotExist'.

At line:1 char:1

+ $MyString.DoesNotExist()

+ ~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : InvalidOperation: (:) [], RuntimeException

+ FullyQualifiedErrorId : MethodNotFound

Accessing members of a list collection object


When you use the member-access operator on a collection object that has the
member,
it always returns the property value or method result for the
collection object.

Accessing members that exist on the collection but not


its items
In this example, the specified members exist on the collection but not the
items in it.

PowerShell

[System.Collections.Generic.List[string]]$Collection = @('a', 'b')

$Collection.IsReadOnly

$Collection.Add('c')

$Collection

Output

False

Accessing members that exist on the collection and its


items
For this example, the specified members exist on both the collection and the
items in it.
Compare the results of the commands using the member-access
operator on the
collection to the results from using the member-access operator
on the collection items
in ForEach-Object . On the collection, the operator
returns the property value or method
result for the collection object and not
the items in it.

PowerShell

[System.Collections.Generic.List[string]]$Collection = @('a', 'b', 'c')

$Collection.Count

$Collection | ForEach-Object -Process { $_.Count }

$Collection.ToString()

$Collection | ForEach-Object -Process { $_.ToString() }

Output

System.Collections.Generic.List`1[System.String]

7 Note

Collections that implement the System.Collections.IDictionary interface,


such as
HashTable and OrderedDictionary, have a different behavior.
When you use the
member-access operator on a dictionary that has a key with
the same name as a
property, it returns the key's value instead of the
property's.

You can access the dictionary object's property value with the psbase
intrinsic
member. For example, if the key name
is keys and you want to return the
collection of the HashTable keys, use
this syntax:

PowerShell

$hashtable.PSBase.Keys

Accessing members that exist on all items in a collection


but not itself
When you use the member-access operator on a collection object that does not
have
the member but the items in it do, PowerShell enumerates the items in the
collection
and returns the property value or method result for each item.

PowerShell

[System.Collections.Generic.List[string]]$Collection = @('a', 'b', 'c')

$Collection.Length

$Collection.ToUpper()

Output

Accessing members that exist on neither the collection


nor its items
When you use the member-access operator on a collection object that does not
have
the member and neither do the items in it, the command returns $null if
you specify a
property or a MethodNotFound error if you specify a method.

PowerShell

[System.Collections.Generic.List[string]]$Collection = @('a', 'b', 'c')

$null -eq $Collection.DoesNotExist

$Collection.DoesNotExist()

Output

True

Method invocation failed because [System.String] does not contain a method

named 'DoesNotExist'.

At line:1 char:1

+ $Collection.DoesNotExist()

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : InvalidOperation: (:) [], RuntimeException

+ FullyQualifiedErrorId : MethodNotFound

Because the collection object does not have the member, PowerShell enumerated
the
items in the collection. Notice that the MethodNotFound error specifies
that
System.String does not contain the method instead of
System.Collections.Generic.List.

Accessing methods that exist only on some items in a


collection
When you use the member-access operator to access a method on a collection
object
that does not have the method and only some of the items in the
collection have it, the
command returns a MethodNotFound error for the first
item in the collection that does
not have the method. Even though the method
gets called on some items, the
command only returns the error.

PowerShell

@('a', 1, 'c').ToUpper()

Output

Method invocation failed because [System.Int32] does not contain a method

named 'ToUpper'.

At line:1 char:1

+ @('a', 1, 'c').ToUpper()

+ ~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : InvalidOperation: (:) [], RuntimeException

+ FullyQualifiedErrorId : MethodNotFound

Accessing properties that exist only on some items in a


collection
When you use the member-access operator to access a property on a collection
object
that does not have the property and only some of the items in the
collection have it, the
command returns the property value for each item in the
collection that has the
property.

PowerShell

$CapitalizedProperty = @{

MemberType = 'ScriptProperty'
Name = 'Capitalized'

Value = { $this.ToUpper() }

PassThru = $true

[System.Collections.Generic.List[object]]$MixedCollection = @(

'a'

('b' | Add-Member @CapitalizedProperty)

('c' | Add-Member @CapitalizedProperty)

'd'

$MixedCollection.Capitalized

Output
B

See Also
about_Arrays
about_Intrinsic_Members
about_Methods
about_Operators
about_Properties
about_Methods
Article • 09/19/2022 • 5 minutes to read

Short description
Describes how to use methods to perform actions on objects in PowerShell.

Long description
PowerShell uses objects to represent the items in data stores or the state of
the
computer. For example, FileInfo objects represent the files in file system
drives and
ProcessInfo objects represent the processes on the computer.

Objects have properties, which store data about the object, and methods that
let you
change the object.

A "method" is a set of instructions that specify an action you can perform on


the object.
For example, the FileInfo object includes the CopyTo method
that copies the file that
the FileInfo object represents.

To get the methods of any object, use the Get-Member cmdlet. Use its
MemberType
property with a value of "Method". The following command gets
the methods of
process objects.

PowerShell

Get-Process | Get-Member -MemberType Method

Output

TypeName: System.Diagnostics.Process

Name MemberType Definition

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

BeginErrorReadLine Method System.Void BeginErrorReadLine()

BeginOutputReadLine Method System.Void BeginOutputReadLine()

...

Kill Method System.Void Kill()

Refresh Method System.Void Refresh()

Start Method bool Start()

ToString Method string ToString()

WaitForExit Method bool WaitForExit(int milliseconds), ...

WaitForInputIdle Method bool WaitForInputIdle(int millisecon...

To perform or "invoke" a method of an object, type a dot (.), the method name,
and a
set of parentheses "()". If the method has arguments, place the argument
values inside
the parentheses. The parentheses are required for every method
call, even when there
are no arguments. If the method takes multiple arguments,
they should be separated by
commas.

For example, the following command invokes the Kill method of processes to end
the
Notepad process on the computer.

PowerShell

$notepad = Get-Process notepad

$notepad.Kill()

This example can be shortened by combining the above statements.

PowerShell

(Get-Process Notepad).Kill()

The Get-Process command is enclosed in parentheses to ensure that it


runs before the
Kill method is invoked. The Kill method is then invoked
on the returned Process
object.

Another very useful method is the Replace method of strings. The Replace
method,
replaces text within a string. In the example below, the dot (.) can
be placed immediately
after the end quote of the string.

PowerShell

'this is rocket science'.Replace('rocket', 'rock')

Output

this is rock science

As shown in the previous examples, you can invoke a method on an object that
you get
by using a command, an object in a variable, or anything that
results in an object (like a
string in quotes).

Starting in PowerShell 4.0, method invocation by using dynamic method names is


supported.
Learning about methods
To find definitions of the methods of an object, go to help topic for the
object type and
look for its methods page. For example, the following page
describes the methods of
process objects
System.Diagnostics.Process.

To determine the arguments of a method, review the method definition, which is


like the
syntax diagram of a PowerShell cmdlet.

A method definition might have one or more method signatures, which are like
the
parameter sets of PowerShell cmdlets. The signatures show all of the valid
formats of
commands to invoke the method.

For example, the CopyTo method of the FileInfo class contains the following
two
method signatures:

CopyTo(String destFileName)

CopyTo(String destFileName, Boolean overwrite)

The first method signature takes the destination file name (and a path). The
following
example uses the first CopyTo method to copy the Final.txt file to
the C:\Bin
directory.

PowerShell

(Get-ChildItem c:\final.txt).CopyTo("c:\bin\final.txt")

7 Note

Unlike PowerShell's argument mode, object methods execute in expression


mode,
which is a pass-through to the .NET framework that PowerShell is built
on. In
expression mode bareword arguments (unquoted strings) are not
allowed. You can
see this difference when using a the path as a parameter,
versus the path as an
argument. You can read more about parsing modes in
about_Parsing

The second method signature takes a destination file name and a Boolean value
that
determines whether the destination file should be overwritten, if it
already exists.

The following example uses the second CopyTo method to copy the Final.txt
file to
the C:\Bin directory, and to overwrite existing files.
PowerShell

(Get-ChildItem c:\final.txt).CopyTo("c:\bin\final.txt", $true)

Member-access enumeration
Starting in PowerShell 3.0, when you use the member-access operator ( . ) to
access a
method that does not exist on a list collection, PowerShell
automatically enumerates the
items in the collection and invokes the method on
each item. For more information, see
about_Member-Access_Enumeration.

Examples
The following example runs the Kill method of individual process objects in
a collection
of objects.

The first command starts three instances of the Notepad process. Get-Process
gets all
three instance of the Notepad process and saves them in the $p
variable.

PowerShell

Notepad; Notepad; Notepad

$p = Get-Process Notepad

$p.Count

Output

The next command runs the Kill method on all three processes in the $p
variable. This
command works even though a collection of processes does not
have a Kill method.

PowerShell

$p.Kill()

Get-Process Notepad

The Get-Process command confirms that the Kill method worked.

Output
Get-Process : Cannot find a process with the name "notepad". Verify the proc

ess name and call the cmdlet again.

At line:1 char:12

+ Get-Process <<<< notepad

+ CategoryInfo : ObjectNotFound: (notepad:String) [Get-Process]

, ProcessCommandException

+ FullyQualifiedErrorId : NoProcessFoundForGivenName,Microsoft.PowerShel

l.Commands.GetProcessCommand

This example is functionally equivalent to using the Foreach-Object cmdlet to


run the
method on each object in the collection.

PowerShell

$p | ForEach-Object {$_.Kill()}

ForEach and Where methods


Beginning in PowerShell 4.0, collection filtering using a method syntax is
supported. This
allows use of two new methods when dealing with collections
ForEach and Where .

You can read more about these methods in about_arrays

Calling a specific method when multiple


overloads exist
Consider the following scenario when calling .NET methods. If a method takes an
object
but has an overload via an interface taking a more specific type,
PowerShell chooses the
method that accepts the object unless you explicitly
cast it to that interface.

PowerShell

Add-Type -TypeDefinition @'

// Interface

public interface IFoo {

string Bar(int p);

// Type that implements the interface

public class Foo : IFoo {

// Direct member method named 'Bar'

public string Bar(object p) { return $"object: {p}"; }

// *Explicit* implementation of IFoo's 'Bar' method().

string IFoo.Bar(int p) {

return $"int: {p}";

'@

In this example the less specific object overload of the Bar method was
chosen.

PowerShell

[Foo]::new().Bar(1)

Output

object: 1

In this example we cast the method to the interface IFoo to select the more
specific
overload of the Bar method.

PowerShell

([IFoo] [Foo]::new()).Bar(1)

Output

int: 1

Using .NET methods that take filesystem paths


PowerShell supports multiple runspaces per process. Each runspace has its own
current
directory. This is not the same as the working directory of the
current process:
[System.Environment]::CurrentDirectory .

.NET methods use the process working directory. PowerShell cmdlets use the
Runspace
location. Also, .NET methods only work with native filesystem paths,
not PowerShell Path
objects. To use PowerShell paths with .NET methods, you
must resolve the path to a
filesystem-native path before passing it to the .NET
method.

See also
about_Objects
about_Member-Access_Enumeration
about_Properties
Get-Member
about_Modules
Article • 09/19/2022 • 12 minutes to read

Short description
Explains how to install, import, and use PowerShell modules.

Long description
A module is a package that contains PowerShell members, such as cmdlets,
providers,
functions, workflows, 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 PowerShell sessions and use them just like the built-in
commands.

This topic explains how to use PowerShell modules. For information about how to
write
PowerShell modules, see
Writing a PowerShell Module.

What Is a Module?
A module is a package that contains PowerShell members, such as cmdlets,
providers,
functions, workflows, variables, and aliases. The members of this
package can be
implemented in a PowerShell script, a compiled DLL, or a
combination of both. These
files are usually grouped together in a single
directory. For more information, see
Understanding a Windows PowerShell Module
in the SDK documentation.

Module Auto-Loading
Beginning in PowerShell 3.0, PowerShell imports modules automatically the first
time
that you run any command in an installed module. You can now use the
commands in a
module without any set-up or profile configuration, so there's no
need to manage
modules after you install them on your computer.

The commands in a module are also easier to find. The Get-Command cmdlet now
gets all
commands in all installed modules, even if they are not yet in the
session. You can find a
command and use it without importing needing to import
the module first.
Each of the following examples cause the CimCmdlets module, which contains
Get-
CimInstance , to be imported into your session.

Run the Command

PowerShell

Get-CimInstance Win32_OperatingSystem

Get the Command

PowerShell

Get-Command Get-CimInstance

Get Help for the Command

PowerShell

Get-Help Get-CimInstance

Get-Command commands that include a wildcard character ( * ) are considered to


be for

discovery, not use, and do not import any modules.

Only modules that are stored in the location specified by the PSModulePath
environment variable are automatically imported. Modules in other locations
must be
imported by running the Import-Module cmdlet.

Also, commands that use PowerShell providers do not automatically import a


module.
For example, if you use a command that requires the WSMan: drive, such
as the Get-
PSSessionConfiguration cmdlet, you might need to run the
Import-Module cmdlet to

import the Microsoft.WSMan.Management module that


includes the WSMan: drive.

You can still run the Import-Module command to import a module and use the
$PSModuleAutoloadingPreference variable to enable, disable and configure
automatic
importing of modules. For more information, see
about_Preference_Variables.

How to Use a Module


To use a module, perform the following tasks:

1. Install the module. (This is often done for you.)


2. Find the commands that the module added.
3. 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 use it in PowerShell.

Most modules are installed for you. PowerShell comes with several preinstalled
modules,
sometimes called the core modules. On Windows-based computers, if
features that are
included with the operating system have cmdlets to manage
them, those modules are
preinstalled. When you install a Windows feature, by
using, for example, the Add Roles
and Features Wizard in Server Manager, or the
Turn Windows features on or off dialog
box in Control Panel, any PowerShell
modules that are part of the feature are installed.
Many other modules come in
an installer or Setup program that installs the module.

Use the following command to create a Modules directory for the current
user:

PowerShell

New-Item -Type Directory -Path $HOME\Documents\WindowsPowerShell\Modules

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
PowerShell. In
PowerShell use the Copy-Item cmdlet. For example, to copy the
MyModule folder from
C:\ps-test\MyModule to the Modules directory, type:

PowerShell

Copy-Item -Path C:\ps-test\MyModule -Destination `

$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 and DSC Resource Locations, and PSModulePath
section.

How to Find Installed Modules


To find modules that are installed in a default module location, but not yet
imported
into your session, type:

PowerShell

Get-Module -ListAvailable

To find the modules that have already been imported into your session, at the
PowerShell prompt, type:

PowerShell

Get-Module

For more information about the Get-Module cmdlet, see


Get-Module.

How to Find the Commands in a Module


Use the Get-Command cmdlet to find all available commands. You can use the
parameters
of the Get-Command cmdlet to filter commands such as by module,
name, and noun.

To find all commands in a module, type:

PowerShell

Get-Command -Module <module-name>

For example, to find the commands in the BitsTransfer module, type:

PowerShell

Get-Command -Module BitsTransfer

For more information about the Get-Command cmdlet, see


Get-Command.

How to Get Help for the Commands in a


Module
If the module contains Help files for the commands that it exports, the
Get-Help cmdlet
will display the Help topics. Use the same Get-Help command
format that you would
use to get help for any command in PowerShell.
Beginning in PowerShell 3.0, you can download Help files for a module and
download
updates to the Help files so they are never obsolete.

To get help for a commands in a module, type:

PowerShell

Get-Help <command-name>

To get help online for command in a module, type:

PowerShell

Get-Help <command-name> -Online

To download and install the help files for the commands in a module, type:

PowerShell

Update-Help -Module <module-name>

For more information, see Get-Help


and Update-Help.

How to Import a Module


You might have to import a module or import a module file. Importing is
required when
a module is not installed in the locations specified by the
PSModulePath environment
variable, $env:PSModulePath , or the module
consists of file, such as a .dll or .psm1 file,
instead of typical module that
is delivered as a folder.

You might also choose to import a module so that you can use the parameters of
the
Import-Module command, such as the Prefix parameter, which adds a
distinctive prefix to

the noun names of all imported commands, or the


NoClobber parameter, which
prevents the module from adding commands that
would hide or replace existing
commands in the session.

To import modules, use the Import-Module cmdlet.

To import modules in a PSModulePath location into the current session, use the
following command format.

PowerShell
Import-Module <module-name>

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

PowerShell

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:

PowerShell

Import-Module C:\ps-test\TestCmdlets

To import a module file that is not contained in a module folder, use the fully
qualified
path to the module file in the command.

For example, to add the TestCmdlets.dll module in the C:\ps-test directory to


your
session, type:

PowerShell

Import-Module C:\ps-test\TestCmdlets.dll

For more information about adding modules to your session, see


Import-Module.

How to Import a Module into Every Session


The Import-Module command imports modules into your current PowerShell
session. To
import a module into every PowerShell session that you start, add
the Import-Module
command to your PowerShell profile.

For more information about profiles, see about_Profiles.

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.

PowerShell

Remove-Module <module-name>

For example, the following command removes the BitsTransfer module from the
current
session.

PowerShell

Remove-Module BitsTransfer

Removing a module reverses the operation of importing a module. Removing a


module
does not uninstall the module. For more information, see
Remove-Module.

Module and DSC Resource Locations, and


PSModulePath
The $env:PSModulePath environment variable contains a list of folder
locations that are
searched to find modules and resources.

By default, the effective locations assigned to $env:PSModulePath are:

System-wide locations: $PSHOME\Modules

These folders contain modules that ship with Windows and PowerShell.

DSC resources that are included with PowerShell are stored in the
$PSHOME\Modules\PSDesiredStateConfiguration\DSCResources folder.

User-specific modules: These are modules installed by the user in the user's
scope.
Install-Module has a Scope parameter that allows you to specify
whether the
module is installed for the current user or for all users. For
more information, see
Install-Module.

The user-specific CurrentUser location on Windows is the


PowerShell\Modules
folder located in the Documents location in your
user profile. The specific path of
that location varies by version of Windows
and whether or not you are using folder
redirection. Microsoft OneDrive can
also change the location of your Documents
folder.

By default, on Windows 10 and higher, that location is


$HOME\Documents\PowerShell\Modules . On Linux or Mac, the CurrentUser
location is
$HOME/.local/share/powershell/Modules .

7 Note

You can verify the location of your Documents folder using the
following
command: [Environment]::GetFolderPath('MyDocuments') .

The AllUsers location is $env:PROGRAMFILES\PowerShell\Modules on


Windows. On
Linux or Mac the modules are stored at
/usr/local/share/powershell/Modules .

7 Note

To add or change files in the $env:Windir\System32 directory, start


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:

PowerShell

$Env:PSModulePath

To add a default module location, use the following command format.

PowerShell

$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:


PowerShell

$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 PowerShell profile or use System in Control
Panel to change
the value of the PSModulePath environment variable in the
registry.

Also, to make the change persistent, you can also use the
SetEnvironmentVariable
method of the System.Environment class to add a
Path to the PSModulePath
environment variable.

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 detect name conflicts, use the All parameter of the Get-Command
cmdlet. Beginning in
PowerShell 3.0, Get-Command gets only that commands that
run when you type the
command name. The All parameter gets all commands
with the specific name in the
session.

To prevent name conflicts, use the NoClobber or Prefix parameters of


the Import-
Module cmdlet. The Prefix parameter adds a prefix to the names
of imported commands

so that they are unique in the session. The NoClobber


parameter does not import any
commands that would hide or replace existing
commands in the session.

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.

Module authors can prevent name conflicts by using the DefaultCommandPrefix


property of the module manifest to add a default prefix to all command names.
The
value of the Prefix parameter takes precedence over the value of
DefaultCommandPrefix.

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 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,
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 PowerShell drives. Snap-ins can add only
cmdlets and providers.

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:
PowerShell

Get-Command <cmdlet-name> | Format-List -Property verb,noun,pssnapin,module

For example, to find the source of the Get-Date cmdlet, type:

PowerShell

Get-Command Get-Date | Format-List -Property verb,noun,module

For more information about PowerShell snap-ins, see


about_PSSnapins.

Module-related Warnings and Errors


The commands that a module exports should follow the PowerShell command naming
rules. If the module that you import exports cmdlets or functions that have
unapproved
verbs in their names, the Import-Module cmdlet displays the
following warning message.

WARNING: Some imported command names include unapproved verbs which might
make them less discoverable. Use the Verbose parameter for more detail or
type
Get-Verb to see the list of approved verbs.

This message is only a warning. The complete module is still imported,


including the
non-conforming commands. Although the message is displayed to
module users, the
naming problem should be fixed by the module author.

To suppress the warning message, use the DisableNameChecking parameter of


the
Import-Module cmdlet.

Built-in Modules and Snap-ins


In PowerShell 2.0 and in older-style host programs in PowerShell 3.0 and later,
the core
commands that are installed with PowerShell are packaged in snap-ins
that are added
automatically to every PowerShell session.

Beginning in PowerShell 3.0, for host programs that implement the


InitialSessionState.CreateDefault2 initial session state API the

Microsoft.PowerShell.Core snap-in is added to every session by default. Modules


are
loaded automatically on first-use.
7 Note

Remote sessions, including sessions that are started by using the


New-PSSession
cmdlet, are older-style sessions in which the built-in
commands are packaged in
snap-ins.

The following modules (or snap-ins) are installed with PowerShell.

CimCmdlets
Microsoft.PowerShell.Archive
Microsoft.PowerShell.Core
Microsoft.PowerShell.Diagnostics
Microsoft.PowerShell.Host
Microsoft.PowerShell.Management
Microsoft.PowerShell.ODataUtils
Microsoft.PowerShell.Security
Microsoft.PowerShell.Utility
Microsoft.WSMan.Management
PackageManagement
PowerShellGet
PSDesiredStateConfiguration
PSDiagnostics
PSScheduledJob
PSWorkflow
PSWorkflowUtility
ISE

Logging Module Events


Beginning in PowerShell 3.0, you can record execution events for the cmdlets
and
functions in PowerShell modules and snap-ins by setting the
LogPipelineExecutionDetails property of modules and snap-ins to $True .
You can also
use a Group Policy setting, Turn on Module Logging, to enable
module logging in all
PowerShell sessions. For more information, see
about_EventLogs and
about_Group_Policy_Settings.

See also
about_Command_Precedence
about_Group_Policy_Settings
about_PSSnapins
Get-Command
Get-Help
Get-Module
Import-Module
Remove-Module
about_Module_Manifests
Article • 01/30/2023 • 27 minutes to read

Short description
Describes the settings and practices for writing module manifest files.

Long description
A module manifest is a PowerShell data file ( .psd1 ) containing a hash table.
The keys-
value pairs in the hash table describe the contents and attributes of
the module, define
the prerequisites, and control how the components are
processed.

Manifests aren't required to load a module but they're required to publish a


module to
the PowerShell Gallery. Manifests also enable you to separate your
module's
implementation from how it loads. With a manifest, you can define
requirements,
compatibility, loading order, and more.

When you use New-ModuleManifest without specifying any parameters for the
manifest's
settings it writes a minimal manifest file. The snippet below shows
you this default
output, snipped of commentary and spacing for brevity:

PowerShell

@{

# RootModule = ''

ModuleVersion = '1.0'

# CompatiblePSEditions = @()

GUID = 'e7184b71-2527-469f-a50e-166b612dfb3b'

Author = 'username'

CompanyName = 'Unknown'

Copyright = '(c) 2022 username. All rights reserved.'

# Description = ''

# PowerShellVersion = ''

# PowerShellHostName = ''

# PowerShellHostVersion = ''

# DotNetFrameworkVersion = ''

# CLRVersion = ''

# ProcessorArchitecture = ''

# RequiredModules = @()

# RequiredAssemblies = @()

# ScriptsToProcess = @()

# TypesToProcess = @()

# FormatsToProcess = @()

# NestedModules = @()

FunctionsToExport = @()

CmdletsToExport = @()

VariablesToExport = '*'

AliasesToExport = @()

# DscResourcesToExport = @()

# ModuleList = @()

# FileList = @()

PrivateData = @{

PSData = @{

# Tags = @()

# LicenseUri = ''

# ProjectUri = ''

# IconUri = ''

# ReleaseNotes = ''

} # End of PSData hashtable

} # End of PrivateData hashtable

# HelpInfoURI = ''

# DefaultCommandPrefix = ''

You can use Test-ModuleManifest to validate a module manifest before you


publish your
module. Test-ModuleManifest returns an error if the manifest is
invalid or the module
can't be imported into the current session because the
session doesn't meet
requirements set in the manifest.

Using script code in a module manifest


The values assigned the settings in the manifest file can be expressions that
are
evaluated by PowerShell. This allows you to construct paths and
conditionally assign
values based on variables.

When you import a module using Import-Module , the manifest is evaluated in


Restricted language mode. Restricted mode limits the commands and variables
that

can be used.

Allowed commands

Import-LocalizedData
ConvertFrom-StringData

Write-Host

Out-Host
Join-Path

Allowed variables

$PSScriptRoot
$PSEdition

$EnabledExperimentalFeatures

For more information, see about_Language_Modes.

Manifest settings
The following sections detail every available setting in a module manifest and
how you
can use them. They start with a synopsis of the setting and are
followed by a matrix that
lists:

Input type: The object type that you can specify for this setting in the
manifest.
Required: If this value is Yes , the setting is required both to import
the module
and to publish it to the PowerShell Gallery. If it's No , it's
required for neither. If it's
PowerShell Gallery , it's only required for
publishing to the PowerShell Gallery.
Value if unset: The value this setting has when imported and not
explicitly set.
Accepts wildcards: Whether this setting can take a wildcard value or not.

RootModule
This setting specifies the primary or root file of the module. When the module
is
imported, the members exported by the root module file are imported into the
caller's
session state.

Value

Input Type System.String

Required No

Value if unset $null

Accepts wildcards No

The value must be the path to one of the following:

a script ( .ps1 )
a script module ( .psm1 )
a module manifest ( .psd1 )
an assembly ( .dll )
a cmdlet definition XML file ( .cdxml )
a Windows PowerShell 5.1 Workflow ( .xaml )
The path should be relative to the module manifest.

If a module manifest has no root file was designated in the RootModule key,
the
manifest becomes the primary file for the module, and the module becomes a
manifest
module (ModuleType = Manifest). When RootModule is defined, the
module's type is
determined from the file extension used:

a .ps1 or .psm1 file makes the module type Script


a .psd1 file makes the module type Manifest
a .dll file makes the module type Binary
a .cdxml file makes the module type CIM
a .xaml file makes the module type Workflow

By default, all module members in the RootModule are exported.

 Tip

Module loading speed differs between Binary, Script, and CIM


module types. For
more information, see
PowerShell module authoring considerations

For example, this module's ModuleType is Manifest. The only module


members this
module can export are those defined in the modules specified with
the NestedModules
setting.

PowerShell

@{

RootModule = ''

7 Note

This setting may also be specified in module manifests as


ModuleToProcess. While
that name for this setting is valid, it's best
practice to use RootModule instead.

ModuleVersion
This setting specifies the version of the module. When multiple versions of a
module
exist on a system, the latest version is loaded by default when you run
Import-Module .

Value
Value

Input Type System.String

Required Yes

Value if unset None

Accepts wildcards No

The value of this setting must be convertible to System.Version when you run
Import-
Module .

For example, this manifest declares the module's version as '1.2.3' .

PowerShell

@{

ModuleVersion = '1.2.3'

When you import the module and inspect the Version property, note that it
is a
System.Version object and not a string:

PowerShell

$ExampleModule = Import-Module example.psd1

$ExampleModule.Version

$ExampleModule.Version.GetType().Name

Output

Major Minor Build Revision

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

1 2 3 -1

Version

CompatiblePSEditions
This setting specifies the module's compatible PSEditions.

Value

Input Type System.String[]


Value

Accepted Values Desktop , Core

Required No

Value if unset $null

Accepts wildcards No

If the value of this setting is $null , the module can be imported regardless
of the
PSEdition of the session. You can set it to one or more of the accepted
values.

For information about PSEdition, see:

about_PowerShell_Editions
Modules with compatible PowerShell Editions.

When this setting is defined, the module can only be imported into a session
where the
$PSEdition automatic variable's value is included in the setting.

7 Note

Because the $PSEdition automatic variable was introduced in version 5.1,


older
versions of Windows PowerShell can't load a module that uses the
CompatiblePSEditions setting.

For example, you can import this module manifest in any session:

PowerShell

@{

# CompatiblePSEditions = @()

With the setting specified, this module can only be imported in sessions where
the
$PSEdition automatic variable's value is Core .

PowerShell

@{

CompatiblePSEditions = @('Core')

GUID
This setting specifies a unique identifier for the module. The GUID is used
to distinguish
between modules with the same name.

Value

Input Type System.String

Required No

Value if unset 00000000-0000-0000-0000-000000000000

Accepts wildcards No

The value of this setting must be convertible to System.Guid when you run
Import-
Module .

U Caution

While it's not a required setting, not specifying a GUID in a manifest


has no
benefits and may lead to name collisions for modules.

You can create a new guid to use in your manifest:

PowerShell

New-Guid | Select-Object -ExpandProperty Guid

Output

8456b025-2fa5-4034-ae47-e6305f3917ca

PowerShell

@{

GUID = '8456b025-2fa5-4034-ae47-e6305f3917ca'

If there is another module on the machine with the same name, you can still
import the
one you want by specifying the module's fully qualified name:

PowerShell
Import-Module -FullyQualifiedName @{

ModuleName = 'Example'

GUID = '8456b025-2fa5-4034-ae47-e6305f3917ca'

ModuleVersion = '1.0.0'

Author
This setting identifies the module author.

Value

Input Type System.String

Required PowerShell Gallery

Value if unset $null

Accepts wildcards No

This manifest declares that the module's author is the Contoso Developer
Experience
Team.

PowerShell

@{

Author = 'Contoso Developer Experience Team'

CompanyName
This setting identifies the company or vendor who created the module.

Value

Input Type System.String

Required No

Value if unset $null

Accepts wildcards No

This manifest declares that the module was created by Contoso, Ltd.
PowerShell

@{

CompanyName = 'Contoso, Ltd.'


}

Copyright
This setting specifies a copyright statement for the module.

Value

Input Type System.String

Required No

Value if unset $null

Accepts wildcards No

This manifest declares a copyright statement reserving all rights to Contoso,


Ltd. as of
2022.

PowerShell

@{

Copyright = '(c) 2022 Contoso, Ltd. All rights reserved.'

Description
This setting describes the module at a high level.

Value

Input Type System.String

Required PowerShell Gallery

Value if unset $null

Accepts wildcards No

This manifest includes a short description. You can also use a here-string to
write a
longer or multi-line description.
PowerShell

@{

Description = 'Example commands to show a valid module manifest'

PowerShellVersion
This setting specifies the minimum version of PowerShell this module requires.

Value

Input Type System.String

Required No

Value if unset $null

Accepts wildcards No

The value of this setting must be convertible to System.Version when you run
Import-
Module .

If this setting isn't set, PowerShell doesn't restrict the module's import
based on the
current version.

For example, this manifest declares that the module is compatible with every
version of
PowerShell and Windows PowerShell.

PowerShell

@{

# PowerShellVersion = ''

With PowerShellVersion set to 7.2 , you can only import the module in
PowerShell 7.2
or higher.

PowerShell

@{

PowerShellVersion = '7.2'

PowerShellHostName
This setting specifies the name of the PowerShell host program that the module
requires, such as Windows PowerShell ISE Host or ConsoleHost.

Value

Input Type System.String

Required No

Value if unset $null

Accepts wildcards No

You can find the name of the host for a session with the $Host.Name
statement. For
example, you can see that the host for a remote session is
ServerRemoteHost instead of
ConsoleHost:

PowerShell

$Host.Name

Enter-PSSession -ComputerName localhost

$Host.Name

Output

ConsoleHost

[localhost]: PS C:\Users\username\Documents> $Host.Name

ServerRemoteHost

This module can be imported into any host.

PowerShell

@{

# PowerShellHostName = ''

With PowerShellHostName set to ServerRemoteHost , you can only import the


module in
a remote PowerShell session.

PowerShell

@{

PowerShellHostName = 'ServerRemoteHost'

PowerShellHostVersion
This setting specifies the minimum version of a PowerShell host program that
the
module requires.

Value

Input Type System.String

Required No

Value if unset $null

Accepts wildcards No

The value of this setting must be convertible to System.Version when you run
Import-
Module .

U Caution

While this setting can be used without the PowerShellHostName setting, it


increases the odds of unexpected behavior. Only use this setting when you are
also
using the PowerShellHostName setting.

For example, this manifest's module can be imported from any PowerShell session
running in ConsoleHost, regardless of the host's version.

PowerShell

@{

PowerShellHostName = 'ConsoleHost'

# PowerShellHostVersion = ''

With the PowerShellHostVersion set to 5.1 , you can only import the module
from any
PowerShell session running in ConsoleHost where the host's version
is 5.1 or higher.

PowerShell

@{

PowerShellHostName = 'ConsoleHost'

PowerShellHostVersion = '5.1'
}

DotNetFrameworkVersion
This setting specifies the minimum version of the Microsoft .NET Framework that
the
module requires.

Value

Input Type System.String

Required No

Value if unset $null

Accepts wildcards No

7 Note

This setting is valid for the PowerShell Desktop edition only, such as
Windows
PowerShell 5.1, and only applies to .NET Framework versions lower
than 4.5. This
requirement has no effect for newer versions of PowerShell or
the .NET Framework.

The value of this setting must be convertible to System.Version when you run
Import-
Module .

For example, this manifest declares that its module can be imported in any
PowerShell
or Windows PowerShell session, regardless of the version of the
Microsoft .NET
Framework.

PowerShell

@{

# DotNetFrameworkVersion = ''
}

With DotNetFrameworkVersion set to 4.0 , you can import this module in any
session
of Windows PowerShell where the latest available version of the
Microsoft .NET
Framework is at least 4.0. You can also import it in any
PowerShell session.

PowerShell
@{

DotNetFrameworkVersion = '4.0'

CLRVersion
This setting specifies the minimum version of the Common Language Runtime (CLR)
of
the Microsoft .NET Framework that the module requires.

Value

Input Type System.String

Required No

Value if unset $null

Accepts wildcards No

7 Note

This setting is valid for the PowerShell Desktop edition only, such as
Windows
PowerShell 5.1, and only applies to .NET Framework versions lower
than 4.5. This
requirement has no effect for newer versions of PowerShell or
the .NET Framework.

The value of this setting must be convertible to System.Version when you run
Import-
Module .

For example, this manifest declares that its module can be imported in any
PowerShell
or Windows PowerShell session, regardless of the version of the
Microsoft .NET
Framework's CLR version.

PowerShell

@{

# CLRVersion = ''

With CLRVersion set to 4.0 , you can import this module in any session of
Windows
PowerShell where the latest available version of the CLR is at least
4.0. You can also
import it in any PowerShell session.

PowerShell
@{

CLRVersion = '4.0'

ProcessorArchitecture
This setting specifies the processor architecture that the module requires.

Value

Input Type System.String

Accepted Values None , MSIL , X86 , IA64 , Amd64 , Arm

Required No

Value if unset None

Accepts wildcards No

The value of this setting must be convertible to


System.Reflection.ProcessorArchitecture when you run Import-Module .

For example, this manifest declares that its module can be imported in any
session,
regardless of the system's processor architecture.

PowerShell

@{

# ProcessorArchitecture = ''

With ProcessorArchitecture set to Amd64 , you can only import this module
in a session
running on a machine with a matching architecture.

PowerShell

@{

ProcessorArchitecture = 'Amd64'

RequiredModules
This setting specifies modules that must be in the global session state. If the
required
modules aren't in the global session state, PowerShell imports them.
If the required
modules aren't available, the Import-Module command fails.

Value

Input Type System.String[] , System.Collections.Hashtable[]

Required No

Value if unset $null

Accepts wildcards No

Entries for this setting can be a module name, a full module specification, or
a path to a
module file.

When the value is a path, the path can be fully qualified or relative.

When the value is a name or module specification, PowerShell searches the


PSModulePath for the specified module.

A module specification is a hash table that has the following keys.

ModuleName - Required. Specifies the module name.

GUID - Optional. Specifies the GUID of the module.

It's also Required to specify at least one of the three below keys. The
RequiredVersion key can't be used with the ModuleVersion or
MaximumVersion keys.

You can define an acceptable version range for the


module by specifying the
ModuleVersion and MaximumVersion keys together.

ModuleVersion - Specifies a minimum acceptable version of the module.

RequiredVersion - Specifies an exact, required version of the module.


MaximumVersion - Specifies the maximum acceptable version of the module.

7 Note

RequiredVersion was added in Windows PowerShell 5.0.


MaximumVersion was added

in Windows PowerShell 5.1.

For example, this manifest declares that its module doesn't require any other
modules
for its functionality.

PowerShell
@{

# RequiredModules = @()

This manifest declares that it requires the PSReadLine module. When you run
Import-
Module on this manifest, PowerShell imports the latest version of
PSReadLine that's
available to the session. If no version is available, the
import returns an error.

PowerShell

@{

RequiredModules = @(

'PSReadLine'

 Tip

In PowerShell 2.0, Import-Module doesn't import required modules


automatically. It
only verifies that the required modules are in the global
session state.

This manifest declares that it requires a version of the PSReadLine module


vendored in
it's own module folder. When you run Import-Module on this
manifest, PowerShell
imports the vendored PSReadLine from the specified path.

PowerShell

@{

RequiredModules = @(

'Vendored\PSReadLine\PSReadLine.psd1'

This manifest declares that it specifically requires version 2.0.0 of the


PSReadLine
module. When you run Import-Module on this manifest, PowerShell
imports version 2.0.0
of PSReadLine if it's available. If it's not available,
Import-Module returns an error.

PowerShell

@{

RequiredModules = @(

@{

ModuleName = 'PSReadLine'

RequiredVersion = '2.0.0'

This manifest declares that it requires the PSReadLine module to be imported at


version
2.0.0 or higher.

PowerShell

@{

RequiredModules = @(

@{

ModuleName = 'PSReadLine'

ModuleVersion = '2.0.0'

This manifest declares that it requires the PSReadLine module to be imported at


version
2.0.0 or lower.

PowerShell

@{

RequiredModules = @(

@{

ModuleName = 'PSReadLine'

MaximumVersion = '2.0.0'

This manifest declares that it requires the PSDesiredStateConfiguration module


to be
imported at a version equal to or higher than 2.0.0 but no higher than
2.99.99.

PowerShell

@{

RequiredModules = @(

@{

ModuleName = 'PSDesiredStateConfiguration'

ModuleVersion = '2.0.0'

MaximumVersion = '2.99.99'

RequiredAssemblies
This setting specifies the assembly ( .dll ) files that the module requires.
PowerShell
loads the specified assemblies before updating types or formats,
importing nested
modules, or importing the module file that's specified in the
value of the RootModule
key.

Value

Input Type System.String[]

Required No

Value if unset $null

Accepts wildcards No

Entries for this setting can be the filename of an assembly or the path to one.
List all
required assemblies, even if they're also listed as binary modules in
the NestedModules
setting.

This manifest requires the example.dll assembly. Before loading any


formatting or type
files specified in this manifest, PowerShell loads
example.dll from the Assemblies folder
located in the same directory as the
module manifest.

PowerShell

@{

RequiredAssemblies = @(

'Assemblies\Example.dll'

ScriptsToProcess
This setting 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.

Value

Input Type System.String[]

Required No
Value

Value if unset $null

Accepts wildcards No

To specify scripts that run in the module's session state, use the
NestedModules key.

When you import this manifest, PowerShell runs the Initialize.ps1 in your
current
session.

PowerShell

@{

ScriptsToProcess = @(

'Scripts\Initialize.ps1'

For example, if Initialize.ps1 writes informational messages and sets the


$ExampleState variable:

PowerShell

if ([string]::IsNullOrEmpty($ExampleState)) {

Write-Information "Example not initialized."

Write-Information "Initializing now..."

$ExampleState = 'Initialized'

} else {

Write-Information "Example already initialized."

When you import the module, the script runs, writing those messages and setting
$ExampleState in your session.

PowerShell

$InformationPreference = 'Continue'

"Example State is: $ExampleState"

Import-Module .\example7x.psd1

"Example State is: $ExampleState"

Import-Module .\example7x.psd1 -Force

Output

Example State is:

Example not initialized.

Initializing now...

Example State is: Initialized

Example already initialized.

TypesToProcess
This setting specifies the type files ( .ps1xml ) that run when the module is
imported.

Value

Input Type System.String[]

Required No

Value if unset $null

Accepts wildcards No

When you import the module, PowerShell runs the Update-TypeData cmdlet with
the
specified files. Because type files aren't scoped, they affect all session
states in the
session.

For more information on type files, see about_Types.ps1xml

For example, when you import this manifest, PowerShell loads the types
specified in the
Example.ps1xml file from the Types folder located in the
same directory as the module

manifest.

PowerShell

@{

TypesToProcess = @(

'Types\Example.ps1xml'

FormatsToProcess
This setting specifies the formatting files ( .ps1xml ) that run when the
module is
imported.

Value
Value

Input Type System.String[]

Required No

Value if unset $null

Accepts wildcards No

When you import a module, PowerShell runs the Update-FormatData cmdlet with
the
specified files. Because formatting files aren't scoped, they affect all
session states in the
session.

For more information on type files, see about_Format.ps1xml

For example, when you import this module, PowerShell loads the formats
specified in
the Example.ps1xml file from the Formats folder located in the
same directory as the
module manifest.

PowerShell

@{

FormatsToProcess = @(

'Formats\Example.ps1xml'

NestedModules
This setting specifies script modules ( .psm1 ) and binary modules ( .dll )
that are
imported into the module's session state. You can also specify script
files ( .ps1 ). The
files in this setting run in the order in which they're
listed.

Value

Input Type System.String[] , System.Collections.Hashtable[]

Required No

Value if unset $null

Accepts wildcards No

Entries for this setting can be a module name, a full module specification, or
a path to a
module or script file.
When the value is a path, the path can be fully qualified or relative.

When the value is a module name or specification, PowerShell searches the


PSModulePath for the specified module.

A module specification is a hash table that has the following keys.

ModuleName - Required. Specifies the module name.

GUID - Optional. Specifies the GUID of the module.

It's also Required to specify at least one of the three below keys. The
RequiredVersion key can't be used with the ModuleVersion or
MaximumVersion keys.

You can define an acceptable version range for the


module by specifying the
ModuleVersion and MaximumVersion keys together.

ModuleVersion - Specifies a minimum acceptable version of the module.

RequiredVersion - Specifies an exact, required version of the module.


MaximumVersion - Specifies the maximum acceptable version of the module.

7 Note

RequiredVersion was added in Windows PowerShell 5.0.


MaximumVersion was added

in Windows PowerShell 5.1.

Any items that need to be exported from a nested module must be exported by the
nested module using the Export-ModuleMember cmdlet or be listed in one of the
export
properties:

FunctionsToExport
CmdletsToExport
VariablesToExport
AliasesToExport

Nested modules in the module session state are available to the root module,
but they
aren't returned by a Get-Module command in the caller's session
state.

Scripts ( .ps1 ) that are listed in this setting 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
filename in the ScriptsToProcess
setting.

For example, when you import this manifest, the Helpers.psm1 module is loaded
into
the root module's session state. Any cmdlets declared in the nested module
are
exported unless otherwise restricted.
PowerShell

@{

NestedModules = @(

'Helpers\Helpers.psm1'

FunctionsToExport
This setting specifies the functions that the module exports. You can use this
setting to
restrict the functions that are exported by the module. It can
remove functions from the
list of exported functions, but it can't add
functions to the list.

Value

Input Type System.String[]

Required No

Value if unset $null

Accepts wildcards Yes

You can specify entries in this setting with wildcards. All matching functions
in the list of
exported functions are exported.

 Tip

For performance and discoverability, you should always explicitly list the
functions
you want your module to export in this setting without using any
wildcards.

For example, when you import a module with the setting commented out, all
functions
in the root module and any nested modules are exported.

PowerShell

@{

# FunctionsToExport = @()

This manifest is functionally identical to not specifying the setting at all.

PowerShell
@{

FunctionsToExport = '*'

With FunctionsToExport set as an empty array, when you import this module
no
functions the root module or any nested modules export are available.

PowerShell

@{

FunctionsToExport = @()

7 Note

If you create your module manifest with the New-ModuleManifest command and
don't specify the FunctionsToExport parameter, the created manifest has
this
setting specified as an empty array. Unless you edit the manifest, no
functions from
the module are exported.

With FunctionsToExport set to only include the Get-Example function, when


you import
this module only the Get-Example function is made available, even
if other functions
were exported by the root module or any nested modules.

PowerShell

@{

FunctionsToExport = @(

'Get-Example'

With FunctionsToExport set with a wildcard string, when you import this
module any
function whose name ends with Example is made available, even if
other functions were
exported as module members by the root module or any
nested modules.

PowerShell

@{

FunctionsToExport = @(

'*Example'

CmdletsToExport
This setting specifies the cmdlets that the module exports. You can use this
setting to
restrict the cmdlets that are exported by the module. It can remove
cmdlets from the list
of exported module members, but it can't add cmdlets to
the list.

Value

Input Type System.String[]

Required No

Value if unset $null

Accepts wildcards Yes

You can specify entries in this setting with wildcards. All matching cmdlets
in the list of
exported cmdlets is exported.

 Tip

For performance and discoverability, you should always explicitly list the
cmdlets
you want your module to export in this setting without using any
wildcards.

For example, when you import a module with this setting commented out, all
cmdlets in
the root module and any nested modules are exported.

PowerShell

@{

# CmdletsToExport = @()

This manifest is functionally identical to not specifying the setting at all.

PowerShell

@{

CmdletsToExport = '*'

With CmdletsToExport set as an empty array, when you import this module no
cmdlets
the root module or any nested modules export are available.

PowerShell
@{

CmdletsToExport = @()

7 Note

If you create your module manifest with the New-ModuleManifest command and
don't specify the CmdletsToExport parameter, the created manifest has
this setting
specified as an empty array. Unless you edit the manifest, no
cmdlets from the
module is exported.

With CmdletsToExport set to only include the Get-Example cmdlet, when


you import
this module only the Get-Example cmdlet is made available, even
if other cmdlets were
exported by the root module or any nested modules.

PowerShell

@{

CmdletsToExport = @(

'Get-Example'

With CmdletsToExport set with a wildcard string, when you import this
module any
cmdlet whose name ends with Example is made available, even if
other cmdlets were
exported as module members by the root module or any nested
modules.

PowerShell

@{

CmdletsToExport = @(

'*Example'

VariablesToExport
This setting specifies the variables that the module exports. You can use this
setting to
restrict the variables that are exported by the module. It can
remove variables from the
list of exported module members, but it can't add
variables to the list.

Value
Value

Input Type System.String[]

Required No

Value if unset $null

Accepts wildcards Yes

You can specify entries in this setting with wildcards. All matching variables
in the list of
exported module members is exported.

 Tip

For performance and discoverability, you should always explicitly list the
variables
you want your module to export in this setting without using any
wildcards.

For example, when you import a module with this setting commented out, all
variables
in the root module and any nested modules are exported.

PowerShell

@{

# VariablesToExport = @()

This manifest is functionally identical to not specifying the setting at all.

PowerShell

@{

VariablesToExport = '*'

7 Note

If you create your module manifest with the New-ModuleManifest command and
don't specify the VariablesToExport parameter, the created manifest has
this
setting specified as '*' . Unless you edit the manifest, all variables
from the module
is exported.
With VariablesToExport set as an empty array, when you import this module
no
variables the root module or any nested modules export are available.

PowerShell

@{

VariablesToExport = @()

With VariablesToExport set to only include the SomeExample variable, when


you import
this module only the $SomeExample variable is made available, even
if other variables
were exported by the root module or any nested modules.

PowerShell

@{

VariablesToExport = @(

'SomeExample'

With VariablesToExport set with a wildcard string, when you import this
module any
variable whose name ends with Example is made available, even if
other variables were
exported as module members by the root module or any
nested modules.

PowerShell

@{

VariablesToExport = @(

'*Example'

DscResourcesToExport
This setting specifies the DSC Resources that the module exports. You can use
this
setting to restrict the class-based DSC Resources that are exported by the
module. It can
remove DSC Resources from the list of exported module members,
but it can't add DSC
Resources to the list.

Value

Input Type System.String[]


Value

Required No

Value if unset $null

Accepts wildcards Yes

You can specify entries in this setting with wildcards. All matching
class-based DSC
Resources in the module are exported.

 Tip

For discoverability, you should always explicitly list all the DSC
Resources your
module exports.

For more information on authoring and using DSC Resources, see the
documentation
for DSC.

This manifest exports all the class-based and MOF-based DSC Resources defined
in the
root module and any nested modules.

PowerShell

@{

# DscResourcesToExport = @()

This manifest exports all the MOF-based DSC Resources defined in the root
module and
any nested modules, but only one class-based DSC Resource,
ExampleClassResource .

PowerShell

@{

DscResourcesToExport = @(

'ExampleClassResource'

This manifest exports all the DSC Resources it includes. Even if the MOF-Based
resource
wasn't listed, the module would still export it.

PowerShell
@{

DscResourcesToExport = @(

'ExampleClassResource'

'ExampleMofResourceFirst'
)

ModuleList
This setting is an informational inventory list of the modules included in this
one. This
list doesn't affect the behavior of the module.

Value

Input Type System.String[] , System.Collections.Hashtable[]

Required No

Value if unset $null

Accepts wildcards No

Entries for this setting can be a module name, a full module specification, or
a path to a
module or script file.

When the value is a path, the path can be fully qualified or relative.

When the value is a module name or specification, PowerShell searches the


PSModulePath for the specified module.

A module specification is a hash table that has the following keys.

ModuleName - Required. Specifies the module name.


GUID - Optional. Specifies the GUID of the module.

It's also Required to specify at least one of the three below keys. The
RequiredVersion key can't be used with the ModuleVersion or
MaximumVersion keys.

You can define an acceptable version range for the


module by specifying the
ModuleVersion and MaximumVersion keys together.
ModuleVersion - Specifies a minimum acceptable version of the module.

RequiredVersion - Specifies an exact, required version of the module.


MaximumVersion - Specifies the maximum acceptable version of the module.

7 Note
RequiredVersion was added in Windows PowerShell 5.0.
MaximumVersion was added

in Windows PowerShell 5.1.

This manifest doesn't provide an informational list of the modules it includes.


It may or
may not have modules. Even though this setting isn't specified, any
modules listed in
the RootModule, ScriptsToProcess, or
NestedModules settings still behave normally.

PowerShell

@{

# ModuleList = @()

This manifest declares that the only modules it includes are Example.psm1 and
the
submodules First.psm1 and Second.psm1 in the Submodules folder.

PowerShell

@{

ModuleList = @(

'Example.psm1'

'Submodules\First.psm1'

'Submodules\Second.psm1'

FileList
This setting is an informational inventory list of the files included in this
module. This list
doesn't affect the behavior of the module.

Value

Input Type System.String[]

Required No

Value if unset $null

Accepts wildcards Yes

Entries for this setting should be the relative path to a file from the folder
containing the
module manifest.
When a user calls Get-Module against a manifest with this setting defined,
the FileList
property contains the full path to these files, joining the
module's path with each entry's
relative path.

This manifest doesn't include a list of its files.

PowerShell

@{

# FileList = @()

This manifest declares that the only files it includes are listed in this
setting.

PowerShell

@{

FileList = @(

'Example.psd1'

'Example.psm1'

'Assemblies\Example.dll'

'Scripts\Initialize.ps1'

'Submodules\First.psm1'

'Submodules\Second.psm1'

PrivateData
This setting defines a hash table of data that's available to any commands or
functions
in the root module's scope.

Value

Input Type System.Collections.Hashtable

Required PowerShell Gallery

Value if unset $null

Accepts wildcards No

This setting has two primary effects:

1. Any keys added to this setting are available to functions and cmdlets in the
root
module with $MyInvocation.MyCommand.Module.PrivateData . The hash
table isn't
available in the module scope itself, only in cmdlets you
define in the module.
2. You can add the PSData key with a hash table for metadata needed when
publishing to the PowerShell Gallery. For more information on module
manifests
and the publishing to the PowerShell Gallery, see
Package manifest values that
impact the PowerShell Gallery UI

For example, this manifest defines the PublishedDate key in


PrivateData.

PowerShell

@{

PrivateData = @{

PublishedDate = '2022-06-01'

Cmdlets in the module can access this value with the $MyInvocation variable.

PowerShell

Function Get-Stale {

[CmdletBinding()]

param()

$PublishedDate =
$MyInvocation.MyCommand.Module.PrivateData.PublishedDate

$CurrentDate = Get-Date

try {

$PublishedDate = Get-Date -Date $PublishedDate -ErrorAction Stop

} catch {

# The date was set in the manifest, set to an invalid value, or

# the script module was directly imported without the manifest.

Throw "Unable to determine published date. Check the module


manifest."

if ($CurrentDate -gt $PublishedDate.AddDays(30)) {

Write-Warning "This module version was published more than 30 days


ago."

} else {

$TimeUntilStale = $PublishedDate.AddDays(30) - $CurrentDate

"This module will be stale in $($TimeUntilStale.Days) days"

Once the module is imported, the function uses the value from PrivateData
to
determine when the module was published.
PowerShell

Get-Stale -TestDate '2022-06-15'

Get-Stale -TestDate '2022-08-01'

Output

This module will be stale in 16 days

WARNING: This module version was published more than 30 days ago.

HelpInfoURI
This setting specifies the internet address of the HelpInfo XML file for the
module.

Value

Input Type System.String

Required No

Value if unset $null

Accepts wildcards No

This setting's value must be a Uniform Resource Identifier (URI) that begins
with http or
https.

The HelpInfo XML file supports the Updatable Help feature that was introduced
in
PowerShell 3.0. It contains information about the location of downloadable
help files for
the module and the version numbers of the newest help files for
each supported locale.

For information about Updatable Help, see about_Updatable_Help. For


information
about the HelpInfo XML file, see Supporting Updatable Help.

For example, this module supports updatable help.

PowerShell

@{

HelpInfoUri = 'http://https://go.microsoft.com/fwlink/?LinkID=603'

DefaultCommandPrefix
This setting specifies a prefix that's prepended to the nouns of all commands
in the
module when they're imported into a session. Prefixes help prevent
command name
conflicts in a user's session.

Value

Input Type System.String

Required No

Value if unset $null

Accepts wildcards No

Module users can override this prefix by specifying the Prefix parameter of
the Import-
Module cmdlet.

This setting was introduced in PowerShell 3.0.

When this manifest is imported, any cmdlets imported from this module have
Example
prepended to the noun in their name. For example, Get-Item is
imported as Get-
ExampleItem .

PowerShell

@{

DefaultCommandPrefix = 'Example'

See also
about_PowerShell_Editions
New-ModuleManifest
Test-ModuleManifest
Modules with compatible PowerShell Editions
Package manifest values that impact the PowerShell Gallery UI
PowerShell module authoring considerations
about_Numeric_Literals
Article • 03/02/2023 • 4 minutes to read

Short description
This article describes the syntax and usage of numeric values in PowerShell.

Long description
There are two kinds of numeric literals: integer and real. Both can have type
and
multiplier suffixes.

Integer literals
Integer literals can be written in decimal or hexadecimal notation. Hexadecimal
literals
are prefixed with 0x to distinguish them from decimal numbers.

Integer literals can have a type suffix and a multiplier suffix.

Suffix Meaning

l long data type

kb kilobyte multiplier

mb megabyte multiplier

gb gigabyte multiplier

tb terabyte multiplier

Pb petabyte multiplier

The type of an integer literal is determined by its value, the type suffix, and
the numeric
multiplier suffix.

For an integer literal with no type suffix:

If the value can be represented by type [int] , that is its type.


Otherwise, if the value can be represented by type [long] , that is its
type.
Otherwise, if the value can be represented by type [decimal] , that is its
type.
Otherwise, it is represented by type [double] .
For an integer literal with a type suffix:

If the type suffix is u and the value can be represented by type [int]
then its type
is [int] .
If the type suffix is u and the value can be represented by type [long]
then its
type is [long] .
If its value can be represented by type specified then that is its type.
Otherwise, that literal is malformed.

Real literals
Real literals can only be written in decimal notation. This notation can
include fractional
values following a decimal point and scientific notation
using an exponential part.

The exponential part includes an 'e' followed by an optional sign (+/-) and a
number
representing the exponent. For example, the literal value 1e2 equals
the numeric value
100.

Real literals can have a type suffix and a multiplier suffix.

Suffix Meaning

d decimal data type

kb kilobyte multiplier

mb megabyte multiplier

gb gigabyte multiplier

tb terabyte multiplier

pb petabyte multiplier

There are two kinds of real literal: double and decimal. These are indicated by
the
absence or presence, respectively, of decimal-type suffix. PowerShell does
not support a
literal representation of a [float] value. A double real
literal has type [double] . A
decimal real literal has type [decimal] .
Trailing zeros in the fraction part of a decimal
real literal are significant.

If the value of exponent-part's digits in a [double] real literal is less


than the minimum
supported, the value of that [double] real literal is 0. If
the value of exponent-part's
digits in a [decimal] real literal is less than
the minimum supported, that literal is
malformed. If the value of
exponent-part's digits in a [double] or [decimal] real literal
is greater
than the maximum supported, that literal is malformed.

7 Note

The syntax permits a double real literal to have a long-type suffix.


PowerShell treats
this case as an integer literal whose value is represented
by type [long] . This
feature has been retained for backwards compatibility
with earlier versions of
PowerShell. However, programmers are discouraged
from using integer literals of
this form as they can easily obscure the
literal's actual value. For example, 1.2L has
value 1, 1.2345e1L has
value 12, and 1.2345e-5L has value 0, none of which are
immediately
obvious.

Numeric multipliers
For convenience, integer and real literals can contain a numeric multiplier,
which
indicates one of a set of commonly used powers of 2. The numeric
multiplier can be
written in any combination of upper or lowercase letters.

The multiplier suffixes can be used in combination with the u , ul , and l


type suffixes.

Multiplier examples

PS> 1kb

1024

PS> 1.30Dmb

1363148.80

PS> 0x10Gb

17179869184

PS> 1.4e23tb

1.5393162788864E+35

PS> 0x12Lpb

20266198323167232

Numeric type accelerators


PowerShell supports the following type accelerators:

Accelerator Note Description

[byte] Byte (unsigned)

[sbyte] Byte (signed)

[Int16] 16-bit integer

[UInt16] 16-bit integer (unsigned)

[Int32] 32-bit integer

[int] alias for [int32] 32-bit integer

[UInt32] 32-bit integer (unsigned)

[Int64] 64-bit integer

[long] alias for [int64] 64-bit integer

[UInt64] 64-bit integer (unsigned)

[bigint] See BigInteger Struct

[single] Single precision floating point

[float] alias for [single] Single precision floating point

[double] Double precision floating point

[decimal] 128-bit floating point

Working with other numeric types


To work with any other numeric types you must use type accelerators, which is
not
without some problems. For example, high integer values are always parsed
as double
before being cast to any other type.

PS> [bigint]111111111111111111111111111111111111111111111111111111

111111111111111100905595216014112456735339620444667904

The value is parsed as a double first, losing precision in the higher ranges.
To avoid this
problem, enter values as strings and then convert them:
PS> [bigint]'111111111111111111111111111111111111111111111111111111'

111111111111111111111111111111111111111111111111111111

Examples
The following table contains several examples of numeric literals and lists
their type and
value:

Number Type Value

100 Int32 100

100D Decimal 100

100l Int64 100

1e2 Double 100

1.e2 Double 100

0x1e2 Int32 482

0x1e2L Int64 482

0x1e2D Int32 7725

482D Decimal 482

482gb Int64 517543559168

0x1e2lgb Int64 517543559168

Numeric type conversion


When strings are converted to numbers, additional hexadecimal format indicators are
supported. Those additional formats are not recognized as literals.

PowerShell

[int] '0xF' -eq 0xF

[int] '&hF' -eq 0xF

[int] '#F' -eq 0xF

Commands that look like numeric literals


Any command that looks like a numeric literal must be executed using the the
call
operator ( & ), otherwise it is interpreted as a number of the associated
type.

Access properties and methods of numeric objects


To access a member of a numeric literal, there are cases when you need to
enclose the
literal in parentheses.

The literal does not have a decimal point


The literal does not have any digits following the decimal point
The literal does not have a suffix

For example, the following example fails:

PS> 2.GetType().Name

At line:1 char:11

+ 2.GetType().Name

+ ~

An expression was expected after '('.

+ CategoryInfo : ParserError: (:) [],


ParentContainsErrorRecordException

+ FullyQualifiedErrorId : ExpectedExpression

The following examples work:

PS> 2L.GetType().Name

Int64

PS> 1.234.GetType().Name

Double

PS> (2).GetType().Name

Int32

The first two examples work without enclosing the literal value in parentheses
because
the PowerShell parser can determine where the numeric literal ends and
the GetType
method starts.
about_Objects
Article • 09/19/2022 • 2 minutes to read

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. An object is
made up of three types of data: the
objects type, its methods, and its properties.

Types, Methods, and Properties


The object type tells what kind of object it is. For example, an object
that represents a
file is a FileInfo object.

The object methods are actions that you can perform on the object.
For example,
FileInfo objects have a CopyTo method that you can use
to copy the file.

Object properties store information about the object. For example,


FileInfo objects have
a LastWriteTime property that stores the date
and time that the file was most recently
accessed.

When working with objects, you can use their methods and properties
in commands to
take action and manage data.

You can discover an objects properties and methods using


Get-Member or the psobject
intrinsic member.

Objects in Pipelines
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:

PowerShell

Get-ChildItem C: | where { $_.PsIsContainer -eq $false } | Format-List

The first command Get-ChildItem C: returns a file or directory object


for each item in
the root directory of the file system. The file and
directory objects are passed down the
pipeline to the second command.

The second command where { $_.PsIsContainer -eq $false } uses the


PsIsContainer
property of all file system objects to select only
files, which have a value of False
( $false ) in their PsIsContainer
property. Folders, which are containers and, thus, have a
value of
True ( $true ) in their PsIsContainer property, are not selected.

The second command passes only the file objects to the third command
Format-List ,
which displays the file objects in a list.

See also
about_Methods
about_Object_Creation
about_Pipelines
about_Properties
Get-Member
about_Object_Creation
Article • 12/05/2022 • 5 minutes to read

Short description
Explains how to create objects in PowerShell.

Long description
You can create objects in PowerShell and use the objects that you create in
commands
and scripts.

There are many ways to create objects, this list is not definitive:

New-Object: Creates an instance of a .NET Framework object or COM


object.
Import-Csv / ConvertFrom-CSV: Creates custom objects
(PSCustomObject) from
the items defined as character separated values.
ConvertFrom-Json: Creates custom objects defined in JavaScript Object
Notation
(JSON).
ConvertFrom-String: Built on top of FlashExtract ,
ConvertFrom-String creates
custom objects from structured string data. This
topic will demonstrate and discuss
each of these methods.
ConvertFrom-StringData: Creates custom objects defined as key value
pairs.
Add-Type: Allows you to define a class in your PowerShell session that
you can
instantiate with New-Object .
New-Module: The AsCustomObject parameter creates a custom object
you define
using script block.
Add-Member: Adds properties to existing objects. You can use
Add-Member to
create a custom object out of a simple type, like
[System.Int32] .
Select-Object: Selects properties on an object. You can use
Select-Object to create
custom and calculated properties on an already
instantiated object.

The following additional methods are covered in this article:

By calling a type's constructor using a static new() method


By typecasting hash tables of property names and property values

Static new() method


All .NET types have a new() method that allows you to construct instances
more easily.
You can also see all the available constructors for a given type.

To see the constructors for a type, specify the new method name after the
type name
and press <ENTER> .

PowerShell

[System.Uri]::new

Output

OverloadDefinitions

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

uri new(string uriString)

uri new(string uriString, bool dontEscape)

uri new(uri baseUri, string relativeUri, bool dontEscape)

uri new(string uriString, System.UriKind uriKind)

uri new(uri baseUri, string relativeUri)

uri new(uri baseUri, uri relativeUri)

Now, you can create a System.Uri by specifying the appropriate constructor.

PowerShell

[System.Uri]::new("https://www.bing.com")

Output

AbsolutePath : /

AbsoluteUri : https://www.bing.com/

LocalPath : /

Authority : www.bing.com

...

You can use the following sample to determine what .NET types are currently
loaded for
you to instantiate.

PowerShell

[AppDomain]::CurrentDomain.GetAssemblies() |

ForEach-Object {

$_.GetExportedTypes() |

ForEach-Object { $_.FullName }

Objects created using the new() method may not have the same properties as
objects
of the same type that are created by PowerShell cmdlets. PowerShell
cmdlets, providers,
and Extended Type System can add extra properties to the
instance.

For example, the FileSystem provider in PowerShell adds six NoteProperty


values to the
DirectoryInfo object returned by Get-Item .

PowerShell

$PSDirInfo = Get-Item /

$PSDirInfo | Get-Member | Group-Object MemberType | Select-Object Count,


Name

Output

Count Name

----- ----

4 CodeProperty

13 Property

6 NoteProperty

1 ScriptProperty

18 Method

When you create a DirectoryInfo object directly, it does not have those six
NoteProperty values.

PowerShell

$NewDirInfo = [System.IO.DirectoryInfo]::new('/')

$NewDirInfo | Get-Member | Group-Object MemberType | Select-Object Count,


Name

Output

Count Name

----- ----

4 CodeProperty

13 Property

1 ScriptProperty

18 Method

For more information about the Extended Type System, see


about_Types.ps1xml.

This feature was added in PowerShell 5.0


Create objects from hash tables
You can create an object from a hash table of properties and property values.

The syntax is as follows:

[<class-name>]@{

<property-name>=<property-value>

<property-name>=<property-value>

This method works only for classes that have a parameterless constructor. The
object
properties must be public and settable.

This feature was added in PowerShell version 3.0

Create custom objects from hash tables


Custom objects are very useful and are easy to create using the hash table
method. The
PSCustomObject class is designed specifically for this purpose.

Custom objects are an excellent way to return customized output from a function
or
script. This is more useful than returning formatted output that cannot be
reformatted
or piped to other commands.

The commands in the Test-Object function set some variable values and then
use
those values to create a custom object. You can see this object in use in
the example
section of the Update-Help cmdlet help topic.

PowerShell

function Test-Object {

$ModuleName = "PSScheduledJob"

$HelpCulture = "en-us"

$HelpVersion = "3.1.0.0"

[PSCustomObject]@{

"ModuleName"=$ModuleName

"UICulture"=$HelpCulture

"Version"=$HelpVersion

$ModuleName = "PSWorkflow"

$HelpCulture = "en-us"

$HelpVersion = "3.0.0.0"

[PSCustomObject]@{

"ModuleName"=$ModuleName

"UICulture"=$HelpCulture

"Version"=$HelpVersion

Test-Object

The output of this function is a collection of custom objects formatted as a


table by
default.

Output

ModuleName UICulture Version

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

PSScheduledJob en-us 3.1.0.0

PSWorkflow en-us 3.0.0.0

Users can manage the properties of the custom objects just as they do with
standard
objects.

PowerShell

(Test-Object).ModuleName

Output

PSScheduledJob

PSWorkflow

PSObject type objects maintain the list of members in the order that the
members were
added to the object. Even though Hashtable objects don't
guarantee the order of the
key-value pairs, casting a literal hashtable to
[pscustomobject] maintains the order.

The hashtable must be a literal. Tf you wrap the hashtable in parentheses or if


you cast a
variable containing a hashtable, there is no guarantee that the
order is preserved.

PowerShell

$hash = @{

Name = "Server30"

System = "Server Core"

PSVersion = "4.0"

$Asset = [pscustomobject]$hash

$Asset

Output

PSVersion Name System

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

4.0 Server30 Server Core

Create non-custom objects from hash tables


You can also use hash tables to create objects for non-custom classes. When you
create
an object for a non-custom class, the namespace-qualified type name is
required,
although you may omit any initial System namespace component.

For example, the following command creates a session option object.

PowerShell

[System.Management.Automation.Remoting.PSSessionOption]@{

IdleTimeout=43200000

SkipCnCheck=$True

The requirements of the hash table feature, especially the parameterless


constructor
requirement, eliminate many existing classes. However, most
PowerShell option classes
are designed to work with this feature, as well as
other very useful classes, such as the
ProcessStartInfo class.

PowerShell

[System.Diagnostics.ProcessStartInfo]@{

CreateNoWindow="$true"

Verb="run as"

Output

Arguments :

ArgumentList : {}

CreateNoWindow : True

EnvironmentVariables : {OneDriveConsumer, PROCESSOR_ARCHITECTURE,

CommonProgramFiles(x86), APPDATA...}

Environment : {[OneDriveConsumer, C:\Users\user1\OneDrive],

[PROCESSOR_ARCHITECTURE, AMD64],

[CommonProgramFiles(x86),

C:\Program Files (x86)\Common Files],

[APPDATA, C:\Users\user1\AppData\Roaming]...}

RedirectStandardInput : False

RedirectStandardOutput : False

RedirectStandardError : False

...

You can also use the hash table feature when setting parameter values. For
example, the
value of the SessionOption parameter of the New-PSSession .
cmdlet can be a hash table.

PowerShell

New-PSSession -ComputerName Server01 -SessionOption @{

IdleTimeout=43200000

SkipCnCheck=$True

Register-ScheduledJob Name Test -FilePath .\Get-Inventory.ps1 -Trigger @{

Frequency="Daily"

At="15:00"

Generic objects
You can also create generic objects in PowerShell. Generics are classes,
structures,
interfaces, and methods that have placeholders (type parameters)
for one or more of
the types that they store or use.

The following example creates a Dictionary object.

PowerShell

$dict = New-Object 'System.Collections.Generic.Dictionary[String,Int]'

$dict.Add("One", 1)

$dict

Output

Key Value

--- -----

One 1

For more information on Generics, see Generics in .NET.

See also
about_Methods
about_Objects
about_Pipelines
about_Properties
about_Types.ps1xml
about_Operators
Article • 03/31/2023 • 11 minutes to read

Short description
Describes the operators that are supported by PowerShell.

Long description
An operator is a language element that you can use in a command or expression.
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.

The addition operator concatenates elements. The multiplication operator


returns the
specified number of copies of each element. You can use arithmetic
operators on any
.NET type that implements them, such as: Int , String ,
DateTime , Hashtable , and Arrays.

Bitwise operators ( -band , -bor , -bxor , -bnot , -shl , -shr )


manipulate the bit patterns in
values.

For more information, see about_Arithmetic_Operators.

Assignment Operators
Use assignment operators ( = , += , -= , *= , /= , %= ) to assign, change,
or append values
to variables. You can combine arithmetic operators with
assignment to assign the result
of the arithmetic operation to a 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're equal.

The comparison operators also include operators that find or replace patterns
in text.
The ( -match , -notmatch , -replace ) operators use regular
expressions, and ( -like , -
notlike ) use wildcards * .

Containment comparison operators determine whether a test value appears in a


reference set ( -in , -notin , -contains , -notcontains ).

Type comparison operators ( -is , -isnot ) determine whether an object is of a


given
type.

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 the unary ++ and -- operators to increment or decrement values and
- for
negation. For example, to increment the variable $a from 9 to
10 , you type $a++ .

For more information, see about_Arithmetic_Operators.

Special Operators
Special operators have specific use-cases that don't fit into any other
operator group.
For example, special operators allow you to run commands,
change a value's data type,
or retrieve elements from an array.

Grouping operator ( )
As in other languages, (...) serves to override operator precedence in
expressions. For
example: (1 + 2) / 3

However, in PowerShell, there are additional behaviors.

(...) allows you to let output from a command participate in an expression.


For

example:

PowerShell

PS> (Get-Item *.txt).Count -gt 10

True

7 Note

Wrapping a command in parentheses causes the automatic variable $? to be


set to
$true , even when the enclosed command itself set $? to $false .
For example,
(Get-Item /Nosuch); $? unexpectedly yields True. For
more information about $? ,

see
about_Automatic_Variables.
Grouping assignment statements
Ungrouped assignment statements don't output values. When grouping an
assignment
statement, the value of the assigned variable is passed through
and can be used in larger
expressions. For example:

PowerShell

PS> ($var = 1 + 2)

PS> ($var = 1 + 2) -eq 3

True

Wrapping the statement in parentheses turns it into an expression that outputs


the
value of $var .

This behavior applies to all the assignment operators, including compound


operators
like += , and the increment ( ++ ) and decrement ( -- ) operators.
However, the order of
operation for increment and decrement depends on their
position.

PowerShell

PS> $i = 0

PS> (++$i) # prefix

PS> $i = 0

PS> ($i++) # postfix

PS> $i

In the prefix case, the value of $i is incremented before being output. In


the postfix
case, the value of $i is incremented after being output.

You can also use this technique In the context of a conditional statement, such
as the if
statement.

PowerShell

if ($textFiles = Get-ChildItem *.txt) {

$textFiles.Count

In this example, if no files match, the Get-ChildItem command returns nothing


and
assigns nothing to $textFiles , which is considered $false in a boolean
context. If one
or more FileInfo objects are assigned to $textFiles , the
conditional evaluates to $true .
You can work with the value of $textFiles
in the body of the if statement.

7 Note

While this technique is convenient and concise, it can lead to confusion


between
the assignment operator ( = ) and the equality-comparison operator
( -eq ).

Piping grouped expressions


When used as the first segment of a pipeline, wrapping a command or expression
in
parentheses invariably causes enumeration of the expression result. If the
parentheses
wrap a command, it's run to completion with all output collected
in memory before the
results are sent through the pipeline.

Subexpression operator $( )
Returns the result of one or more statements. For a single result, returns a
scalar. For
multiple results, returns an array. Use this when you want to use
an expression within
another expression. For example, to embed the results of
command in a string
expression.

PowerShell

PS> "Today is $(Get-Date)"

Today is 12/02/2019 13:15:20

PS> "Folder list: $((dir c:\ -dir).Name -join ', ')"

Folder list: Program Files, Program Files (x86), Users, Windows

Array subexpression operator @( )


Returns the result of one or more statements as an array. The result is always
an array of
0 or more objects.

PowerShell

PS> $list = @(Get-Process | Select-Object -First 10; Get-Service | Select-


Object -First 10 )

PS> $list.GetType()

IsPublic IsSerial Name BaseType

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

True True Object[] System.Array

PS> $list.Count

20

PS> $list = @(Get-Service | Where-Object Status -eq Starting )

PS> $list.GetType()

IsPublic IsSerial Name BaseType

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

True True Object[] System.Array

PS> $list.Count

Hash table literal syntax @{}


Similar to the array subexpression, this syntax is used to declare a hash
table. For more
information, see about_Hash_Tables.

Call operator &


Runs a command, script, or script block. The call operator, also known as the
"invocation
operator", lets you run commands that are stored in variables and
represented by
strings or script blocks. The call operator executes in a child
scope. For more about
scopes, see about_Scopes.

This example stores a command in a string and executes it using the call
operator.

PS> $c = "get-executionpolicy"

PS> $c

get-executionpolicy

PS> & $c

AllSigned

The call operator doesn't parse strings. This means that you can't use
command
parameters within a string when you use the call operator.

PS> $c = "Get-Service -Name Spooler"

PS> $c

Get-Service -Name Spooler

PS> & $c

& : The term 'Get-Service -Name Spooler' 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.

At line:1 char:2

+ & $c

+ ~~

+ CategoryInfo : ObjectNotFound: (Get-Service -Name


Spooler:String) [], CommandNotFoundException

+ FullyQualifiedErrorId : CommandNotFoundException

The Invoke-Expression cmdlet can execute code that causes parsing errors
when using
the call operator.

PS> & "1+1"

& : The term '1+1' 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.

At line:1 char:2

+ & "1+1"

+ ~~~~~

+ CategoryInfo : ObjectNotFound: (1+1:String) [],


CommandNotFoundException

+ FullyQualifiedErrorId : CommandNotFoundException

PS> Invoke-Expression "1+1"

You can execute a script using its filename. A script file must have a .ps1
file extension
to be executable. Files that have spaces in their path must be
enclosed in quotes. If you
try to execute the quoted path, PowerShell displays
the contents of the quoted string in
stead of running the script. The call
operator allows you to execute the contents of the
string containing the
filename.

PS C:\Scripts> Get-ChildItem

Directory: C:\Scripts

Mode LastWriteTime Length Name

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

-a---- 8/28/2018 1:36 PM 58 script name with spaces.ps1

PS C:\Scripts> ".\script name with spaces.ps1"

.\script name with spaces.ps1

PS C:\Scripts> & ".\script name with spaces.ps1"

Hello World!

For more about script blocks, see about_Script_Blocks.

Cast operator [ ]
Converts or limits objects to the specified type. If the objects can't be
converted,
PowerShell generates an error.

PowerShell

[DateTime] '2/20/88' - [DateTime] '1/20/88' -eq [TimeSpan] '31'

A cast can also be performed when a variable is assigned to using


cast notation.

Comma operator ,
As a binary operator, the comma creates an array or appends to the array being
created.
In expression mode, as a unary operator, the comma creates an array
with just one
member. Place the comma before the member.

PowerShell

$myArray = 1,2,3

$SingleArray = ,1

Write-Output (,1)

Since Write-Output expects an argument, you must put the expression in


parentheses.

Dot sourcing operator .


Runs a script in the current scope so that any functions, aliases, and
variables that the
script creates are added to the current scope, overriding
existing ones. Parameters
declared by the script become variables. Parameters
for which no value has been given
become variables with no value. However, the
automatic variable $args is preserved.

PowerShell

. c:\scripts\sample.ps1 1 2 -Also:3

7 Note
The dot sourcing operator is followed by a space. Use the space to
distinguish the
dot from the dot ( . ) symbol that represents the current
directory.

In the following example, the Sample.ps1 script in the current directory is


run in the
current scope.

PowerShell

. .\sample.ps1

Format operator -f
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.

PowerShell

"{0} {1,-10} {2:N}" -f 1,"hello",[math]::pi

Output

1 hello 3.14

You can zero-pad a numeric value with the "0" custom specifier. The
number of zeroes
following the : indicates the maximum width to pad the
formatted string to.

PowerShell

"{0:00} {1:000} {2:000000}" -f 7, 24, 365

Output

07 024 000365

If you need to keep the curly braces ( {} ) in the formatted string, you can
escape them
by doubling the curly braces.

PowerShell

"{0} vs. {{0}}" -f 'foo'

Output

foo vs. {0}

For more information, see the String.Format method and


Composite Formatting.

Index operator [ ]
Selects objects from indexed collections, such as arrays and hash tables. Array
indexes
are zero-based, so the first object is indexed as [0] . You can also
use negative indexes
to get the last values. Hash tables are indexed by key
value.

Given a list of indices, the index operator returns a list of members


corresponding to
those indices.

PS> $a = 1, 2, 3

PS> $a[0]

PS> $a[-1]

PS> $a[2, 1, 0]

PowerShell

(Get-HotFix | Sort-Object installedOn)[-1]

PowerShell

$h = @{key="value"; name="PowerShell"; version="2.0"}

$h["name"]

Output

PowerShell

PowerShell

$x = [xml]"<doc><intro>Once upon a time...</intro></doc>"

$x["doc"]

Output

intro

-----

Once upon a time...

When an object isn't an indexed collection, using the index operator to access
the first
element returns the object itself. Index values beyond the first
element return $null .

PS> (2)[0]

PS> (2)[-1]

PS> (2)[1] -eq $null

True

PS> (2)[0,0] -eq $null

True

Pipeline operator |
Sends ("pipes") the output of the command that precedes it to the command that
follows it. When the output includes more than one object (a "collection"), the
pipeline
operator sends the objects one at a time.

PowerShell

Get-Process | Get-Member

Get-Service | Where-Object {$_.StartType -eq 'Automatic'}

Range operator ..
The range operator can be used to represent an array of sequential integers.
The values
joined by the range operator define the start and end values of the
range.

PowerShell

1..10

$max = 10

foreach ($a in 1..$max) {Write-Host $a}

You can also create ranges in reverse order.


PowerShell

10..1

5..-5 | ForEach-Object {Write-Output $_}

The start and end values of the range can be any pair of expressions that
evaluate to an
integer. For example, you could use the members of an
enumeration for your start and
end values.

PowerShell

PS> enum Food {

Apple

Banana = 3

Kiwi = 10

PS> [Food]::Apple..[Food]::Kiwi

10

) Important

The resulting range isn't limited to the values of the enumeration. Instead
it
represents the range of values between the two values provided. You can't
use the
range operator to reliably represent the members of an enumeration.

Member-access operator .
Accesses the properties and methods of an object. The member name may be an
expression.

PowerShell

$myProcess.peakWorkingSet

(Get-Process PowerShell).kill()

'OS', 'Platform' | Foreach-Object { $PSVersionTable. $_ }

Starting PowerShell 3.0, when you use the operator on a list collection object
that
doesn't have the member, PowerShell automatically enumerates the items in
that
collection and uses the operator on each of them. For more information,
see
about_Member-Access_Enumeration.

Static member operator ::


Calls the static properties 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. The member name may be an expression.

PowerShell

[datetime]::Now

'MinValue', 'MaxValue' | Foreach-Object { [int]:: $_ }

See also
about_Arithmetic_Operators
about_Assignment_Operators
about_Comparison_Operators
about_Logical_Operators
about_Operator_Precedence
about_Member-Access_Enumeration
about_Type_Operators
about_Split
about_Join
about_Redirection
about_Operator_Precedence
Article • 09/19/2022 • 3 minutes to read

Short description
Lists the PowerShell operators in precedence order.

Long description
PowerShell operators let you construct simple, but powerful expressions. This
topic lists
the operators in precedence order. Precedence order is the order in
which PowerShell
evaluates the operators when multiple operators appear in the
same expression.

When operators have equal precedence, PowerShell evaluates them from left to
right as
they appear within the expression. The exceptions are the assignment
operators, the
cast operators, and the negation operators ( ! , -not ,
-bnot ), which are evaluated from
right to left.

You can use enclosures, such as parentheses, to override the standard


precedence order
and force PowerShell to evaluate the enclosed part of an
expression before an
unenclosed part.

In the following list, operators are listed in the order that they are
evaluated. Operators
on the same line, or in the same group, have equal
precedence.

The Operator column lists the operators. The Reference column lists the
PowerShell Help
topic in which the operator is described. To display the topic,
type get-help <topic-
name> .

OPERATOR REFERENCE

$() @() () @{} about_Operators

. ?. (member access) about_Operators

:: (static) about_Operators

[0] ?[0] (index operator) about_Operators

[int] (cast operators) about_Operators

-split (unary) about_Split


OPERATOR REFERENCE

-join (unary) about_Join

, (comma operator) about_Operators

++ -- about_Assignment_Operators

! -not about_Logical_Operators

.. (range operator) about_Operators

-f (format operator) about_Operators

- (unary/negative) about_Arithmetic_Operators

* / % about_Arithmetic_Operators

+ - about_Arithmetic_Operators

The following group of operators have equal precedence. Their case-sensitive


and
explicitly case-insensitive variants have the same precedence.

OPERATOR REFERENCE

-split (binary) about_Split

-join (binary) about_Join

-is -isnot -as about_Type_Operators

-eq -ne -gt -ge -lt -le about_Comparison_Operators

-like -notlike about_Comparison_Operators

-match -notmatch about_Comparison_Operators

-in -notIn about_Comparison_Operators

-contains -notContains about_Comparison_Operators

-replace about_Comparison_Operators

The list resumes here with the following operators in precedence


order:

OPERATOR REFERENCE

-band -bnot -bor -bxor -shr -shl about_Arithmetic_Operators

-and -or -xor about_Logical_Operators


The following items are not true operators. They are part of PowerShell's
command
syntax, not expression syntax. Assignment is always the last action
that happens.

SYNTAX REFERENCE

. (dot-source) about_Operators

& (call) about_Operators

? <if-true> : <if-false> (Ternary operator) about_Operators

?? (null-coalese operator) about_Operators

| (pipeline operator) about_Operators

> >> 2> 2>> 2>&1 about_Redirection

&& || (pipeline chain operators) about_Operators

= += -= *= /= %= ??= about_Assignment_Operators

Examples
The following two commands show the arithmetic operators and the effect of
using
parentheses to force PowerShell to evaluate the enclosed part of the
expression first.

PowerShell

PS> 2 + 3 * 4
14

PS> (2 + 3) * 4

20

The following example gets the read-only text files from the local directory
and saves
them in the $read_only variable.

PowerShell

$read_only = Get-ChildItem *.txt | Where-Object {$_.isReadOnly}

It is equivalent to the following example.

PowerShell

$read_only = ( Get-ChildItem *.txt | Where-Object {$_.isReadOnly} )

Because the pipeline operator ( | ) has a higher precedence than the assignment
operator ( = ), the files that the Get-ChildItem cmdlet gets are sent to the
Where-Object
cmdlet for filtering before they are assigned to the $read_only
variable.

The following example demonstrates that the index operator takes precedence
over the
cast operator.

This expression creates an array of three strings. Then, it uses the index
operator with a
value of 0 to select the first object in the array, which is
the first string. Finally, it casts
the selected object as a string. In this
case, the cast has no effect.

PowerShell

PS> [string]@('Windows','PowerShell','2.0')[0]
Windows

This expression uses parentheses to force the cast operation to occur before
the index
selection. As a result, the entire array is cast as a (single)
string. Then, the index operator
selects the first item in the string array,
which is the first character.

PowerShell

PS> ([string]@('Windows','PowerShell','2.0'))[0]

In the following example, because the -gt (greater-than) operator has a


higher
precedence than the -and (logical AND) operator, the result of the
expression is FALSE.

PowerShell

PS> 2 -gt 4 -and 1

False

It is equivalent to the following expression.

PowerShell

PS> (2 -gt 4) -and 1

False

If the -and operator had higher precedence, the answer would be TRUE.

PowerShell
PS> 2 -gt (4 -and 1)

True

However, this example demonstrates an important principle of managing operator


precedence. When an expression is difficult for people to interpret, use
parentheses to
force the evaluation order, even when it forces the default
operator precedence. The
parentheses make your intentions clear to people who
are reading and maintaining your
scripts.

See also
about_Operators
about_Arithmetic_Operators
about_Assignment_Operators
about_Comparison_Operators
about_Type_Operators
about_Join
about_Redirection
about_Scopes
about_Split
about_Output_Streams
Article • 02/01/2023 • 2 minutes to read

Short description
Explains the availability and purpose of output streams in PowerShell.

Long description
PowerShell provides multiple output streams. The streams provide channels for
different
types of messages. You can write to these streams using the
associated cmdlet or
redirection. For more information, see
about_Redirection.

PowerShell supports the following output streams.

Stream # Description Introduced in Write Cmdlet

1 Success stream PowerShell 2.0 Write-Output

2 Error stream PowerShell 2.0 Write-Error

3 Warning stream PowerShell 2.0 Write-Warning

4 Verbose stream PowerShell 2.0 Write-Verbose

5 Debug stream PowerShell 2.0 Write-Debug

6 Information stream PowerShell 5.0 Write-Information

n/a Progress stream PowerShell 2.0 Write-Progress

7 Note

The Progress stream doesn't support redirection.

Success stream
The Success stream is the default stream for normal, successful results.
Use the Write-
Output cmdlet to explicitly write objects to this stream. This
stream is used for passing

objects through the PowerShell pipeline. The


Success stream is connected to the stdout
stream for native
applications.
Error stream
The Error stream is the default stream for error results. Use the
Write-Error cmdlet to
explicitly write to this stream. The Error stream
is connected to the stderr stream for
native applications. Under most
conditions, these errors can terminate the execution
pipeline. Errors written
to this stream are also added to the $Error automatic variable.
For more
information, see about_Automatic_Variables.

Warning stream
The Warning stream is intended for error conditions that are less severe
than errors
written to the Error stream. Under normal conditions, these
warnings don't terminate
execution. Warnings aren't written to the $Error
automatic variable. Use the Write-
Warning cmdlet to explicitly write to this
stream.

Verbose stream
The Verbose stream is intended for messages that help users troubleshoot
commands
as they're run interactively or from a script. Use the Write-Verbose
cmdlet to explicitly
write messages to this stream. Many cmdlets provide
verbose output that's useful for
understanding the internal workings of the
cmdlet. The verbose messages are output
only when you use the -Verbose common
parameter. For more information, see
about_CommonParameters.

Debug stream
The Debug stream is used for messages that help scripters understand why
their code is
failing. Use the Write-Debug cmdlet to explicitly write to this
stream. The debug
messages are output only when you use the -Debug common
parameter. For more
information, see about_CommonParameters.

Debug messages are intended for script and cmdlet developers more than end
users.
These debug messages can contain internal details necessary for deep
troubleshooting.

Information stream
The Information stream is intended to provide messages that help a user
understand
what a script is doing. It can also be used by developers as an
additional stream used to
pass information through PowerShell. The developer
can tag stream data and have
specific handling for that stream. Use the
Write-Information cmdlet to explicitly write to
this stream.

Write-Host also writes to the Information stream. The difference between


the cmdlets is

that Write-Host also writes to the host console unless you


redirect the Information
stream. Write-Information only writes to the
Information stream.

Progress stream
The Progress stream is used for messages that communicate progress in
longer running
commands and scripts. Use the Write-Progress cmdlet to
explicitly write messages to
this stream. The Progress stream doesn't
support redirection.

See also
about_CommonParameters
about_Redirection
Write-Debug
Write-Error
Write-Host
Write-Information
Write-Output
Write-Progress
Write-Verbose
Write-Warning
about_PackageManagement
Article • 09/19/2022 • 2 minutes to read

Short description
PackageManagement is an aggregator for software package managers.

Long description
PackageManagement functionality was introduced in Windows PowerShell 5.0.

PackageManagement is a unified interface for software package management


systems;
you can run PackageManagement cmdlets to perform software discovery,
installation,
and inventory (SDII) tasks. Regardless of the underlying
installation technology, you can
run the common cmdlets in the
PackageManagement module to search for, install, or
uninstall packages; add,
remove, and query package repositories; and run queries on a
computer to
determine which software packages are installed.

PackageManagement supports a flexible plug-in model that enables support for


other
software package management systems.

The PackageManagement module is included with Windows PowerShell 5.0 and later
releases of PowerShell, and works on three levels of package management
structure:
package providers, package sources, and the packages themselves. Let
us define some
terms:

Package manager: Software package management system. In


PackageManagement
terms, this is a package provider.
Package provider: PackageManagement term for a package manager. Examples
can
include Windows Installer, Chocolatey, and others.
Package source: A URL, local folder, or network shared folder that you
configure
package providers to use as a repository.
Package: A piece of software that a package provider manages, and that is
stored
in a specific package source.

The PackageManagement module includes the following cmdlets. For more


information,
see the PackageManagement
help.

Get-PackageProvider : Returns a list of package providers that are


connected to

PackageManagement.
Get-PackageSource : Gets a list of package sources that are registered for
a package

provider.
Register-PackageSource : Adds a package source for a specified package
provider.

Set-PackageSource : Sets properties on an existing package source.


Unregister-PackageSource : Removes a registered package source.

Get-Package : Returns a list of installed software packages.

Find-Package : Finds software packages in available package sources.


Install-Package : Installs one or more software packages.

Save-Package : Saves packages to the local computer without installing


them.
Uninstall-Package : Uninstalls one or more software packages.

Package Provider Bootstrapping and Dynamic Cmdlet


Parameters
By default, PackageManagement ships with a core bootstrap provider. You can
install
additional package providers as you need them by bootstrapping the
providers; that is,
responding to a prompt to install the provider
automatically, from a web service. You
can specify a package provider with any
PackageManagement cmdlet; if the specified
provider is not available,
PackageManagement prompts you to bootstrap (or
automatically install) the
provider. In the following examples, if the Chocolatey provider
is not already
installed, PackageManagement bootstrapping installs the provider.

PowerShell

Find-Package -Provider Chocolatey <PackageName>

If the Chocolatey provider is not already installed, when you run the
preceding
command, you are prompted to install it.

PowerShell

Install-Package <Chocolatey package Name> -ForceBootstrap

If the Chocolatey provider is not already installed, when you run the
preceding
command, the provider is installed; but because the ForceBootstrap
parameter has been
added to the command, you are not prompted to install it;
both the provider and the
package are installed automatically.

When you try to install a package, if you do not already have the supporting
provider
installed, and you do not add the ForceBootstrap parameter to your
command,
PackageManagement prompts you to install the provider.
Specifying a package provider in your PackageManagement command can make
dynamic parameters available that are specific to that package provider. When
you run
Get-Help for a specific PackageManagement cmdlet, a list of parameter
sets are
returned, grouping dynamic parameters for available package providers
in separate
parameter sets.

More Information About the PackageManagement Project

For more information about the PackageManagement open development project,


including how to create a PackageManagement package provider, see the
PackageManagement project on GitHub at https://oneget.org .

See also
Find-Package
Get-Package
Install-Package
Save-Package
Uninstall-Package
Get-PackageProvider
Get-PackageSource
Register-PackageSource
Set-PackageSource
Unregister-PackageSource
about_Parameters
Article • 11/15/2022 • 6 minutes to read

Short description
Describes how to work with command parameters in PowerShell.

Long description
Most PowerShell commands, such as cmdlets, functions, and scripts, rely on
parameters
to allow users to select options or provide input. The parameters
follow the command
name and have the following form:

-<parameter_name> <parameter_value>

-<parameter_name>:<parameter_value>

The name of the parameter is preceded by a hyphen ( - ), which signals to


PowerShell
that the word following the hyphen is a parameter name. The
parameter name and
value can be separated by a space or a colon character. Some
parameters do not require
or accept a parameter value. Other parameters require
a value, but do not require the
parameter name in the command.

The type of parameters and the requirements for those parameters vary. To find
information about the parameters of a command, use the Get-Help cmdlet. For
example, to find information about the parameters of the Get-ChildItem cmdlet,
type:

PowerShell

Get-Help Get-ChildItem

To find information about the parameters of a script, use the full path to the
script file.
For example:

PowerShell

Get-Help $HOME\Documents\Scripts\Get-Function.ps1

The Get-Help cmdlet returns various details about the command, including a
description, the command syntax, information about the parameters, and
examples
showing how to use the parameters in a command.

You can also use the Parameter parameter of the Get-Help cmdlet to find
information
about a particular parameter. Or, you can use the Parameter
parameter with the
wildcard character ( * ) value to find information about
all parameters of the command.
For example, the following command gets
information about all parameters of the Get-
Member cmdlet:

PowerShell

Get-Help Get-Member -Parameter *

Default parameter values


Optional parameters have a default value, which is the value that is used or
assumed
when the parameter is not specified in the command.

For example, the default value of the ComputerName parameter of many


cmdlets is the
name of the local computer. As a result, the local computer name
is used in the
command unless the ComputerName parameter is specified.

To find the default parameter value, see help topic for the cmdlet. The
parameter
description should include the default value.

You can also set a custom default value for any parameter of a cmdlet or
advanced
function. For information about setting custom default values, see
about_Parameters_Default_Values.

Parameter attribute table


When you use the Full, Parameter, or Online parameters of the
Get-Help cmdlet, Get-
Help displays a parameter attribute table with
detailed information about the 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? 0

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, PowerShell
prompts you for a value for the
parameter.

Parameter Position
If the Position setting is set to a non-negative integer, 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. A named parameter can be
listed in any position after the cmdlet
name. 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
Position
setting for Path is 0, which means that it is a positional
parameter. The Position setting
for Exclude is named.

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 Position settings for these two parameters, you can use
any of the
following commands:

PowerShell

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 must be placed in the order specified by the
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 Name parameter of the Get-Service cmdlet accepts


multiple values.
The following commands are both valid:

PowerShell

Get-Service -Name winrm, netlogon

PowerShell

$s = "winrm", "netlogon"

Get-Service -Name $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)", 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.

7 Note

A typed parameter that accepts pipeline input ( by Value ) or


( by PropertyName )
enables use of delay-bind script blocks on the
parameter.

The delay-bind script block is run automatically during


ParameterBinding. The
result is bound to the parameter. Delay binding
does not work for parameters
defined as type ScriptBlock or
System.Object , the script block is passed through
without being invoked.

You can read about delay-bind script blocks here


about_Script_Blocks.md

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, see
about_CommonParameters.

See also
about_Command_syntax
about_Comment_Based_Help
about_Functions_Advanced
about_Parameters_Default_Values
about_Pipelines
about_Wildcards
about_Parameters_Default_Values
Article • 09/19/2022 • 6 minutes to read

Short description
Describes how to set custom default values for cmdlet parameters and advanced
functions.

Long description
The $PSDefaultParameterValues preference variable lets you specify custom
default
values for any cmdlet or advanced function. Cmdlets and advanced
functions use the
custom default value unless you specify another value in the
command.

The authors of cmdlets and advanced functions set standard default values for
their
parameters. Typically, the standard default values are useful, but they
might not be
appropriate for all environments.

This feature is especially useful when you must specify the same alternate
parameter
value nearly every time you use the command or when a particular
parameter value is
difficult to remember, such as an email server name or
project GUID.

If the desired default value varies predictably, you can specify a script block
that
provides different default values for a parameter under different
conditions.

$PSDefaultParameterValues was introduced in PowerShell 3.0.

Syntax
The $PSDefaultParameterValues variable is a hash table that validates the
format of keys
as an object type of
System.Management.Automation.DefaultParameterDictionary.
The hash table
contains Key/Value pairs. A Key is in the format
CmdletName:ParameterName . A Value is the DefaultValue or
ScriptBlock assigned to the

key.

The syntax of the $PSDefaultParameterValues preference variable is as


follows:

$PSDefaultParameterValues=@{"CmdletName:ParameterName"="DefaultValue"}

$PSDefaultParameterValues=@{ "CmdletName:ParameterName"={{ScriptBlock}} }

$PSDefaultParameterValues["Disabled"]=$True | $False

Wildcard characters are permitted in the CmdletName and ParameterName


values.

To set, change, add, or remove a specific Key/Value pair from


$PSDefaultParameterValues , use the methods to edit a standard hash table. For
example,

the Add and Remove methods. These methods don't overwrite


other values in the hash
table.

There's another syntax that doesn't overwrite an existing


$PSDefaultParameterValues
hash table. To add or change a specific
Key/Value pair, use the following syntax:

$PSDefaultParameterValues["CmdletName:ParameterName"]="DefaultValue"

The CmdletName must be the name of a cmdlet or the name of an advanced


function
that uses the CmdletBinding attribute. You can't use
$PSDefaultParameterValues to
specify default values for scripts or simple
functions.

The DefaultValue can be an object or a script block. If the value is a


script block,
PowerShell evaluates the script block and uses the result as the
parameter value. When
the specified parameter accepts a script block value,
enclose the script block value in a
second set of braces, such as:

PowerShell

$PSDefaultParameterValues=@{ "Invoke-Command:ScriptBlock"={{Get-Process}} }

For more information, see the following documents:

about_Hash_Tables
about_Script_Blocks
about_Preference_Variables

Examples

How to set $PSDefaultParameterValues


$PSDefaultParameterValues is a preference variable, so it exists only in the
session in

which it's set. It has no default value.

To set $PSDefaultParameterValues , type the variable name and one or more


Key/Value
pairs. If you run another $PSDefaultParameterValues command, it
overwrites the existing
hash table.

For examples about how to change Key/Value pairs without overwriting


existing hash
table values, see
How to add values to $PSDefaultParameterValues
or
How to change
values in $PSDefaultParameterValues.

To save $PSDefaultParameterValues for future sessions, add a


$PSDefaultParameterValues command to your PowerShell profile. For more
information,

see about_Profiles.

Set a custom default value


The Key/Value pair sets the Send-MailMessage:SmtpServer key to a custom
default value
of Server123.

PowerShell

$PSDefaultParameterValues = @{

"Send-MailMessage:SmtpServer"="Server123"

Set default values for multiple parameters

To set default values for multiple parameters, separate each Key/Value pair
with a
semicolon ( ; ). The Send-MailMessage:SmtpServer and
Get-WinEvent:LogName keys are set
to custom default values.

PowerShell

$PSDefaultParameterValues = @{

"Send-MailMessage:SmtpServer"="Server123";

"Get-WinEvent:LogName"="Microsoft-Windows-PrintService/Operational"

Use wildcards and switch parameters


The cmdlet and parameter names can contain wildcard characters. Use $True and
$False to set values for switch parameters, such as Verbose. The common
parameter's
Verbose parameter is set to $True for all commands.

PowerShell

$PSDefaultParameterValues = @{"*:Verbose"=$True}

Use an array for the default value


If a parameter can accept multiple values, an array, you can set multiple
values as the
default values. The default value of the
Invoke-Command:ComputerName key is set to an
array value of Server01 and
Server02.

PowerShell

$PSDefaultParameterValues = @{

"Invoke-Command:ComputerName"="Server01","Server02"

Use a script block


You can use a script block to specify different default values for a parameter
under
different conditions. PowerShell evaluates the script block and uses the
result as the
default parameter value.

The Format-Table:AutoSize key sets that switch parameter to a default value


of True.
The If statement contains a condition that the $host.Name must
be the PowerShell
console, ConsoleHost.

PowerShell

$PSDefaultParameterValues=@{

"Format-Table:AutoSize"={if ($host.Name -eq "ConsoleHost"){$True}}

If a parameter accepts a script block value, enclose the script block in an


extra set of
braces. When PowerShell evaluates the outer script block, the
result is the inner script
block, and that is set as the default parameter
value.

The Invoke-Command:ScriptBlock key set to a default value of the System


event log
because the script block is enclosed in a second set of braces. The
result of the script
block is passed to the Invoke-Command cmdlet.

PowerShell

$PSDefaultParameterValues=@{

"Invoke-Command:ScriptBlock"={{Get-EventLog -Log System}}

How to get $PSDefaultParameterValues


The hash table values are displayed by entering $PSDefaultParameterValues at
the
PowerShell prompt.

A $PSDefaultParameterValues hash table is set with three Key/Value pairs.


This hash
table is used in the following examples that describe how to add,
change, and remove
values from $PSDefaultParameterValues .

PS> $PSDefaultParameterValues = @{

"Send-MailMessage:SmtpServer"="Server123"

"Get-WinEvent:LogName"="Microsoft-Windows-PrintService/Operational"

"Get-*:Verbose"=$True

PS> $PSDefaultParameterValues

Name Value

---- -----

Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational

Get-*:Verbose True

Send-MailMessage:SmtpServer Server123

To get the value of a specific CmdletName:ParameterName key, use the


following syntax:

$PSDefaultParameterValues["CmdletName:ParameterName"]

For example, to get the value for the Send-MailMessage:SmtpServer key.

PS> $PSDefaultParameterValues["Send-MailMessage:SmtpServer"]

Server123

How to add values to $PSDefaultParameterValues


To add a value to $PSDefaultParameterValues , use the Add method. Adding a
value
doesn't affect the hash table's existing values.

Use a comma ( , ) to separate the Key from the Value. The following
syntax shows how
to use the Add method for $PSDefaultParameterValues .

PS> $PSDefaultParameterValues.Add("CmdletName:ParameterName",
"DefaultValue")

The hash table created in the prior example is updated with a new Key/Value
pair. The
Add method sets the Get-Process:Name key to the value
PowerShell.

PowerShell

$PSDefaultParameterValues.Add("Get-Process:Name", "PowerShell")

The following syntax accomplishes the same result.

PowerShell

$PSDefaultParameterValues["Get-Process:Name"]="PowerShell"

The $PSDefaultParameterValues variable displays the updated hash table. The


Get-
Process:Name key was added.

PS> $PSDefaultParameterValues

Name Value

---- -----

Get-Process:Name PowerShell

Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational

Get-*:Verbose True

Send-MailMessage:SmtpServer Server123

How to remove values from $PSDefaultParameterValues


To remove a value from $PSDefaultParameterValues , use the Remove method
of hash
tables. Removing a value doesn't affect the hash table's existing
values.
The following syntax shows how to use the Remove method on
$PSDefaultParameterValues .

PS> $PSDefaultParameterValues.Remove("CmdletName:ParameterName")

In this example, the hash table created in the prior example is updated to
remove a
Key/Value pair. The Remove method removes the
Get-Process:Name key.

PowerShell

$PSDefaultParameterValues.Remove("Get-Process:Name")

The $PSDefaultParameterValues variable displays the updated hash table. The


Get-
Process:Name key was removed.

PS> $PSDefaultParameterValues

Name Value

---- -----

Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational

Get-*:Verbose True

Send-MailMessage:SmtpServer Server123

How to change values in $PSDefaultParameterValues


Changes to a specific value don't affect existing hash table values. To change
a specific
Key/Value pair in $PSDefaultParameterValues , use the following
syntax:

PS> $PSDefaultParameterValues["CmdletName:ParameterName"]="DefaultValue"

In this example, the hash table created in the prior example is updated to
change a
Key/Value pair. The following command changes the
Send-MailMessage:SmtpServer key
to a new value of ServerXYZ.

PowerShell

$PSDefaultParameterValues["Send-MailMessage:SmtpServer"]="ServerXYZ"

The $PSDefaultParameterValues variable displays the updated hash table. The


Send-
MailMessage:SmtpServer key was changed to a new value.

PS> $PSDefaultParameterValues

Name Value

---- -----

Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational

Get-*:Verbose True

Send-MailMessage:SmtpServer ServerXYZ

How to disable and re-enable $PSDefaultParameterValues


You can temporarily disable and then re-enable $PSDefaultParameterValues .
Disabling
$PSDefaultParameterValues is useful if you're running scripts that
need different default
parameter values.

To disable $PSDefaultParameterValues , add a key of Disabled with a value of


True. The
values in $PSDefaultParameterValues are preserved, but aren't
effective.

PS> $PSDefaultParameterValues.Add("Disabled", $True)

The following syntax accomplishes the same result.

PS> $PSDefaultParameterValues["Disabled"]=$True

The $PSDefaultParameterValues variable displays the updated hash table with


the value
for the Disabled key.

PS> $PSDefaultParameterValues

Name Value

---- -----

Disabled True

Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational

Get-*:Verbose True

Send-MailMessage:SmtpServer ServerXYZ

To re-enable $PSDefaultParameterValues , remove the Disabled key or change


the value
of the Disabled key to $False . The previous value of
$PSDefaultParameterValues is
effective again.

PS> $PSDefaultParameterValues.Remove("Disabled")

The following syntax accomplishes the same result.

PS> $PSDefaultParameterValues["Disabled"]=$False

The $PSDefaultParameterValues variable displays the updated hash table. When


the
Remove method is used, the Disabled key is removed from the output.
If the alternate
syntax was used to re-enable $PSDefaultParameterValues , the
Disabled key is displayed
as False.

PS> $PSDefaultParameterValues

Name Value

---- -----

Disabled False

Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational

Get-*:Verbose True

Send-MailMessage:SmtpServer ServerXYZ

See also
about_CommonParameters
about_Functions_Advanced
about_Functions_CmdletBindingAttribute
about_Hash_Tables
about_Preference_Variables
about_Profiles
about_Script_Blocks
about_Parameter_Sets
Article • 09/19/2022 • 4 minutes to read

Short description
Describes how to define and use parameter sets in advanced functions.

Long description
PowerShell uses parameter sets to enable you to write a single function that
can do
different actions for different scenarios. Parameter sets enable you to
expose different
parameters to the user. And, to return different information
based on the parameters
specified by the user. You can only use one parameter
set at a time.

Parameter set requirements


The following requirements apply to all parameter sets.

If no parameter set is specified for a parameter, the parameter belongs to


all
parameter sets.

Each parameter set must have a unique combination of parameters. If possible,


at
least one of the unique parameters should be a mandatory parameter.

A parameter set that contains multiple positional parameters must define


unique
positions for each parameter. No two positional parameters can specify
the same
position.

Only one parameter in a set can declare the ValueFromPipeline keyword with
a
value of true . Multiple parameters can define the
ValueFromPipelineByPropertyName keyword with a value of true .

7 Note

There is a limit of 32 parameter sets.

Default parameter sets


When multiple parameter sets are defined, the DefaultParameterSetName keyword
of the
CmdletBinding attribute specifies the default parameter set.
PowerShell uses the default
parameter set when it can't determine the parameter
set to use based on the
information provided to the command. For more
information about the CmdletBinding
attribute, see
about_functions_cmdletbindingattribute.

Declaring parameter sets


To create a parameter set, you must specify the ParameterSetName keyword of
the
Parameter attribute for every parameter in the parameter set. For
parameters that
belong to multiple parameter sets, add a Parameter
attribute for each parameter set.

The Parameter attribute enables you to define the parameter differently for
each
parameter set. For example, you can define a parameter as mandatory in one
set and
optional in another. However, each parameter set must contain at least
one unique
parameter.

Parameters that don't have an assigned parameter set name belong to all
parameter
sets.

Example
The following example function counts the number lines, characters, and words
in a text
file. Using parameters, you can specify which values you want
returned and which files
you want to measure. There are four parameter sets
defined:

Path
PathAll
LiteralPath
LiteralPathAll

PowerShell

function Measure-Lines {

[CmdletBinding(DefaultParameterSetName = 'Path')]

param (

[Parameter(Mandatory = $true,

ParameterSetName = 'Path',

HelpMessage = 'Enter one or more filenames',

Position = 0)]

[Parameter(Mandatory = $true,

ParameterSetName = 'PathAll',

Position = 0)]

[string[]]$Path,

[Parameter(Mandatory = $true, ParameterSetName = 'LiteralPathAll')]

[Parameter(Mandatory = $true,

ParameterSetName = 'LiteralPath',

HelpMessage = 'Enter a single filename',

ValueFromPipeline = $true)]

[string]$LiteralPath,

[Parameter(ParameterSetName = 'Path')]

[Parameter(ParameterSetName = 'LiteralPath')]

[switch]$Lines,

[Parameter(ParameterSetName = 'Path')]

[Parameter(ParameterSetName = 'LiteralPath')]

[switch]$Words,

[Parameter(ParameterSetName = 'Path')]

[Parameter(ParameterSetName = 'LiteralPath')]

[switch]$Characters,

[Parameter(Mandatory = $true, ParameterSetName = 'PathAll')]

[Parameter(Mandatory = $true, ParameterSetName = 'LiteralPathAll')]

[switch]$All,

[Parameter(ParameterSetName = 'Path')]

[Parameter(ParameterSetName = 'PathAll')]

[switch]$Recurse

begin {

if ($All) {

$Lines = $Words = $Characters = $true

elseif (($Words -eq $false) -and ($Characters -eq $false)) {

$Lines = $true

if ($Path) {

$Files = Get-ChildItem -Path $Path -Recurse:$Recurse

else {

$Files = Get-ChildItem -LiteralPath $LiteralPath

process {

foreach ($file in $Files) {

$result = [ordered]@{ }

$result.Add('File', $file.fullname)

$content = Get-Content -LiteralPath $file.fullname

if ($Lines) { $result.Add('Lines', $content.Length) }

if ($Words) {

$wc = 0
foreach ($line in $content) { $wc += $line.split(' ').Length
}

$result.Add('Words', $wc)

if ($Characters) {

$cc = 0
foreach ($line in $content) { $cc += $line.Length }

$result.Add('Characters', $cc)

New-Object -TypeName psobject -Property $result

Each parameter set must have a unique parameter or a unique combination of


parameters. The Path and PathAll parameter sets are very similar but the
All parameter
is unique to the PathAll parameter set. The same is true
with the LiteralPath and
LiteralPathAll parameter sets. Even though the
PathAll and LiteralPathAll
parameter sets both have the All parameter,
the Path and LiteralPath parameters
differentiate them.

Use Get-Command -Syntax shows you the syntax of each parameter set. However
it does
not show the name of the parameter set. The following example shows
which
parameters can be used in each parameter set.

PowerShell

(Get-Command Measure-Lines).ParameterSets |

Select-Object -Property @{n='ParameterSetName';e={$_.name}},

@{n='Parameters';e={$_.ToString()}}

Output

ParameterSetName Parameters

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

Path [-Path] <string[]> [-Lines] [-Words] [-Characters] [-


Recurse] [<CommonParameters>]

PathAll [-Path] <string[]> -All [-Recurse] [<CommonParameters>]

LiteralPath -LiteralPath <string> [-Lines] [-Words] [-Characters]


[<CommonParameters>]

LiteralPathAll -LiteralPath <string> -All [<CommonParameters>]

Parameter sets in action


In this example, we are using the PathAll parameter set.
PowerShell

Measure-Lines test* -All

Output

File Lines Words Characters

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

C:\temp\test\test.help.txt 31 562 2059

C:\temp\test\test.md 30 1527 3224

C:\temp\test\test.ps1 3 3 79

C:\temp\test\test[1].txt 31 562 2059

Error using parameters from multiple sets


In this example, unique parameters from different parameter sets are used.

PowerShell

Get-ChildItem -Path $PSHOME -LiteralPath $PSHOME

Output

Get-ChildItem : Parameter set cannot be resolved using the specified named


parameters.

At line:1 char:1

+ Get-ChildItem -Path $PSHOME -LiteralPath $PSHOME

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : InvalidArgument: (:) [Get-ChildItem],


ParameterBindingException

+ FullyQualifiedErrorId :
AmbiguousParameterSet,Microsoft.PowerShell.Commands.GetChildItemCommand

The Path and LiteralPath parameters are unique to different parameter


sets of the Get-
ChildItem cmdlet. When the parameters are run together in the
same cmdlet, an error is
thrown. Only one parameter set can be used per cmdlet
call at a time.
about_Parsing
Article • 02/27/2023 • 10 minutes to read

Short description
Describes how PowerShell parses commands.

Long description
When you enter a command at the command prompt, PowerShell breaks the command
text into a series of segments called tokens and then determines how to
interpret each
token.

For example, if you type:

PowerShell

Write-Host book

PowerShell breaks the command into two tokens, Write-Host and book , and
interprets
each token independently using one of two major parsing modes:
expression mode and
argument mode.

7 Note

As PowerShell parses command input it tries to resolve the command names to


cmdlets or native executables. If a command name doesn't have an exact
match,
PowerShell prepends Get- to the command as a default verb. For
example,
PowerShell parses Service as Get-Service . It's not
recommended to use this
feature for the following reasons:

It's inefficient. This causes PowerShell to search multiple times.


External programs with the same name are resolved first, so you may not
execute the intended cmdlet.
Get-Help and Get-Command don't recognize verb-less names.

The command name may be a reserved word or a language keyword. Process


is
both, and can't be resolved to Get-Process .
Expression mode
Expression mode is intended for combining expressions, required for value
manipulation
in a scripting language. Expressions are representations of values
in PowerShell syntax,
and can be simple or composite, for example:

Literal expressions are direct representations of their values:

PowerShell

'hello'

32

Variable expressions carry the value of the variable they reference:

PowerShell

$x

$script:path

Operators combine other expressions for evaluation:

PowerShell

-12

-not $Quiet

3 + 7

$input.Length -gt 1

Character string literals must be contained in quotation marks.


Numbers are treated as numerical values rather than as a series of
characters
(unless escaped).
Operators, including unary operators like - and -not and binary
operators like +
and -gt , are interpreted as operators and apply their
respective operations on
their arguments (operands).
Attribute and conversion expressions are parsed as expressions and applied
to
subordinate expressions. For example: [int] '7' .
Variable references are evaluated to their values but splatting is
forbidden and
causes a parser error.
Anything else is treated as a command to be invoked.

Argument mode
When parsing, PowerShell first looks to interpret input as an expression. But
when a
command invocation is encountered, parsing continues in argument mode.
If you have
arguments that contain spaces, such as paths, then you must
enclose those argument
values in quotes.

Argument mode is designed for parsing arguments and parameters for commands in
a
shell environment. All input is treated as an expandable string unless it
uses one of the
following syntaxes:

Dollar sign ( $ ) followed by a variable name begins a variable reference,


otherwise
it's interpreted as part of the expandable string. The variable
reference can include
member access or indexing.
Additional characters following simple variable references, such as
$HOME , are
considered part of the same argument. Enclose the variable
name in braces ( {} )
to separate it from subsequent characters. For
example, ${HOME} .
When the variable reference includes member access, the first of any
additional
characters is considered the start of a new argument. For
example
$HOME.Length-more results in two arguments: the value of
$HOME.Length and

string literal -more .

Quotation marks ( ' and " ) begin strings

Braces ( {} ) begin a new script blocks

Commas ( , ) introduce lists passed as arrays, unless the command being


called is a
native application, in which case they're interpreted as part of
the expandable
string. Initial, consecutive or trailing commas aren't
supported.

Parentheses ( () ) begin a new expression

Subexpression operator ( $() ) begins an embedded expression

Initial at sign ( @ ) begins expression syntaxes such as splatting ( @args ),


arrays
( @(1,2,3) ), and hash table literals ( @{a=1;b=2} ).

() , $() , and @() at the start of a token create a new parsing context
that can

contain expressions or nested commands.


When followed by additional characters, the first additional character is
considered the start of a new, separate argument.
When preceded by an unquoted literal $() works like an expandable string,
()
starts a new argument that's an expression, and @() is taken as
literal @ with ()
starting a new argument that's an expression.
Everything else is treated as an expandable string, except metacharacters
that still
need escaping. See Handling special characters.
The argument-mode metacharacters (characters with special syntactic
meaning)
are: <space> ' " ` , ; ( ) { } | & < > @ # . Of these,
< > @ # are only special
at the start of a token.

The stop-parsing token ( --% ) changes the interpretation of all remaining


arguments. For more information, see the stop-parsing token section
below.

Examples
The following table provides several examples of tokens processed in expression
mode
and argument mode and the evaluation of those tokens. For these examples,
the value
of the variable $a is 4 .

Example Mode Result

2 Expression 2 (integer)

`2 Expression "2" (command)

Write-Output 2 Expression 2 (integer)

2+2 Expression 4 (integer)

Write-Output 2+2 Argument "2+2" (string)

Write-Output(2+2) Expression 4 (integer)

$a Expression 4 (integer)

Write-Output $a Expression 4 (integer)

$a+2 Expression 6 (integer)

Write-Output $a+2 Argument "4+2" (string)

$- Argument "$-" (command)

Write-Output $- Argument "$-" (string)

a$a Expression "a$a" (command)

Write-Output a$a Argument "a4" (string)

a'$a' Expression "a$a" (command)

Write-Output a'$a' Argument "a$a" (string)


Example Mode Result

a"$a" Expression "a$a" (command)

Write-Output a"$a" Argument "a4" (string)

a$(2) Expression "a$(2)" (command)

Write-Output a$(2) Argument "a2" (string)

Every token can be interpreted as some kind of object type, such as Boolean
or String.
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 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)

Set-Variable AB A,B argument 'A','B' (array)

CMD /CECHO A,B argument 'A,B' (string)

CMD /CECHO $AB expression 'A B' (array)

CMD /CECHO :$AB argument ':A B' (string)

Handling special characters


The backtick character ( ` ) can be used to escape any special character in
an expression.
This is most useful for escaping the argument-mode
metacharacters that you want to
use as literal characters rather than as a
metacharacter. For example, to use the dollar
sign ( $ ) as a literal in an
expandable string:

PowerShell

"The value of `$ErrorActionPreference is '$ErrorActionPreference'."

Output

The value of $ErrorActionPreference is 'Continue'.

Line continuation
The backtick character can also be used at the end of a line to allow you to
continue the
input on the next line. This is improve the readability of a
command that takes several
parameters with long names and argument values. For
example:

PowerShell

New-AzVm `

-ResourceGroupName "myResourceGroupVM" `

-Name "myVM" `

-Location "EastUS" `

-VirtualNetworkName "myVnet" `

-SubnetName "mySubnet" `

-SecurityGroupName "myNetworkSecurityGroup" `

-PublicIpAddressName "myPublicIpAddress" `

-Credential $cred

However, you should avoid using line continuation.

The backtick characters can be hard to see and easy to forget.


An extra space after the backtick breaks the line continuation. Since the
space is
hard to see it can be difficult to find the error.

PowerShell provides several ways break lines at natural points in the syntax.

After pipe characters ( | )


After binary operators ( + , - , -eq , etc.)
After commas ( , ) in an array
After opening characters such as [ , { , (

For large parameter set, use splatting instead. For example:

PowerShell

$parameters = @{

ResourceGroupName = "myResourceGroupVM"

Name = "myVM"

Location = "EastUS"

VirtualNetworkName = "myVnet"
SubnetName = "mySubnet"

SecurityGroupName = "myNetworkSecurityGroup"

PublicIpAddressName = "myPublicIpAddress"

Credential = $cred

New-AzVm @parameters

Passing arguments to native commands


When running native commands from PowerShell, the arguments are first parsed by
PowerShell. The parsed arguments are then joined into a single string with each
parameter separated by a space.

For example, the following command calls the icacls.exe program.

PowerShell

icacls X:\VMS /grant Dom\HVAdmin:(CI)(OI)F

To run this command in PowerShell 2.0, you must use escape characters to
prevent
PowerShell from misinterpreting the parentheses.

PowerShell

icacls X:\VMS /grant Dom\HVAdmin:`(CI`)`(OI`)F

The stop-parsing token


Beginning in PowerShell 3.0, you can use the stop-parsing ( --% ) token to
stop
PowerShell from interpreting input as PowerShell commands or expressions.

7 Note

The stop-parsing token is only intended for use on Windows platforms.

When calling a native command, place the stop-parsing token before the program
arguments. This technique is much easier than using escape characters to
prevent
misinterpretation.

When it encounters a stop-parsing token, PowerShell treats the remaining


characters in
the line as a literal. The only interpretation it performs is to
substitute values for
environment variables that use standard Windows notation,
such as %USERPROFILE% .

PowerShell

icacls X:\VMS --% /grant Dom\HVAdmin:(CI)(OI)F

PowerShell sends the following command string to the icacls.exe program:

X:\VMS /grant Dom\HVAdmin:(CI)(OI)F

The stop-parsing token is effective only until the next newline or pipeline
character. You
can't use the line continuation character ( ` ) to extend
its effect or use a command
delimiter ( ; ) to terminate its effect.

Other than %variable% environment-variable references, you can't embed any


other
dynamic elements in the command. Escaping a % character as %% , the
way you can do
inside batch files, isn't supported. %<name>% tokens are
invariably expanded. If <name>
doesn't refer to a defined environment
variable the token is passed through as-is.

You can't use stream redirection (like >file.txt ) because they're passed
verbatim as
arguments to the target command.

In the following example, the first step runs a command without using the
stop-parsing
token. PowerShell evaluates the quoted string and passes the value
(without quotes) to
cmd.exe , which results in an error.

PowerShell

PS> cmd /c echo "a|b"

'b' is not recognized as an internal or external command,

operable program or batch file.

PS> cmd /c --% echo "a|b"

"a|b"

7 Note

Some commands on Windows systems are implemented as a Windows batch file.


For
example, that az command for Azure CLI is a Windows batch file.

Passing arguments that contain quote characters


Some native commands expect arguments that contain quote characters. Normally,
PowerShell's command line parsing removes the quote character you provided. The
parsed arguments are then joined into a single string with each parameter
separated by
a space. This string is then assigned to the Arguments
property of a ProcessStartInfo
object. Quotes within the string must be
escaped using extra quotes or backslash ( \ )
characters.
7 Note

The backslash ( \ ) character isn't recognized as an escape character by


PowerShell.
It's the escape character used by the underlying API for
ProcessStartInfo.Arguments .

For more information about the escape requirements, see the documentation for
ProcessStartInfo.Arguments.

7 Note

The following examples use the TestExe.exe tool. You can build TestExe
from the
source code. See TestExe in the PowerShell source repository.

The goal of these examples is to pass the directory path


"C:\Program Files
(x86)\Microsoft\" to a native command so that it received
the path as a quoted string.

The echoargs parameter of TestExe displays the values received as


arguments to the
executable. You can use this tool to verify that you have
properly escaped the characters
in your arguments.

PowerShell

TestExe -echoargs """""${env:ProgramFiles(x86)}\Microsoft\\"""""

TestExe -echoargs """""C:\Program Files (x86)\Microsoft\\"""""

TestExe -echoargs --% ""\""C:\Program Files (x86)\Microsoft\\""

TestExe -echoargs --% """C:\Program Files (x86)\Microsoft\\""

TestExe -echoargs --% """%ProgramFiles(x86)%\Microsoft\\""

The output is the same for all examples:

Output

Arg 0 is <"C:\Program Files (x86)\Microsoft\">

Passing arguments to PowerShell commands


Beginning in PowerShell 3.0, you can use the end-of-parameters token ( -- )
to stop
PowerShell from interpreting input as PowerShell parameters. This is a
convention
specified in the POSIX Shell and Utilities specification.
The end-of-parameters token
The end-of-parameters token ( -- ) indicates that all arguments following it
are to be
passed in their actual form as though double quotes were placed
around them. For
example, using -- you can output the string -InputObject
without using quotes or
having it interpreted as a parameter:

PowerShell

Write-Output -- -InputObject

Output

-InputObject

Unlike the stop-parsing ( --% ) token, any values following the -- token can
be
interpreted as expressions by PowerShell.

PowerShell

Write-Output -- -InputObject $env:PROCESSOR_ARCHITECTURE

Output

-InputObject

AMD64

This behavior only applies to PowerShell commands. If you use the -- token
when
calling an external command, the -- string is passed as an argument to
that command.

PowerShell

TestExe -echoargs -a -b -- -c

The output shows that -- is passed as an argument to TestExe .

Output

Arg 0 is <-a>

Arg 1 is <-b>

Arg 2 is <-->

Arg 3 is <-c>

See also
about_Command_Syntax
about_Path_Syntax
Article • 09/19/2022 • 3 minutes to read

Short description
Describes the full and relative path formats in PowerShell.

Long description
All items in a data store accessible through a PowerShell provider can be
uniquely
identified by their path names. A path is a combination of the
item name, the container
and subcontainers in which the item is located, and
the PowerShell drive through which
the containers are accessed.

In PowerShell, path names are divided into one of two types: fully qualified
and relative.
A fully qualified path consists of all elements that make
up a path. The following syntax
shows the elements in a fully qualified path
name:

Syntax

[<provider>::]<drive>:[\<container>[\<subcontainer>...]]\<item>

The <provider> placeholder refers to the 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 PowerShell drive that's supported by


a particular
PowerShell provider. In the case of the FileSystem provider, the
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
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 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:

PowerShell

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 don't need to specify a fully qualified path and can
instead use a
relative path. PowerShell allows you to identify an item based on
its location relative to
the current working location.

PowerShell uses the following character sequences to specify relative paths.

( . ) - Current location
( .. ) - Parent of current location
( \ ) - Root of current location

The following examples are based on the current working directory being set to
C:\Windows .

The relative path .\System resolves as C:\Windows\System


The relative path ..\Program Files resolves as C:\Program Files
The relative path \Program Files resolves as C:\Program Files
The relative path System resolves as C:\Windows\System

When using a path in a command, you can use a fully qualified path 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:

PowerShell

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 get the same results using the fully qualified path:

PowerShell

Get-ChildItem C:\TechDocs

Regardless of whether you use a fully qualified path or a relative path


name, a path 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 for the
first file ( C:\TechDocs\Jan\Results.txt ) and the path
for the second file
( C:\TechDocs\Feb\Results.txt ) allow you to clearly distinguish
between the
two files.

See also
about_Locations
about_Pipelines
Article • 09/19/2022 • 11 minutes to read

Short description
Combining commands into pipelines in the 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.

The output of the first command can be sent for processing as input to the
second
command. And that output can be sent to yet another command. The result
is a
complex command chain or pipeline that is composed of a series of
simple commands.

For example,

PowerShell

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 in order from left to right. The
processing is
handled as a single operation and output is displayed as it's
generated.

Here is a simple example. The following command gets the Notepad process and
then
stops it.

For example,

PowerShell

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 doesn't have a Name or ID parameter to


specify the process, because the
specified process is submitted through the
pipeline.

This pipeline example 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.

PowerShell

Get-ChildItem -Path *.txt |

Where-Object {$_.length -gt 10000} |

Sort-Object -Property length |

Format-Table -Property name, length

This pipeline consists of four commands in the specified order. The following
illustration
shows the output from each command as it's passed to the next
command in the
pipeline.

Get-ChildItem -Path *.txt

| (FileInfo objects for *.txt)

Where-Object {$_.length -gt 10000}

| (FileInfo objects for *.txt)

| ( Length > 10000 )

Sort-Object -Property Length

| (FileInfo objects for *.txt)

| ( Length > 10000 )

| ( Sorted by length )

Format-Table -Property name, length

| (FileInfo objects for *.txt)

| ( Length > 10000 )

| ( Sorted by length )

| ( Formatted in a table )

Name Length
---- ------
tmp1.txt 82920
tmp2.txt 114000
tmp3.txt 114000
Using pipelines
Most PowerShell cmdlets are designed to support pipelines. In most cases, you
can pipe
the results of a Get cmdlet to another cmdlet of the same noun.
For example, you can
pipe the output of the Get-Service cmdlet to the
Start-Service or Stop-Service
cmdlets.

This example pipeline starts the WMI service on the computer:

PowerShell

Get-Service wmi | Start-Service

For another example, you can pipe the output of Get-Item or Get-ChildItem
within the
PowerShell registry provider to the New-ItemProperty cmdlet. This
example adds a new
registry entry, NoOfEmployees, with a value of 8124,
to the MyCompany registry key.

PowerShell

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
object type to these cmdlets. This example shows
how to sort all the processes on the
computer by the number of open handles in
each process.

PowerShell

Get-Process | Sort-Object -Property handles

You can pipe objects to the formatting, export, and output cmdlets, such as
Format-
List , Format-Table , Export-Clixml , Export-CSV , and Out-File .

This example shows how to use the Format-List cmdlet to display a list of
properties for
a process object.

PowerShell

Get-Process winlogon | Format-List -Property *

You can also pipe the output of native commands to PowerShell cmdlets. For
example:
PowerShell

PS> ipconfig.exe | Select-String -Pattern 'IPv4'

IPv4 Address. . . . . . . . . . . : 172.24.80.1

IPv4 Address. . . . . . . . . . . : 192.168.1.45

IPv4 Address. . . . . . . . . . . : 100.64.108.37

) Important

The Success and Error streams are similar to the stdin and stderr
streams of other
shells. However, stdin is not connected to the PowerShell
pipeline for input. For
more information, see
about_Redirection.

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


This section explains how input objects are bound to cmdlet parameters and
processed
during pipeline execution.

Accepts pipeline input


To support pipelining, the receiving cmdlet must have a parameter that accepts
pipeline
input. Use the Get-Help command with the Full or Parameter
options to determine
which parameters of a cmdlet accept pipeline input.

For example, to determine which of the parameters of the Start-Service


cmdlet accepts
pipeline input, type:

PowerShell

Get-Help Start-Service -Full

or

PowerShell

Get-Help Start-Service -Parameter *

The help for the Start-Service cmdlet shows that only the InputObject and
Name
parameters accept pipeline input.

Output

-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? true
Position? 0

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? 0

Default value None


Accept pipeline input? True (ByPropertyName, ByValue)

Accept wildcard characters? false

When you send objects through the pipeline to Start-Service , PowerShell


attempts to
associate the objects with the InputObject and Name
parameters.

Methods of accepting pipeline input


Cmdlets parameters can accept pipeline input in one of two different ways:

ByValue: The parameter accepts values that match the expected .NET type
or 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: The parameter accepts input only when the input object
has a
property of 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 both value or property name, making it
easier
to take input from the pipeline.

Parameter binding
When you pipe objects from one command to another command, PowerShell attempts
to associate the piped objects with a parameter of the receiving cmdlet.

PowerShell's parameter binding component associates the input objects with


cmdlet
parameters according to the following criteria:

The parameter must accept input from a pipeline.


The parameter must accept the type of object being sent or a type that can be
converted to the expected type.
The parameter wasn't 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, service
objects, and objects with
properties that can be converted to string or service objects.

PowerShell manages parameter binding as efficiently as possible. You can't


suggest or
force the PowerShell to bind to a specific parameter. The command
fails if PowerShell
can't bind the piped objects.

For more information about troubleshooting binding errors, see


Investigating Pipeline
Errors later in this
article.

One-at-a-time processing
Piping objects to a command is much like using a parameter of the command to
submit
the objects. Let's look at a pipeline example. In this example, we use a
pipeline to display
a table of service objects.

PowerShell

Get-Service | Format-Table -Property Name, DependentServices

Functionally, this is like using the InputObject parameter of Format-Table


to submit the
object collection.

For example, we can save the collection of services to a variable that is


passed using the
InputObject parameter.
PowerShell

$services = Get-Service
Format-Table -InputObject $services -Property Name, DependentServices

Or we can embed the command in the InputObject parameter.

PowerShell

Format-Table -InputObject (Get-Service) -Property Name, DependentServices

However, there's an important difference. When you pipe multiple objects to a


command, 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
minor difference
has significant consequences.

When executing a pipeline, PowerShell automatically enumerates any type that


implements the IEnumerable interface and sends the members through the
pipeline one
at a time. The exception is [hashtable] , which requires a call
to the GetEnumerator()
method.

In the following examples, an array and a hashtable are piped to the Measure-Object
cmdlet to count the number of objects received from the pipeline. The array
has
multiple members, and the hashtable has multiple key-value pairs. Only the
array is
enumerated one at a time.

PowerShell

@(1,2,3) | Measure-Object

Output

Count : 3

Average :

Sum :

Maximum :

Minimum :

Property :

PowerShell

@{"One"=1;"Two"=2} | Measure-Object

Output

Count : 1

Average :

Sum :

Maximum :

Minimum :

Property :

Similarly, if you pipe multiple process objects from the Get-Process cmdlet
to the Get-
Member cmdlet, 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.

PowerShell

Get-Process | Get-Member

Output

TypeName: System.Diagnostics.Process

Name MemberType Definition

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

Handles AliasProperty Handles = Handlecount

Name AliasProperty Name = ProcessName

NPM AliasProperty NPM = NonpagedSystemMemorySize

...

7 Note

Get-Member eliminates duplicates, so if the objects are all of the same


type, it only

displays one object type.

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. It displays the properties
of an array of objects. (Note the
array symbol ( [] ) after the System.Object type name.)

For example,

PowerShell

Get-Member -InputObject (Get-Process)

Output

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, all array objects have a Count property. You can
use that to count the
number of processes running on the computer.

For example,

PowerShell

(Get-Process).count

It's important to remember that objects sent down the pipeline are delivered
one at a
time.

Using native commands in the pipeline


PowerShell allows you to include native external commands in the pipeline.
However, it
is important to note that PowerShell's pipeline is object-oriented
and does not support
raw byte data.

Piping or redirecting output from a native program that outputs raw byte data
converts
the output to .NET strings. This conversion can cause corruption of
the raw data output.

As a workaround, call the native commands using cmd.exe /c and use the |
and >
operators provided by the native shell.

Investigating pipeline errors


When PowerShell can't associate the piped objects with a parameter of the
receiving
cmdlet, the command fails.

In the following example, we try to move a registry entry from one registry
key to
another. The Get-Item cmdlet gets the destination path, which
is then piped to the
Move-ItemProperty cmdlet. The Move-ItemProperty
command specifies the current path

and name of the registry entry to be moved.

PowerShell

Get-Item -Path HKLM:\Software\MyCompany\sales |

Move-ItemProperty -Path HKLM:\Software\MyCompany\design -Name product

The command fails and PowerShell displays the following error


message:

Output

Move-ItemProperty : The input object can't be bound to any parameters for

the command either because the command doesn't 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 p

To investigate, use the Trace-Command cmdlet to trace the parameter binding


component
of PowerShell. The following example traces parameter binding while
the pipeline is
executing. The PSHost parameter displays the trace results
in the console and the
FilePath parameter send the trace results to the
debug.txt file for later reference.

PowerShell

Trace-Command -Name ParameterBinding -PSHost -FilePath debug.txt -Expression


{

Get-Item -Path HKLM:\Software\MyCompany\sales |

Move-ItemProperty -Path HKLM:\Software\MyCompany\design -Name product

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.

Output

...

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.

Output

...

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

...

Use the Get-Help cmdlet to view the attributes of the Destination parameter.

Output

Get-Help Move-ItemProperty -Parameter Destination

-Destination <String>

Specifies the path to the destination location.

Required? true

Position? 1

Default value None

Accept pipeline input? True (ByPropertyName)

Accept wildcard characters? false

The results show that Destination takes pipeline input only "by property
name".
Therefore, the piped object must have a property named Destination.

Use Get-Member to see the properties of the object coming from Get-Item .

PowerShell

Get-Item -Path HKLM:\Software\MyCompany\sales | Get-Member

The output shows that the item is a Microsoft.Win32.RegistryKey object that


doesn't
have a Destination property. That explains why the command failed.

The Path parameter accepts pipeline input by name or by value.

Output
Get-Help Move-ItemProperty -Parameter Path

-Path <String[]>

Specifies the path to the current location of the property. Wildcard

characters are permitted.

Required? true

Position? 0

Default value None

Accept pipeline input? True (ByPropertyName, ByValue)

Accept wildcard characters? true

To fix the command, we must specify the destination in the Move-ItemProperty


cmdlet
and use Get-Item to get the Path of the item we want to move.

For example,

PowerShell

Get-Item -Path HKLM:\Software\MyCompany\design |

Move-ItemProperty -Destination HKLM:\Software\MyCompany\sales -Name product

Intrinsic line continuation


As already discussed, a pipeline is a series of commands connected by pipeline
operators ( | ), usually written on a single line. However, for
readability, PowerShell
allows you to split the pipeline across multiple lines.
When a pipe operator is the last
token on the line, the PowerShell parser joins
the next line to current command to
continue the construction of the pipeline.

For example, the following single-line pipeline:

PowerShell

Command-1 | Command-2 | Command-3

can be written as:

PowerShell

Command-1 |

Command-2 |

Command-3

The leading spaces on the subsequent lines are not significant. The indentation
enhances readability.

See also
about_Command_Syntax
about_ForEach
about_Objects
about_Parameters
about_PSReadLine
about_PowerShell_exe
Article • 05/08/2023

Short description
Explains how to use the powershell.exe command-line interface. Displays the
command-line parameters and describes the syntax.

SYNTAX

PowerShell[.exe]

[-PSConsoleFile <file> | -Version <version>]

[-NoLogo]

[-NoExit]

[-Sta]

[-Mta]

[-NoProfile]

[-NonInteractive]

[-InputFormat {Text | XML}]

[-OutputFormat {Text | XML}]

[-WindowStyle <style>]

[-EncodedCommand <Base64EncodedCommand>]

[-ConfigurationName <string>]
[-File - | <filePath> <args>]
[-ExecutionPolicy <ExecutionPolicy>]

[-Command - | { <script-block> [-args <arg-array>] }

| { <string> [<CommandParameters>] } ]

PowerShell[.exe] -Help | -? | /?

Parameters

-Command
Executes the specified commands (and any parameters) as though they were typed
at
the PowerShell command prompt, and then exits, unless the NoExit
parameter is
specified.

The value of Command can be - , a script block, or a string. If the value


of Command is
- , the command text is read from standard input.
The Command parameter only accepts a script block for execution when it can
recognize the value passed to Command as a ScriptBlock type. This is
only possible
when running powershell.exe from another PowerShell host. The
ScriptBlock type may
be contained in an existing variable, returned from an
expression, or parsed by the
PowerShell host as a literal script block enclosed
in curly braces ( {} ), before being
passed to powershell.exe .

PowerShell

powershell -Command {Get-WinEvent -LogName security}

In cmd.exe , there is no such thing as a script block (or ScriptBlock


type), so the value
passed to Command will always be a string. You can
write a script block inside the
string, but instead of being executed it will
behave exactly as though you typed it at a
typical PowerShell prompt, printing
the contents of the script block back out to you.

A string passed to Command is still executed as PowerShell code, so the


script block
curly braces are often not required in the first place when
running from cmd.exe . To
execute an inline script block defined inside a
string, the call operator & can be used:

Windows Command Prompt

powershell.exe -Command "& {Get-WinEvent -LogName security}"

If the value of Command is a string, Command must be the last parameter


for pwsh,
because all arguments following it are interpreted as part of the
command to execute.

When called from within an existing PowerShell session, the results are
returned to the
parent shell as deserialized XML objects, not live objects. For
other shells, the results are
returned as strings.

If the value of Command is - , the command text is read from standard


input. You must
redirect standard input when using the Command parameter
with standard input. For
example:

PowerShell

@'

"in"

"hi" |

% { "$_ there" }

"out"

'@ | powershell -NoProfile -Command -

This example produces the following output:

Output

in

hi there

out

The process exit code is determined by status of the last (executed) command
within the
script block. The exit code is 0 when $? is $true or 1 when
$? is $false . If the last
command is an external program or a PowerShell
script that explicitly sets an exit code
other than 0 or 1 , that exit code
is converted to 1 for process exit code. To preserve
the specific exit code,
add exit $LASTEXITCODE to your command string or script block.

For more information, see $LASTEXITCODE in about_Automatic_Variables.

Similarly, the value 1 is returned when a script-terminating


(runspace-terminating) error,
such as a throw or -ErrorAction Stop , occurs
or when execution is interrupted with
Ctrl + C .

-ConfigurationName <string>
Specifies a configuration endpoint in which PowerShell is run. This can be any
endpoint
registered on the local machine including the default PowerShell
remoting endpoints or
a custom endpoint having specific user role capabilities.

-EncodedCommand <Base64EncodedCommand>
Accepts a base-64-encoded string version of a command. Use this parameter to
submit
commands to PowerShell that require complex quotation marks or curly
braces. The
string must be formatted using UTF-16LE character encoding.

-ExecutionPolicy <ExecutionPolicy>
Sets the default execution policy for the current session and saves it in the
$env:PSExecutionPolicyPreference environment variable. This parameter does
not
change the PowerShell execution policy that's set in the registry. For
information about
PowerShell execution policies, including a list of valid
values, see
about_Execution_Policies.
-File - | <filePath> <args>
If the value of File is - , the command text is read from standard input.
Running
powershell -File - without redirected standard input starts a regular
session. This is

the same as not specifying the File parameter at all.

If the value of File is a filepath, the script runs in the local scope
("dot-sourced"), so that
the functions and variables that the script creates
are available in the current session.
Enter the script filepath and any
parameters. File must be the last parameter in the
command. All values
typed after the File parameter are interpreted as the script filepath
and
parameters passed to that script.

Parameters passed to the script are passed as literal strings, after


interpretation by the
current shell. For example, if you are in cmd.exe and
want to pass an environment
variable value, you would use the cmd.exe
syntax: powershell.exe -File .\test.ps1 -
TestParam %windir%

In contrast, running powershell.exe -File .\test.ps1 -TestParam $env:windir


in
cmd.exe results in the script receiving the literal string $env:windir
because it has no
special meaning to the current cmd.exe shell. The
$env:windir style of environment
variable reference can be used inside a
Command parameter, since there it will be
interpreted as PowerShell code.

Similarly, if you want to execute the same command from a Batch script, you
would use
%~dp0 instead of .\ or $PSScriptRoot to represent the current
execution directory:
powershell.exe -File %~dp0test.ps1 -TestParam %windir% .
If you instead used

.\test.ps1 , PowerShell would throw an error because it


can't find the literal path
.\test.ps1

When the value of File is a filepath, File must be the last parameter
in the command
because any characters typed after the File parameter name
are interpreted as the script
filepath followed by the script parameters.

You can include the script parameters and values in the value of the File
parameter. For
example: -File .\Get-Script.ps1 -Domain Central

Typically, the switch parameters of a script are either included or omitted.


For example,
the following command uses the All parameter of the
Get-Script.ps1 script file: -File
.\Get-Script.ps1 -All

In rare cases, you might need to provide a Boolean value for a parameter.
It isn't
possible to pass an explicit boolean value for a switch parameter when
running a script
in this way. This limitation was removed in PowerShell 6
( pwsh.exe ).

7 Note

The File parameter can't support scripts using a parameter that expects
an array of
argument values. This, unfortunately, is a limitation of how a
native command gets
argument values. When you call a native executable (such
as powershell or pwsh ),
it doesn't know what to do with an array, so
it's passed as a string.

When the script file terminates with an exit command, the process exit code
is set to
the numeric argument used with the exit command. With normal
termination, the exit
code is always 0 .

For more information, see $LASTEXITCODE in about_Automatic_Variables.

-InputFormat {Text | XML}


Describes the format of data sent to PowerShell. Valid values are Text (text
strings) or
XML (serialized CLIXML format).

-Mta
Starts PowerShell using a multi-threaded apartment. This parameter is
introduced in
PowerShell 3.0. In PowerShell 2.0, multi-threaded apartment (MTA)
is the default. In
PowerShell 3.0, single-threaded apartment (STA) is the
default.

-NoExit
Doesn't exit after running startup commands.

-NonInteractive
This switch is used to create sessions that shouldn't require user input. This
is useful for
scripts that run in scheduled tasks or CI/CD pipelines. Any
attempts to use interactive
features, like Read-Host or confirmation prompts,
result in statement terminating errors
rather than hanging.

-NoLogo
Hides the copyright banner at startup.
-NoProfile
Doesn't load the PowerShell profile.

-OutputFormat {Text | XML}


Determines how output from PowerShell is formatted. Valid values are Text
(text
strings) or XML (serialized CLIXML format).

-PSConsoleFile <FilePath>
Loads the specified PowerShell console file. Enter the path and name of the
console file.
To create a console file, use the Export-Console cmdlet in
PowerShell.

-Sta
Starts PowerShell using a single-threaded apartment. In Windows PowerShell 2.0,
multi-
threaded apartment (MTA) is the default. In Windows PowerShell 3.0,
single-threaded
apartment (STA) is the default.

-Version <PowerShell Version>


Starts the specified version of PowerShell. Valid values are 2.0 and 3.0. The
version that
you specify must be installed on the system. If Windows PowerShell
3.0 is installed on
the computer, "3.0" is the default version. Otherwise,
"2.0" is the default version. For
more information, see
Installing PowerShell.

-WindowStyle <Window style>


Sets the window style for the session. Valid values are Normal , Minimized ,
Maximized ,
and Hidden .

-Help, -?, /?
Displays help for PowerShell.exe . If you are typing a PowerShell.exe
command in a
PowerShell session, prepend the command parameters with a hyphen
( - ), not a forward
slash ( / ). You can use either a hyphen or forward slash
in cmd.exe .

REMARKS
Troubleshooting note: In PowerShell 2.0, starting some programs from the
PowerShell
console fails with a LastExitCode of 0xc0000142.

EXAMPLES
PowerShell

# Create a new PowerShell session and load a saved console file

PowerShell -PSConsoleFile sqlsnapin.psc1

# Create a new PowerShell V2 session with text input, XML output, and no
logo

PowerShell -Version 2.0 -NoLogo -InputFormat text -OutputFormat XML

# Execute a PowerShell Command in a session

PowerShell -Command "Get-EventLog -LogName security"

# Run a script block in a session


PowerShell -Command {Get-EventLog -LogName security}

# An alternate way to run a command in a new session

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

about_PowerShell_Ise_exe
Article • 09/19/2022 • 2 minutes to read

Short description
Explains how to use the PowerShell_Ise.exe command-line tool.

Long description
PowerShell_Ise.exe starts a Windows PowerShell Integrated
Scripting Environment (ISE)
session. You can run it in Cmd.exe
and in Windows PowerShell.

To run PowerShell_ISE.exe, type PowerShell_ISE.exe, PowerShell_ISE,


or ISE.

Syntax

PowerShell_Ise[.exe]

PowerShell_ISE[.exe]

ISE[.exe]

[-File]<FilePath[]> [-NoProfile] [-MTA]

-Help | ? | -? | /? Displays the syntax and describes the command-line


switches.

Parameters

-File
Opens the specified files in Windows PowerShell ISE. The
parameter name ("-File") is
optional. To list more than one
file, enter one text string enclosed in quotation marks.
Use
commas to separate the file names within the string.

For example:

PowerShell_ISE -File "File1.ps1,File2.ps1,File3.xml".

Spaces between the file names are permitted in Windows PowerShell,


but might not be
interpreted correctly by other programs, such as
Cmd.exe.
You can use this parameter to open any text file, including Windows
PowerShell script
files and XML files.

-Mta
Starts Windows PowerShell ISE using a multi-threaded apartment. This
parameter is
introduced in Windows PowerShell 3.0. Single-threaded
apartment (STA) is the default.

-NoProfile
Does not run Windows PowerShell profiles. By default, Windows PowerShell
profiles are
run in every session.

This parameter is recommended when you are writing shared content, such as
functions
and scripts that will be run on systems with different profiles.
For more information, see
about_Profiles.

-Help -?, /?
Displays help for PowerShell_ISE.exe.

Examples
These commands start Windows PowerShell ISE. The commands are equivalent
and can
be used interchangeably.

PS C:> PowerShell_ISE.exe

PS C:> PowerShell_ISE

PS C:> ISE

These commands open the Get-Profile.ps1 script in Windows PowerShell ISE.


The
commands are equivalent and can be used interchangeably.

PS C:> PowerShell_ISE.exe -File .\Get-Profile.ps1

PS C:> ISE -File .\Get-Profile.ps1

PS C:> ISE .\Get-Profile.ps1

This command opens the Get-Backups.ps1 and Get-BackupInstance.ps1 scripts


in
Windows PowerShell ISE. To open more than one file, use a comma to
separate the file
names and enclose the entire file name value in quotation
marks.

PS C:> ISE -File ".\Get-Backups.ps1,Get-BackupInstance.ps1"

This command starts Windows PowerShell ISE with no profiles.

PS C:> ISE -NoProfile

This command gets help for PowerShell_ISE.exe.

PS C:> ISE -help

See also
about_PowerShell_exe
about_Windows_PowerShell_ISE
Windows PowerShell Integrated Scripting Environment (ISE)
about_Preference_Variables
Article • 03/02/2023 • 33 minutes to read

Short description
Variables that customize the behavior of PowerShell.

Long description
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 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

$InformationPreference SilentlyContinue

$LogCommandHealthEvent $False (not logged)

$LogCommandLifecycleEvent $False (not logged)

$LogEngineHealthEvent $True (logged)

$LogEngineLifecycleEvent $True (logged)

$LogProviderLifecycleEvent $True (logged)

$LogProviderHealthEvent $True (logged)

$MaximumAliasCount 4096
Variable Default Value

$MaximumDriveCount 4096

$MaximumErrorCount 256

$MaximumFunctionCount 4096

$MaximumHistoryCount 4096

$MaximumVariableCount 4096

$OFS Space character ( " " )

$OutputEncoding ASCIIEncoding object

$ProgressPreference Continue

$PSDefaultParameterValues @{} (empty hash table)

$PSEmailServer $Null (none)

$PSModuleAutoLoadingPreference All

$PSSessionApplicationName 'wsman'

$PSSessionConfigurationName 'http://schemas.microsoft.com/powershell/Microsoft.PowerShell'

$PSSessionOption PSSessionOption object

$Transcript $Null (none)

$VerbosePreference SilentlyContinue

$WarningPreference Continue

$WhatIfPreference $False

PowerShell includes the following environment variables that store user


preferences. For
more information about these environment variables, see
about_Environment_Variables.

env:PSExecutionPolicyPreference

$env:PSModulePath

7 Note

Changes to preference variable only take effect in scripts and functions if


those
scripts or functions are defined in the same scope as the scope in
which preference
was used. For more information, see about_Scopes.
Working with preference variables
This document describes each of the preference variables.

To display the current value of a specific preference variable, type the


variable's name.
For example, the following command displays the
$ConfirmPreference variable's value.

PowerShell

$ConfirmPreference

Output

High

To change a variable's value, use an assignment statement. For example, the


following
statement changes the $ConfirmPreference parameter's value to
Medium.

PowerShell

$ConfirmPreference = "Medium"

The values that you set are specific to the current PowerShell session. To make
variables
effective in all PowerShell sessions, add them to your PowerShell
profile. For more
information, see about_Profiles.

Working remotely
When you run commands on a remote computer, the remote commands are only
subject to the preferences set in the remote computer's PowerShell client. For
example,
when you run a remote command, the value of the remote computer's
$DebugPreference variable determines how PowerShell responds to debugging

messages.

For more information about remote commands, see about_Remote.

$ConfirmPreference
Determines whether PowerShell automatically prompts you for confirmation before
running a cmdlet or function.
The $ConfirmPreference variable takes one of the ConfirmImpact
enumeration values:
High, Medium, Low, or None.

Cmdlets and functions are assigned a risk of High, Medium, or Low.


When the value of
the $ConfirmPreference variable is less than or equal to
the risk assigned to a cmdlet or
function, PowerShell automatically prompts you
for confirmation before running the
cmdlet or function.

If the value of the $ConfirmPreference variable is None, PowerShell never


automatically
prompts you before running a cmdlet or function.

To change the confirming behavior for all cmdlets and functions in the session,
change
$ConfirmPreference variable's value.

To override the $ConfirmPreference for a single command, use a cmdlet's or


function's
Confirm parameter. To request confirmation, use -Confirm . To
suppress confirmation,
use -Confirm:$false .

Valid values of $ConfirmPreference :

None: PowerShell doesn't prompt automatically. To request confirmation of


a
particular command, use the Confirm parameter of the cmdlet or
function.
Low: PowerShell prompts for confirmation before running cmdlets or
functions
with a low, medium, or high risk.
Medium: PowerShell prompts for confirmation before running cmdlets or
functions with a medium, or high risk.
High: PowerShell prompts for confirmation before running cmdlets or
functions
with a high risk.

Detailed explanation
PowerShell can automatically prompt you for confirmation before doing an
action. For
example, when cmdlet or function significantly affects the system
to delete data or use a
significant amount of system resources.

PowerShell

Remove-Item -Path C:\file.txt

Output

Confirm

Are you sure you want to perform this action?

Performing operation "Remove File" on Target "C:\file.txt".

[Y] Yes [A] Yes to All [N] No [L] No to All [?] Help (default is "Y"):

The estimate of the risk is an attribute of the cmdlet or function known as its
ConfirmImpact. Users can't change it.

Cmdlets and functions that might pose a risk to the system have a Confirm
parameter
that you can use to request or suppress confirmation for a single
command.

Because most cmdlets and functions use the default risk value,
ConfirmImpact, 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 $ConfirmPreference variable's default
value, High.
The High value only confirms high-risk cmdlets and
functions. Since most cmdlets and
functions are medium risk, they aren't
automatically confirmed and Remove-Item deletes
the file. Adding -Confirm
to the command prompts the user for confirmation.

PowerShell

$ConfirmPreference

Output

High

PowerShell

Remove-Item -Path C:\temp1.txt

Use -Confirm to request confirmation.

PowerShell

Remove-Item -Path C:\temp2.txt -Confirm

Output
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"):

The following example shows the effect of changing the value of


$ConfirmPreference to
Medium. Because most cmdlets and function are
medium risk, they're automatically
confirmed. To suppress the confirmation
prompt for a single command, use the Confirm
parameter with a value of
$false .

PowerShell

$ConfirmPreference = "Medium"

Remove-Item -Path C:\temp2.txt

Output

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"):

PowerShell

Remove-Item -Path C:\temp3.txt -Confirm:$false

$DebugPreference
Determines how PowerShell responds to debugging messages generated by a script,
cmdlet or provider, or by a Write-Debug command at the command line.

The $DebugPreference variable takes one of the ActionPreference


enumeration values:
SilentlyContinue, Stop, Continue, Inquire,
Ignore, Suspend, or Break.

Some cmdlets display debugging messages, which are typically technical messages
designed for programmers and technical support professionals. By default,
debugging
messages aren't displayed, but you can display debugging messages by
changing the
value of $DebugPreference .
You can use the Debug common parameter of a cmdlet to display or hide the
debugging messages for a specific command. For more information, see
about_CommonParameters.

The valid values are as follows:

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.
Adding the Debug common parameter to a command, when the
command is
configured to generate a debugging message, changes the value of
the
$DebugPreference variable to Inquire.

Continue: Displays the debug message and continues with execution.


SilentlyContinue: (Default) No effect. The debug message isn't 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 messages generated by
cmdlets and scripts. The
examples show the Debug parameter, which displays
or hides the debugging messages
related to a single command.

This example shows the effect of the $DebugPreference variable's default


value,
SilentlyContinue. By default, the Write-Debug cmdlet's debug
message isn't displayed
and processing continues. When the Debug parameter
is used, it overrides the
preference for a single command. The user is prompted
for confirmation.

PowerShell

$DebugPreference

Output

SilentlyContinue

PowerShell

Write-Debug -Message "Hello, World"

PowerShell

Write-Debug -Message "Hello, World" -Debug

Output

DEBUG: Hello, World

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 $DebugPreference with the Continue


value. The debug
message is displayed and the command continues to process.

PowerShell

$DebugPreference = "Continue"

Write-Debug -Message "Hello, World"

Output

DEBUG: Hello, World

This example uses the Debug parameter with a value of $false to suppress
the
message for a single command. The debug message isn't displayed.

PowerShell

Write-Debug -Message "Hello, World" -Debug:$false

This example shows the effect of $DebugPreference being set to the Stop
value. The
debug message is displayed and the command is stopped.

PowerShell

$DebugPreference = "Stop"

Write-Debug -Message "Hello, World"

Output

DEBUG: Hello, World

Write-Debug : The running command stopped because the preference variable

"DebugPreference" or common parameter is set to Stop: Hello, World

At line:1 char:1

+ Write-Debug -Message "Hello, World"

This example uses the Debug parameter with a value of $false to suppress
the
message for a single command. The debug message isn't displayed and
processing isn't
stopped.

PowerShell

Write-Debug -Message "Hello, World" -Debug:$false

This example shows the effect of $DebugPreference being set to the


Inquire value. The
debug message is displayed and the user is prompted for
confirmation.

PowerShell

$DebugPreference = "Inquire"

Write-Debug -Message "Hello, World"

Output

DEBUG: Hello, World

Confirm

Continue with this operation?

[Y] Yes [A] Yes to All [H] Halt Command [S] Suspend

[?] Help (default is "Y"):

This example uses the Debug parameter with a value of $false to suppress
the
message for a single command. The debug message isn't displayed and
processing
continues.

PowerShell

Write-Debug -Message "Hello, World" -Debug:$false

$ErrorActionPreference
Determines how PowerShell responds to a non-terminating error, an error that
doesn't
stop the cmdlet processing. For example, at the command line or in a
script, cmdlet, or
provider, such as the errors generated by the Write-Error
cmdlet.
The $ErrorActionPreference variable takes one of the
ActionPreference
enumeration
values: SilentlyContinue, Stop, Continue, Inquire,
Ignore, or Suspend.

You can use a cmdlet's ErrorAction common parameter to override the


preference for a
specific command.

The valid values are as follows:

Continue: (Default) Displays the error message and continues executing.


Ignore: Suppresses the error message and continues to execute the
command. The
Ignore value is intended for per-command use, not for use as
saved preference.
Ignore isn't a valid value for the
$ErrorActionPreference variable.
Inquire: Displays the error message and asks you whether you want to
continue.
SilentlyContinue: No effect. The error message isn't displayed and
execution
continues without interruption.
Stop: Displays the error message and stops executing. In addition to the
error
generated, the Stop value generates an ActionPreferenceStopException
object to
the error stream.
Suspend: Automatically suspends a workflow job to allow for further
investigation.
After investigation, the workflow can be resumed. The
Suspend value is intended
for per-command use, not for use as saved
preference. Suspend isn't a valid value
for the $ErrorActionPreference
variable.

$ErrorActionPreference and the ErrorAction parameter don't affect how


PowerShell

responds to terminating errors that stop cmdlet processing. For more


information about
the ErrorAction common parameter, see
about_CommonParameters.

Examples
These examples show the effect of the different values of the
$ErrorActionPreference
variable. The ErrorAction parameter is used to
override the $ErrorActionPreference
value.

This example shows the $ErrorActionPreference default value, Continue. A


non-
terminating error is generated. The message is displayed and processing
continues.

PowerShell

# Change the ErrorActionPreference to 'Continue'

$ErrorActionPreference = 'Continue'

# Generate a non-terminating error and continue processing the script.

Write-Error -Message 'Test Error' ; Write-Host 'Hello World'

Output

Write-Error -Message 'Test Error' ; Write-Host 'Hello World' : Test Error

+ CategoryInfo : NotSpecified: (:) [Write-Error],


WriteErrorException

+ FullyQualifiedErrorId :
Microsoft.PowerShell.Commands.WriteErrorException

Hello World

This example shows the $ErrorActionPreference default value, Inquire. An


error is
generated and a prompt for action is shown.

PowerShell

# Change the ErrorActionPreference to 'Inquire'

$ErrorActionPreference = 'Inquire'

Write-Error -Message 'Test Error' ; Write-Host 'Hello World'

Output

Confirm

Test Error

[Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is
"Y"):

This example shows the $ErrorActionPreference set to SilentlyContinue.


The error
message is suppressed.

PowerShell

# Change the ErrorActionPreference to 'SilentlyContinue'

$ErrorActionPreference = 'SilentlyContinue'

# Generate an error message

Write-Error -Message 'Test Error' ; Write-Host 'Hello World'

# Error message is suppressed and script continues processing

Output

Hello World

This example shows the $ErrorActionPreference set to Stop. It also shows


the extra
object generated to the $Error variable.

PowerShell
# Change the ErrorActionPreference to 'Stop'

$ErrorActionPreference = 'Stop'

# Error message is is generated and script stops processing

Write-Error -Message 'Test Error' ; Write-Host 'Hello World'

# Show the ActionPreferenceStopException and the error generated

$Error[0]

$Error[1]

Output

Write-Error -Message 'Test Error' ; Write-Host 'Hello World' : Test Error

At line:1 char:1

+ Write-Error -Message 'Test Error' ; Write-Host 'Hello World'

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : NotSpecified: (:) [Write-Error],


WriteErrorException

+ FullyQualifiedErrorId :
Microsoft.PowerShell.Commands.WriteErrorException

The running command stopped because the preference variable


"ErrorActionPreference"

or common parameter is set to Stop: Test Error

Write-Error -Message 'Test Error' ; Write-Host 'Hello World' : Test Error

At line:1 char:1

+ Write-Error -Message 'Test Error' ; Write-Host 'Hello World'

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : NotSpecified: (:) [Write-Error],


WriteErrorException

+ FullyQualifiedErrorId :
Microsoft.PowerShell.Commands.WriteErrorException

$ErrorView
Determines the display format of error messages in PowerShell.

The $ErrorView variable takes one of the ErrorView enumeration


values: NormalView or
CategoryView.

The valid values are as follows:

NormalView: A detailed view designed for most users. Consists of a


description of
the error and the name of the object involved in the error.

CategoryView: A succinct, structured view designed for production


environments.
The format is as follows:
{Category}: ({TargetName}:{TargetType}):[{Activity}], {Reason}

For more information about the fields in CategoryView, see


ErrorCategoryInfo class.

Examples
This example shows how an error appears when the value of $ErrorView is the
default,
NormalView. Get-ChildItem is used to find a non-existent file.

PowerShell

Get-ChildItem -Path C:\nofile.txt

Output

Get-ChildItem : Cannot find path 'C:\nofile.txt' because it does not exist.

At line:1 char:1

+ Get-ChildItem -Path C:\nofile.txt

This example shows how the same error appears when the value of $ErrorView is
changed to CategoryView.

PowerShell

$ErrorView = "CategoryView"

Get-ChildItem -Path C:\nofile.txt

Output

ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem],


ItemNotFoundException

This example demonstrates that the value of $ErrorView only affects the error
display. It
doesn't change the structure of the error object that's stored in
the $Error automatic
variable. For information about the $Error automatic
variable, see
about_automatic_variables.

The following command takes the ErrorRecord object associated with the most
recent
error in the error array, element 0, and formats the properties of
object in a list.

PowerShell

$Error[0] | Format-List -Property * -Force

Output

PSMessageDetails :

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, UInt32

depth, CmdletProviderContext context)

at System.Management.Automation.ChildItemCmdlet

ProviderIntrinsics.Get(String path, Boolean

recurse, UInt32 depth, 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

ScriptStackTrace : at <ScriptBlock>, <No file>: line 1

PipelineIterationInfo : {0, 1}

$FormatEnumerationLimit
Determines how many enumerated items are included in a display. This variable
doesn't
affect the underlying objects, only the display. When the value of
$FormatEnumerationLimit is fewer than the number of enumerated items,
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 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 the services,
and then sends the results through the
pipeline to the Group-Object cmdlet,
which groups the results by the service status.

The result is a table that lists the status in the Name column, and the
processes in the
Group column. To change the column labels, use a hash
table, see about_Hash_Tables.
For more information, see the examples in
Format-Table.

Find the current value of $FormatEnumerationLimit .

PowerShell

$FormatEnumerationLimit

Output

List all services grouped by Status. There are a maximum of four services
listed in the
Group column for each status because
$FormatEnumerationLimit has a value of 4.

PowerShell

Get-Service | Group-Object -Property Status

Output

Count Name Group

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

60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv...}

41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart...}

To increase the number of items listed, increase the value of


$FormatEnumerationLimit to
1000. Use Get-Service and Group-Object to
display the services.

PowerShell

$FormatEnumerationLimit = 1000

Get-Service | Group-Object -Property Status

Output

Count Name Group

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

60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS,


CcmExec...

41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser,


CiSvc...

Use Format-Table with the Wrap parameter to display the list of services.

PowerShell

Get-Service | Group-Object -Property Status | Format-Table -Wrap

Output

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,

SCardSvr, SwPrv, SysmonLog, TlntSvr, upnphost, UPS, VSS,

WmdmPmSN, Wmi, WmiApSrv, xmlprov}

$InformationPreference
The $InformationPreference variable lets you set information stream
preferences that
you want displayed to users. Specifically, informational
messages that you added to
commands or scripts by adding the
Write-Information cmdlet. If the InformationAction
parameter is used,
its value overrides the value of the $InformationPreference variable.
Write-Information was introduced in PowerShell 5.0.

The $InformationPreference variable takes one of the


ActionPreference
enumeration
values: SilentlyContinue, Stop, Continue, Inquire,
Ignore, or Suspend.
The valid values are as follows:

Stop: Stops a command or script at an occurrence of the


Write-Information
command.
Inquire: Displays the informational message that you specify in a
Write-
Information command, then asks whether you want to continue.

Continue: Displays the informational message, and continues running.


Suspend: Automatically suspends a workflow job after a
Write-Information
command is carried out, to allow users to see the
messages before continuing. The
workflow can be resumed at the user's
discretion.
SilentlyContinue: (Default) No effect. The informational messages aren't
displayed,
and the script continues without interruption.

$Log*Event
The Log*Event preference variables determine which types of events are
written to the
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. The default is $false (not logged).


$LogCommandLifecycleEvent : Logs the starting and stopping of commands and

command pipelines and security exceptions in command discovery. The default


is
$false (not logged).

$LogEngineHealthEvent : Logs errors and failures of sessions. The default is


$true

(logged).
$LogEngineLifecycleEvent : Logs the opening and closing of sessions. The
default is

$true (logged).
$LogProviderHealthEvent : Logs provider errors, such as read and write
errors,

lookup errors, and invocation errors. The default is $true


(logged).
$LogProviderLifecycleEvent : Logs adding and removing of PowerShell
providers.
The default is $true (logged). For information about PowerShell
providers, see
about_Providers.

To enable a Log*Event, type the variable with a value of $true , for


example:

PowerShell
$LogCommandLifeCycleEvent = $true

To disable an event type, type the variable with a value of $false , for
example:

PowerShell

$LogCommandLifeCycleEvent = $false

The events that you enable are effective only for the current PowerShell
console. To
apply the configuration to all consoles, save the variable settings
in your PowerShell
profile. For more information, see about_Profiles.

$MaximumAliasCount
Determines how many aliases are permitted in a PowerShell session. The default
value is
4096 and that should be enough for most uses. You can adjust
$MaximumAliasCount to
meet your needs.

Valid values: 1024 - 32768 ( Int32 )

Default: 4096

To count the aliases on your system, type:

PowerShell

(Get-Alias).count

$MaximumDriveCount
Determines how many PowerShell drives are permitted in a given session. For
example,
file system drives and data stores that are exposed by 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:

PowerShell
(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.
$Error contains an array of error record objects. The most recent
error is the first object
in the array, $Error[0] .

To count the errors on your system, use the $Error array's Count
property.

PowerShell

$Error.count

To display a specific error, use the [0] array notation to see the most
recent error.

PowerShell

$Error[0]

To display the oldest retained error, type:

PowerShell

$Error[($Error.Count -1]

The Force parameter overrides the special formatting of ErrorRecord


objects and reverts
to the conventional format. To display the properties of
the ErrorRecord object, type the
following command:

PowerShell

$Error[0] | Format-List -Property * -Force

In this example, $Error.Count displays the number of errors. To delete all


errors from
the error history, use the Clear method of the error array.

PowerShell

$Error.Count

Output

17

PowerShell

$Error.Clear()

$Error.Count

Output

To find all properties and methods of an error array, use the Get-Member
cmdlet with its
InputObject parameter. When you use the InputObject
parameter, Get-Member displays
the properties and methods of the collection.

PowerShell

Get-Member -InputObject $Error

When you pipe a collection of objects to Get-Member , Get-Member displays


the properties
and methods of the objects in the collection.

PowerShell

$Error | Get-Member

$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 PowerShell Function: drive that
is exposed
by the PowerShell Function provider. For more information about
the Function
provider, about_Function_Provider.

To list the functions in the current session, type:

PowerShell

Get-ChildItem Function:

To count the functions in the current session, type:

PowerShell

(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: 4096

To determine the number of commands current saved in the command history, type:

PowerShell

(Get-History).Count

To see the commands saved in your session history, use the Get-History
cmdlet. For
more information, see 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
PowerShell Variable: drive and the PowerShell Variable
provider. For information, see
about_Variable_Provider.

To find the current number of variables on the system, type:

PowerShell

(Get-Variable).Count

$OFS
The Output Field Separator (OFS) specifies the character that separates the
elements of
an array that's converted to a string.

Valid values: Any string.

Default: Space

By default, the $OFS variable doesn't exist and the output file separator is
a space, but
you can add this variable and set it to any string. You can change
the value of $OFS in
your session, by typing $OFS="<value>" .

7 Note

If you're expecting the default value of a space ( " " ) in your script,
module, or
configuration output, be careful that the $OFS default value
hasn't been changed
elsewhere in your code.

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.

PowerShell

$array = 1,2,3,4

[string]$array

Output

1 2 3 4

To change the separator, add the $OFS variable by assigning a value to it.
The variable
must be named $OFS .

PowerShell

$OFS = "+"

[string]$array

Output

1+2+3+4

To restore the default behavior, you can assign a space ( " " ) to the value of
$OFS or
delete the variable. The following commands delete the variable and
then verify that the
separator is a space.

PowerShell

Remove-Variable OFS

[string]$array

Output

1 2 3 4

$OutputEncoding
Determines the character encoding method that PowerShell uses when it sends
text to
other applications.

For example, if an application returns Unicode strings to PowerShell, you might


need to
change the value to UnicodeEncoding to send the characters
correctly.

The valid values are as follows: Objects derived from an Encoding class, such
as
ASCIIEncoding,
UTF7Encoding,
UTF8Encoding,
UTF32Encoding, and
UnicodeEncoding.

Default: ASCIIEncoding object.


Examples
This example shows how to make the Windows findstr.exe command work in
PowerShell on a computer that's 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.

PowerShell

$OutputEncoding.EncodingName

In this example, a findstr.exe command is used to search for two Chinese


characters
that are present in the Test.txt file. When this findstr.exe
command is run in the
Windows Command Prompt ( cmd.exe ), findstr.exe finds
the characters in the text file.
However, when you run the same findstr.exe
command in PowerShell, the characters
aren't found because the PowerShell sends
them to findstr.exe in ASCII text, instead of
in Unicode text.

PowerShell

findstr <Unicode-characters>

To make the command work in PowerShell, set the value of $OutputEncoding to


the
value of the OutputEncoding property of the console, that's based on
the locale
selected for Windows. Because OutputEncoding is a static
property of the console, use
double-colons ( :: ) in the command.

PowerShell

$OutputEncoding = [console]::OutputEncoding

$OutputEncoding.EncodingName

Output

OEM United States

After the encoding change, the findstr.exe command finds the Unicode
characters.

PowerShell
findstr <Unicode-characters>

Output

test.txt: <Unicode-characters>

$ProgressPreference
Determines how 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 show a command's status.

The $ProgressPreference variable takes one of the ActionPreference


enumeration
values: SilentlyContinue, Stop, Continue, Inquire,
Ignore, or Suspend.

The valid values are as follows:

Stop: Doesn't display the progress bar. Instead, it displays an error


message and
stops executing.
Inquire: Doesn't display the progress bar. Prompts for permission to
continue. If
you reply with Y or A , it displays the progress bar.
Continue: (Default) Displays the progress bar and continues with
execution.
SilentlyContinue: Executes the command, but doesn't display the progress
bar.

$PSDefaultParameterValues
Specifies default values for the parameters of cmdlets and advanced functions.
The
value of $PSDefaultParameterValues is a hash table where the key consists
of the cmdlet
name and parameter name separated by a colon ( : ). The value is
a custom default value
that you specify.

$PSDefaultParameterValues was introduced in PowerShell 3.0.

For more information about this preference variable, see


about_Parameters_Default_Values.

$PSEmailServer
Specifies the default email server that's used to send email messages. This
preference
variable is used by cmdlets that send email, such as the
Send-MailMessage cmdlet.
$PSModuleAutoloadingPreference
Enables and disables automatic importing of modules in the session. All is
the default.
To import a module, get or use any command in the module. For
example, use Get-
Command . The $PSModuleAutoloadingPreference variable does
not exist by default. The
default behavior when the variable isn't defined is
the same as
$PSModuleAutoloadingPreference = 'All' .

Regardless of the variable's value, you can use Import-Module to import a


module.

The $PSModuleAutoloadingPreference variable takes one of the


PSModuleAutoLoadingPreference enumeration values: None,
ModuleQualified, or All.

Valid values are:

All: Modules are imported automatically on first-use.


ModuleQualified: Modules are imported automatically only when a user uses
the
module-qualified name of a command in the module. For example, if the
user
types MyModule\MyCommand , PowerShell imports the MyModule module.
None: Automatic importing of modules is disabled in the session. To
import a
module, use the Import-Module cmdlet.

For more information about automatic importing of modules, see


about_Modules.

$PSSessionApplicationName
Specifies the default application name for a remote command that uses Web
Services
for Management (WS-Management) technology. For more information, see
About
Windows Remote Management.

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 doesn't 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 parameter's value 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.

The $PSSessionApplicationName preference variable is set on the local


computer, but it
specifies a listener on the remote computer. If the
application name that you specify
doesn't exist on the remote computer, the
command to establish the session fails.

$PSSessionConfigurationName
Specifies the default session configuration that's used to create new sessions
in the
current session.

This preference variable is set on the local computer, but it specifies a


session
configuration that's 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 doesn't,
the command to create a session that uses the session
configuration fails.

This preference variable doesn't 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.

The $PSSessionOption variable contains a PSSessionOption object. For more


information, see System.Management.Automation.Remoting.PSSessionOption.
Each
property of the object represents a session option. For example, the
NoCompression
property turns of data compression during the session.

By default, the $PSSessionOption variable contains a PSSessionOption


object with the
default values for all options, as shown below.

Output

MaximumConnectionRedirectionCount : 5

NoCompression : False

NoMachineProfile : False

ProxyAccessType : None

ProxyAuthentication : Negotiate

ProxyCredential :

SkipCACheck : False

SkipCNCheck : False

SkipRevocationCheck : False

OperationTimeout : 00:03:00

NoEncryption : False

UseUTF16 : False

IncludePortInSPN : False

OutputBufferingMode : None

Culture :

UICulture :

MaximumReceivedDataSizePerCommand :

MaximumReceivedObjectSize : 209715200

ApplicationArguments :

OpenTimeout : 00:03:00

CancelTimeout : 00:01:00

IdleTimeout : -00:00:00.0010000

For descriptions of these options and more information, see


New-PSSessionOption. For
more information about remote commands and
sessions, see about_Remote and
about_PSSessions.

To change the value of the $PSSessionOption preference variable, use the


New-
PSSessionOption cmdlet to create a PSSessionOption object with the
option values you
prefer. Save the output in a variable called
$PSSessionOption .

PowerShell

$PSSessionOption = New-PSSessionOption -NoCompression

To use the $PSSessionOption preference variable in every PowerShell session,


add a New-
PSSessionOption command that creates the $PSSessionOption
variable to your
PowerShell profile. For more information, see
about_Profiles.

You can set custom options for a particular remote session. The options that
you set
take precedence over the system defaults and the value of the
$PSSessionOption
preference variable.

To set custom session options, use the New-PSSessionOption cmdlet to create a


PSSessionOption object. Then, use the PSSessionOption object as the
value of the
SessionOption parameter in cmdlets that create a session, such
as New-PSSession ,
Enter-PSSession , and Invoke-Command .

$Transcript
Used by Start-Transcript to specify the name and location of the transcript
file. If you
don't specify a value for the Path parameter,
Start-Transcript uses the path in the
value of the $Transcript global
variable. If you haven't created this variable, Start-
Transcript stores the
transcripts in the $HOME\My Documents directory as

\PowerShell_transcript.<time-stamp>.txt files.

$VerbosePreference
Determines how PowerShell responds to verbose messages generated by a script,
cmdlet, or provider, such as the messages generated by the Write-Verbose
cmdlet.
Verbose messages describe the actions performed to execute a command.

By default, verbose messages aren't displayed, but you can change this behavior
by
changing the value of $VerbosePreference .

The $VerbosePreference variable takes one of the ActionPreference


enumeration values:
SilentlyContinue, Stop, Continue, Inquire,
Ignore, or Suspend.

The valid values are as follows:

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: (Default) Doesn't display the verbose message. Continues
executing.

You can use the Verbose common parameter of a cmdlet to display or hide the
verbose
messages for a specific command. For more information, see
about_CommonParameters.

Examples
These examples show the effect of the different values of $VerbosePreference
and the
Verbose parameter to override the preference value.

This example shows the effect of the SilentlyContinue value, that's the
default. The
command uses the Message parameter, but doesn't write a
message to the PowerShell
console.

PowerShell

Write-Verbose -Message "Verbose message test."

When the Verbose parameter is used, the message is written.

PowerShell

Write-Verbose -Message "Verbose message test." -Verbose

Output

VERBOSE: Verbose message test.

This example shows the effect of the Continue value. The


$VerbosePreference variable is
set to Continue and the message is
displayed.

PowerShell

$VerbosePreference = "Continue"

Write-Verbose -Message "Verbose message test."

Output

VERBOSE: Verbose message test.

This example uses the Verbose parameter with a value of $false that
overrides the
Continue value. The message isn't displayed.

PowerShell

Write-Verbose -Message "Verbose message test." -Verbose:$false

This example shows the effect of the Stop value. The $VerbosePreference
variable is set
to Stop and the message is displayed. The command is
stopped.

PowerShell

$VerbosePreference = "Stop"

Write-Verbose -Message "Verbose message test."

Output

VERBOSE: Verbose message test.

Write-Verbose : The running command stopped because the preference variable

"VerbosePreference" or common parameter is set to Stop: Verbose message


test.

At line:1 char:1

+ Write-Verbose -Message "Verbose message test."

This example uses the Verbose parameter with a value of $false that
overrides the Stop
value. The message isn't displayed.

PowerShell

Write-Verbose -Message "Verbose message test." -Verbose:$false

This example shows the effect of the Inquire value. The


$VerbosePreference variable is
set to Inquire. The message is displayed
and the user is prompted for confirmation.

PowerShell

$VerbosePreference = "Inquire"

Write-Verbose -Message "Verbose message test."

Output

VERBOSE: Verbose message test.

Confirm

Continue with this operation?

[Y] Yes [A] Yes to All [H] Halt Command [S] Suspend

[?] Help (default is "Y"):

This example uses the Verbose parameter with a value of $false that
overrides the
Inquire value. The user isn't prompted and the message isn't
displayed.

PowerShell

Write-Verbose -Message "Verbose message test." -Verbose:$false

$WarningPreference
Determines how 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 .

The $WarningPreference variable takes one of the ActionPreference


enumeration values:
SilentlyContinue, Stop, Continue, Inquire,
Ignore, or Suspend.

The valid values are as follows:

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: (Default) Displays the warning message and then continues
executing.
SilentlyContinue: Doesn't display the warning message. Continues
executing.

You can use the WarningAction common parameter of a cmdlet to determine how
PowerShell responds to warnings from a particular command. For more
information, see
about_CommonParameters.

Examples
These examples show the effect of the different values of $WarningPreference .
The
WarningAction parameter overrides the preference value.

This example shows the effect of the default value, Continue.

PowerShell
$m = "This action can delete data."

Write-Warning -Message $m

Output

WARNING: This action can delete data.

This example uses the WarningAction parameter with the value


SilentlyContinue to
suppress the warning. The message isn't displayed.

PowerShell

$m = "This action can delete data."

Write-Warning -Message $m -WarningAction SilentlyContinue

This example changes the $WarningPreference variable to the


SilentlyContinue value.
The message isn't displayed.

PowerShell

$WarningPreference = "SilentlyContinue"

$m = "This action can delete data."

Write-Warning -Message $m

This example uses the WarningAction parameter to stop when a warning is


generated.

PowerShell

$m = "This action can delete data."

Write-Warning -Message $m -WarningAction Stop

Output

WARNING: This action can delete data.

Write-Warning : The running command stopped because the preference variable

"WarningPreference" or common parameter is set to Stop:

This action can delete data.

At line:1 char:1

+ Write-Warning -Message $m -WarningAction Stop

This example changes the $WarningPreference variable to the Inquire


value. The user is
prompted for confirmation.

PowerShell
$WarningPreference = "Inquire"

$m = "This action can delete data."

Write-Warning -Message $m

Output

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"):

This example uses the WarningAction parameter with the value


SilentlyContinue. The
command continues to execute and no message is
displayed.

PowerShell

$m = "This action can delete data."

Write-Warning -Message $m -WarningAction SilentlyContinue

This example changes the $WarningPreference value to Stop.

PowerShell

$WarningPreference = "Stop"

$m = "This action can delete data."

Write-Warning -Message $m

Output

WARNING: This action can delete data.

Write-Warning : The running command stopped because the preference variable

"WarningPreference" or common parameter is set to Stop:

This action can delete data.

At line:1 char:1

+ Write-Warning -Message $m

This example uses the WarningAction with the Inquire value. The user is
prompted
when a warning occurs.

PowerShell

$m = "This action can delete data."

Write-Warning -Message $m -WarningAction Inquire

Output

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"):

$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
doesn't execute the command.

The valid values are as follows:

False (0, not enabled): (Default) WhatIf isn't automatically


enabled. To enable it
manually, use the cmdlet's WhatIf parameter.
True (1, enabled): WhatIf is automatically enabled on any command
that supports
it. Users can use the WhatIf parameter with a value of
False to disable it manually,
such as -WhatIf:$false .

Examples
These examples show the effect of the different values of $WhatIfPreference .
They show
how to use the WhatIf parameter to override the preference value
for a specific
command.

This example shows the effect of the $WhatIfPreference variable set to the
default value,
False. Use Get-ChildItem to verify that the file exists.
Remove-Item deletes the file. After
the file is deleted, you can verify the
deletion with Get-ChildItem .

PowerShell

Get-ChildItem -Path .\test.txt

Remove-Item -Path ./test.txt

Output

Directory: C:\Test

Mode LastWriteTime Length Name

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

-a--- 9/13/2019 10:53 10 test.txt

PowerShell

Get-ChildItem -Path .\test.txt

Output

Get-ChildItem : Cannot find path 'C:\Test\test.txt' because it does not


exist.

At line:1 char:1

+ Get-ChildItem -File test.txt

This example shows the effect of using the WhatIf parameter when the value
of
$WhatIfPreference is False.

Verify that the file exists.

PowerShell

Get-ChildItem -Path .\test2.txt

Output

Directory: C:\Test

Mode LastWriteTime Length Name

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

-a--- 2/28/2019 17:06 12 test2.txt

Use the WhatIf parameter to determine the result of attempting to delete


the file.

PowerShell

Remove-Item -Path .\test2.txt -WhatIf

Output

What if: Performing the operation "Remove File" on target


"C:\Test\test2.txt".

Verify that the file wasn't deleted.


PowerShell

Get-ChildItem -Path .\test2.txt

Output

Directory: C:\Test

Mode LastWriteTime Length Name

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

-a--- 2/28/2019 17:06 12 test2.txt

This example shows the effect of the $WhatIfPreference variable set to the
value, True.
When you use Remove-Item to delete a file, the file's path
is displayed, but the file isn't
deleted.

Attempt to delete a file. A message is displayed about what would happen if


Remove-
Item was run, but the file isn't deleted.

PowerShell

$WhatIfPreference = "True"

Remove-Item -Path .\test2.txt

Output

What if: Performing the operation "Remove File" on target


"C:\Test\test2.txt".

Use Get-ChildItem to verify that the file wasn't deleted.

PowerShell

Get-ChildItem -Path .\test2.txt

Output

Directory: C:\Test

Mode LastWriteTime Length Name

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

-a--- 2/28/2019 17:06 12 test2.txt

This example shows how to delete a file when the value of $WhatIfPreference
is True. It
uses the WhatIf parameter with a value of $false . Use
Get-ChildItem to verify the file
was deleted.

PowerShell

Remove-Item -Path .\test2.txt -WhatIf:$false

Get-ChildItem -Path .\test2.txt

Output

Get-ChildItem : Cannot find path 'C:\Test\test2.txt' because it does not


exist.

At line:1 char:1

+ Get-ChildItem -Path .\test2.txt

The following are examples of the Get-Process cmdlet that doesn't support
WhatIf and
Stop-Process that does support WhatIf. The
$WhatIfPreference variable's value is True.

Get-Process doesn't support WhatIf. When the command is executed, it


displays the
Winword process.

PowerShell

Get-Process -Name Winword

Output

NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName

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

130 119.84 173.38 8.39 15024 4 WINWORD

Stop-Process does support WhatIf. The Winword process isn't stopped.

PowerShell

Stop-Process -Name Winword

Output

What if: Performing the operation "Stop-Process" on target "WINWORD


(15024)".

You can override the Stop-Process WhatIf behavior using the WhatIf
parameter with a
value of $false . The Winword process is stopped.

PowerShell

Stop-Process -Name Winword -WhatIf:$false

To verify that the Winword process was stopped, use Get-Process .

PowerShell

Get-Process -Name Winword

Output

Get-Process : Cannot find a process with the name "Winword".

Verify the process name and call the cmdlet again.

At line:1 char:1

+ Get-Process -Name Winword

See also
about_automatic_variables
about_CommonParameters
about_Environment_Variables
about_Profiles
about_Remote
about_Scopes
about_Variables
about_Profiles
Article • 04/14/2023

Short description
Describes how to create and use a PowerShell profile.

Long description
You can create a PowerShell profile to customize your environment and add
session-
specific elements to every PowerShell session that you start.

A PowerShell profile is a script that runs when PowerShell starts. You can use
the profile
as a startup script to customize your environment. You can add
commands, aliases,
functions, variables, modules, PowerShell drives and more.
You can also add other
session-specific elements to your profile so they're
available in every session without
having to import or re-create them.

PowerShell supports several profiles for users and host programs. However, it
doesn't
create the profiles for you.

Profile types and locations


PowerShell supports several profile files that are scoped to users and
PowerShell hosts.
You can have any or all of these profiles on your computer.

For example, the PowerShell console supports the following basic profile files.
The
profiles are listed in order that they're executed.

All Users, All Hosts - $PSHOME\Profile.ps1


All Users, Current Host - $PSHOME\Microsoft.PowerShell_profile.ps1
Current User, All Hosts - $HOME\Documents\WindowsPowerShell\Profile.ps1
Current user, Current Host -
$HOME\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

The profile scripts are executed in the order listed. This means that changes
made in the
AllUsersAllHosts profile can be overridden by any of the other
profile scripts. The
CurrentUserCurrentHost profile always runs last. In
PowerShell Help, the
CurrentUserCurrentHost profile is the profile most
often referred to as your PowerShell
profile.
Other programs that host PowerShell can support their own profiles. For
example, Visual
Studio Code (VS Code) supports the following host-specific
profiles.

All users, Current Host - $PSHOME\Microsoft.VSCode_profile.ps1


Current user, Current Host -
$HOME\Documents\PowerShell\Microsoft.VSCode_profile.ps1

The profile paths include the following variables:

The $PSHOME variable stores the installation directory for PowerShell


The $HOME variable stores the current user's home directory

7 Note

In Windows, the location of the Documents folder can be changed by folder


redirection or OneDrive. We don't recommend redirecting the Documents folder
to
a network share or including it in OneDrive. Redirecting the folder can
cause
modules to fail to load and create errors in your profile scripts.

The $PROFILE variable


The $PROFILE automatic variable stores the paths to the 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.

Current User, Current Host - $PROFILE


Current User, Current Host - $PROFILE.CurrentUserCurrentHost
Current User, All Hosts - $PROFILE.CurrentUserAllHosts
All Users, Current Host - $PROFILE.AllUsersCurrentHost
All Users, All Hosts - $PROFILE.AllUsersAllHosts

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 PowerShell
host application that you use.

To see the current values of the $PROFILE variable, type:

PowerShell

$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:

PowerShell

notepad $PROFILE

The following command determines whether an "All Users, All Hosts" profile has
been
created on the local computer:

PowerShell

Test-Path -Path $PROFILE.AllUsersAllHosts

How to create a profile


To create a PowerShell profile, use the following command format:

PowerShell

if (!(Test-Path -Path <profile-name>)) {

New-Item -ItemType File -Path <profile-name> -Force

For example, to create a profile for the current user in the current PowerShell
host
application, use the following command:

PowerShell

if (!(Test-Path -Path $PROFILE)) {

New-Item -ItemType File -Path $PROFILE -Force

In this command, the if statement prevents you from overwriting an existing


profile.
Replace the value of the $PROFILE variable with the path to the
profile file that you want
to create.

7 Note

To create "All Users" profiles in Windows Vista and later versions of


Windows, start
PowerShell with the Run as administrator option.

How to edit a profile


You can open any PowerShell profile in a text editor, such as Notepad.

To open the profile of the current user in the current PowerShell host
application in
Notepad, type:

PowerShell

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:

PowerShell

notepad $PROFILE.AllUsersAllHosts

To apply the changes, save the profile file, and then restart 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's specific to that
host application.

If you are an administrator who is customizing 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
PowerShell profiles.

How to use a profile


Many of the items that you create in 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 PowerShell variables,


environment
variables, aliases, functions, commands, and PowerShell modules
that you add to the
session.

To save these items and make them available in all future sessions, add them
to a
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 recreating them.

How to start a profile


When you open the profile file, it's 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 a function that lists aliases for any cmdlet


PowerShell

function Get-CmdletAlias ($cmdletname) {

Get-Alias |

Where-Object -FilterScript {$_.Definition -like "$cmdletname"} |

Format-Table -Property Definition, Name -AutoSize

Customize your console


PowerShell

function CustomizeConsole {

$hosttime = (Get-ChildItem -Path $PSHOME\PowerShell.exe).CreationTime

$hostversion="$($Host.Version.Major)`.$($Host.Version.Minor)"

$Host.UI.RawUI.WindowTitle = "PowerShell $hostversion ($hosttime)"

Clear-Host

CustomizeConsole

Add a customized PowerShell prompt


PowerShell

function Prompt

$env:COMPUTERNAME + "\" + (Get-Location) + "> "

For more information about the PowerShell prompt, see about_Prompts.

For other profile examples, see Customizing your shell environment.

The NoProfile parameter


To start PowerShell without profiles, use the NoProfile parameter of
powershell.exe , the
program that starts PowerShell.

To begin, open a program that can start PowerShell, such as Cmd.exe or


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 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 doesn't run, and its contents aren't applied.

A Set-ExecutionPolicy command sets and changes your execution policy. it's


one of the
few commands that applies in all PowerShell sessions because the
value is saved in the
registry. You don't have to set it when you open the
console, and you don't have to
store a Set-ExecutionPolicy command in your
profile.

Profiles and remote sessions


PowerShell profiles aren't run automatically in remote sessions, so the
commands that
the profiles add aren't present in the remote session. In
addition, the $PROFILE
automatic variable isn't populated in remote sessions.

To run a profile in a session, use the Invoke-Command cmdlet.

For example, the following command runs the "Current user, Current Host"
profile from
the local computer in the session in $s .

PowerShell

Invoke-Command -Session $s -FilePath $PROFILE

The following command runs the "Current user, Current Host" profile from the
remote
computer in the session in $s . Because the $PROFILE variable isn't
populated, the
command uses the explicit path to the profile. We use dot
sourcing operator so that the
profile executes in the current scope on the
remote computer and not in its own scope.

PowerShell

Invoke-Command -Session $s -ScriptBlock {

. "$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_Execution_Policies
about_Functions
about_Prompts
about_Remote
about_Scopes
about_Signing
Set-ExecutionPolicy
about_Prompts
Article • 09/19/2022 • 4 minutes to read

Short description
Describes the Prompt function and demonstrates how to create a custom
Prompt
function.

Long description
The PowerShell command prompt indicates that PowerShell is ready to run a
command:

PS C:\>

The PowerShell prompt is determined by the built-in Prompt function. You can
customize the prompt by creating your own Prompt function and saving it in
your
PowerShell profile.

About the Prompt function


The Prompt function determines the appearance of the PowerShell prompt.
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:

PowerShell

function Prompt { <function-body> }

The Prompt function must return an object. As a best practice, return a


string or an
object that is formatted as a string. The maximum recommended
length is 80 characters.

For example, the following Prompt function returns a "Hello, World" string
followed by a
right angle bracket ( > ).

PowerShell
PS C:\> function prompt {"Hello, World > "}

Hello, World >

Getting the Prompt function


To get the Prompt function, use the Get-Command cmdlet or use the
Get-Item cmdlet in
the Function drive.

For example:

PowerShell

PS C:\> Get-Command Prompt

CommandType Name ModuleName

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

Function prompt

To get the script that sets the value of the prompt, use the dot method to get
the
ScriptBlock property of the Prompt function.

For example:

PowerShell

(Get-Command Prompt).ScriptBlock

Output

"PS $($executionContext.SessionState.Path.CurrentLocation)$('>' *
($nestedPromptLevel + 1)) "

# .Link

# https://go.microsoft.com/fwlink/?LinkID=225750

# .ExternalHelp System.Management.Automation.dll-help.xml

Like all functions, the Prompt function is stored in the Function: drive.
To display the
script that creates the current Prompt function, type:

PowerShell

(Get-Item function:prompt).ScriptBlock

The default prompt


The default prompt appears only when the Prompt function generates an error
or does
not return an object.

The default PowerShell prompt is:

PS>

For example, the following command sets the Prompt function to $null , which
is invalid.
As a result, the default prompt appears.

PowerShell

PS C:\> function prompt {$null}

PS>

Because PowerShell comes with a built-in prompt, you usually do not see the
default
prompt.

Built-in prompt
PowerShell includes a built-in Prompt function.

PowerShell

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:

Output

[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:

Output

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

For example, when you are debugging in a nested prompt, the prompt resembles
the
following prompt:

Output

[DBG] PS C:\ps-test>>>

Changes to the prompt


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:

Output

PS Hello, World> Enter-PSSession Server01

[Server01]: PS Hello, World>

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

How to customize 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:


PowerShell

function prompt { }

Then, between the braces, enter the commands or the string that creates your
prompt.

For example, the following prompt includes your computer name:

PowerShell

function prompt {"PS [$env:COMPUTERNAME]> "}

On the Server01 computer, the prompt resembles the following prompt:

Output

PS [Server01] >

The following Prompt function includes the current date and time:

PowerShell

function prompt {"$(Get-Date)> "}

The prompt resembles the following prompt:

Output

03/15/2012 17:49:47>

You can also change the default Prompt function:

For example, the following modified Prompt function adds [ADMIN]: to the
built-in
PowerShell prompt when PowerShell is opened by using the
Run as administrator
option:

PowerShell

function prompt {

$identity = [Security.Principal.WindowsIdentity]::GetCurrent()

$principal = [Security.Principal.WindowsPrincipal] $identity

$adminRole = [Security.Principal.WindowsBuiltInRole]::Administrator

$(if (Test-Path variable:/PSDebugContext) { '[DBG]: ' }

elseif($principal.IsInRole($adminRole)) { "[ADMIN]: " }

else { '' }

) + 'PS ' + $(Get-Location) +

$(if ($NestedPromptLevel -ge 1) { '>>' }) + '> '

When you start PowerShell by using the Run as administrator option, a


prompt that
resembles the following prompt appears:

Output

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

PowerShell

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,
PowerShell uses the default prompt, PS> .

PowerShell

function prompt {

$color = Get-Random -Min 1 -Max 16

Write-Host ("PS " + $(Get-Location) +">") -NoNewLine `

-ForegroundColor $Color

return " "

Saving the Prompt function


Like any function, the Prompt function exists only in the current session. To
save the
Prompt function for future sessions, add it to your PowerShell
profiles. For more
information about profiles, see about_Profiles.

See also
about_Automatic_Variables
about_Debuggers
about_Functions
about_Profiles
about_Scopes
Get-History
Write-Host
Get-Location
Enter-PSSession
Get-Random
about_Properties
Article • 09/23/2022 • 5 minutes to read

Short description
Describes how to use object properties in PowerShell.

Long description
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 objects that
are part of the Microsoft .NET Framework, but you can
also create custom objects in
PowerShell.

The association between an item and its object is very close. When you change
an
object, you usually change the item that it represents. For example, when
you get a file
in PowerShell, you don't 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 are associated with
an object.
Different types of object have different properties. For example, a
FileInfo object, which
represents a file, has an IsReadOnly property
that contains $True if the file has the read-
only attribute and $False if
it doesn't. A DirectoryInfo object, which represents a file
system
directory, has a Parent property that contains the path to the parent
directory.

Object properties
To get 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 PowerShell installation

directory.

PowerShell

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

PowerShell

Get-ChildItem $PSHOME\powershell.exe | Get-Member -MemberType Property

Output

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 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
member access operator ( . ). Type a reference to the object, such as a
variable that
contains the object, or a command that gets the object. Then,
type the operator ( . )
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's executed before any properties
are accessed.

PowerShell

(Get-ChildItem $PSHOME\powershell.exe).CreationTime

Output

Saturday, June 5, 2021 7:07:00 AM

You can also save an object in a variable and then get its properties using the
member
access ( . ) method, as shown in the following example:

PowerShell

$a = Get-ChildItem $PSHOME\powershell.exe

$a.CreationTime

Output

Saturday, June 5, 2021 7:07:00 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.

PowerShell

Get-ChildItem $PSHOME\powershell.exe | Format-List -Property *

Output

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

Mode : -a----

VersionInfo : File:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

InternalName: POWERSHELL

OriginalFilename: PowerShell.EXE.MUI

FileVersion: 10.0.22000.1 (WinBuild.160101.0800)

FileDescription: Windows PowerShell

Product: Microsoft? Windows? Operating System

ProductVersion: 10.0.22000.1

Debug: False

Patched: False

PreRelease: False

PrivateBuild: False

SpecialBuild: False

Language: English (United States)

BaseName : powershell

Target : {C:\Windows\WinSxS\amd64_microsoft-windows-powershell-
exe_31bf3856ad364e35_10.0.22000.1_none_bf599c

5a06fbb6f4\powershell.exe}

LinkType : HardLink

Name : powershell.exe

Length : 450560

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 : 6/5/2021 7:07:00 AM

CreationTimeUtc : 6/5/2021 12:07:00 PM

LastAccessTime : 7/18/2022 12:16:17 PM

LastAccessTimeUtc : 7/18/2022 5:16:17 PM

LastWriteTime : 6/5/2021 7:07:00 AM

LastWriteTimeUtc : 6/5/2021 12:07:00 PM

Attributes : Archive

Static properties
You can use the static properties of .NET classes in PowerShell. Static
properties are
properties of class, unlike standard properties, which are
properties of an object.

To get the static properties of an class, use the Static parameter of the
Get-Member
cmdlet. For example, the following command gets the static
properties of the
System.DateTime class.

PowerShell

Get-Date | Get-Member -MemberType Property -Static

Output

TypeName: System.DateTime

Name MemberType Definition

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

MaxValue Property static datetime MaxValue {get;}

MinValue Property static datetime MinValue {get;}

Now Property datetime Now {get;}

Today Property datetime Today {get;}

UtcNow Property datetime UtcNow {get;}

To get the value of a static property, use the following syntax.

Syntax

[<ClassName>]::<Property>

For example, the following command gets the value of the UtcNow static
property of
the System.DateTime class.

PowerShell

[System.DateTime]::UtcNow

Member-access enumeration
Starting in PowerShell 3.0, when you use the member-access operator ( . ) to
access a
property that doesn't exist on a list collection, PowerShell
automatically enumerates the
items in the collection and returns the value of
the property on each item. For more
information, see
about_Member-Access_Enumeration.

Examples
This command returns the value of the DisplayName property of every service
that Get-
Service returns.
PowerShell

(Get-Service).DisplayName

Output

Application Experience

Application Layer Gateway Service


Windows All-User Install Agent

Application Identity

Application Information

...

All collections have a Count property that returns the number of objects in
the
collection.

PowerShell

(Get-Service).Count

Output

176

Starting in PowerShell 3.0, if you request the Count or Length property


of zero objects
or one object, PowerShell returns the correct value.

PowerShell

(Get-Service Audiosrv).Count

Output

If a property exists on the individual objects and on the collection, only the
collection's
property is returned.

PowerShell

$collection = @(

[pscustomobject]@{length = "foo"}

[pscustomobject]@{length = "bar"}

# PowerShell returns the collection's Length.

$collection.length

Output

See also
about_Objects
about_Member-Access_Enumeration
about_Methods
Format-List
Get-Member
Select-Object
about_Providers
Article • 11/15/2022 • 6 minutes to read

Short description
Describes how PowerShell providers provide access to data and components that
wouldn't otherwise be easily accessible at the command line. The data is
presented in a
consistent format that resembles a file system drive.

Long description
PowerShell providers are .NET programs that provide access to specialized data
stores
for easier viewing and management. The data 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
parameters are only available when you use the cmdlet with the provider data.

Built-in providers
PowerShell includes a set of built-in providers that provide access to
different types of
objects.

Alias provider
Drive - Alias:
Object types - System.Management.Automation.AliasInfo
Certificate provider
Drive - Cert:
Object types - Microsoft.PowerShell.Commands.X509StoreLocation,
System.Security.Cryptography.X509Certificates.X509Certificate2
Environment provider
Drive - Env:
Object types - System.Collections.DictionaryEntry
FileSystem provider
Drive - C: and other depending on hardware
Object types - System.IO.FileInfo, System.IO.DirectoryInfo
Function provider
Drive - Function:
Object types - System.Management.Automation.FunctionInfo
Registry provider
Drive - HKLM: , HKCU:
Object types - Microsoft.Win32.RegistryKey
Variable provider
Drive - Variable:
Object types - System.Management.Automation.PSVariable
WSMan provider
Drive - WSMan:
Object types -
Microsoft.WSMan.Management.WSManConfigContainerElement

You can also create your own PowerShell providers, and you can install
providers that
others develop. To list the providers that are available in your
session, type:

PowerShell

Get-PSProvider

Installing and removing providers


Providers are typically installed via PowerShell modules. Importing the module
loads the
provider into your session. You can't uninstall the built-in
providers. You can uninstall
providers loaded by other modules.

You can unload a provider from the current session using the Remove-Module
cmdlet.
This cmdlet doesn't 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 isn't affected, but the drive is no
longer available in that
session.

Viewing providers
To view the PowerShell providers on your computer, type:

PowerShell

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

The provider allows you to view, navigate, and change items in the data store
as though
they were data in a file system. The data store is accessed by 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 using the Get-PSDrive
cmdlet. For example, to get
all the properties of the Function: drive, type:

PowerShell

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:

PowerShell

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:

PowerShell

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:

PowerShell

Set-Location cert:

Then, to view the contents of the Cert: drive, type:

PowerShell

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:

PowerShell

Set-Location HKLM:\SOFTWARE\

If any element in the fully qualified name includes spaces, you must enclose
the name in
double-quotation marks ( " ). The following example shows a fully
qualified path that
includes spaces.

"C:\Program Files\Internet Explorer\iexplore.exe"

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\Microsoft\PowerShell key, type
the following command:

PowerShell

Get-ChildItem .\PowerShell

Also, double-dots ( .. ) refers to the directory or container directly above


your current
location. You can use double-dots ( .. ) to navigate through a
provider hierarchy.

PS HKLM:\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters\> cd
..\..\LanmanWorkstation\Parameters

PS HKLM:\SYSTEM\CurrentControlSet\Services\LanmanWorkstation\Parameters>

Provider Home
Providers also have a Home location. This location is shared by all
PSDrives backed by
the provider. It can be retrieved by viewing the Home
property of the provider.

PowerShell

Get-PSProvider | Format-Table Name, Home

Output

Name Home

---- ----

Registry

Alias

Environment

FileSystem C:\Users\username

Function

Variable

Certificate

The FileSystem provider is the only provider that has a default value for
Home. It's the
same value as $HOME . For more information, see
about_Automatic_Variables.

You can set the Home directory for a provider, for the current session,
using its property.

PowerShell

(Get-PSProvider FileSystem).Home = "C:\"

The ~ character can be used to represent the provider's home directory. If


the provider
doesn't have a Home location set, you see an error.

PowerShell
Cert:\> Set-Location ~

Output

Set-Location : Home location for this provider isn't set. To set the home

location, call "(get-psprovider 'Certificate').Home = 'path'".

At line:1 char:1

+ Set-Location ~

+ ~~~~~~~~~~~~~~

+ CategoryInfo : InvalidOperation: (:) [Set-Location],

PSInvalidOperationException

...

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:

PowerShell

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 PowerShell providers, type:

Get-Help <ProviderName>

For example:

PowerShell

Get-Help registry

For a list of Help topics about the providers, type:

PowerShell

Get-Help * -Category Provider

See also
about_Locations
about_Path_Syntax
about_PSConsoleHostReadLine
Article • 09/19/2022 • 2 minutes to read

Short description
Explains how to create a customize how PowerShell reads input at the console
prompt.

Long description
Starting in Windows PowerShell V3, you can write a function named
PSConsoleHostReadLine that overrides the default way that console input is
processed.

EXAMPLES
The following example launches Notepad and gets input from a text File that
the user
creates:

PowerShell

function PSConsoleHostReadLine

$inputFile = Join-Path $env:TEMP PSConsoleHostReadLine

Set-Content $inputFile "PS > "

# Notepad opens. Enter your command in it, save the file, and then exit.

notepad $inputFile | Out-Null

$userInput = Get-Content $inputFile

$resultingCommand = $userInput.Replace("PS >", "")

$resultingCommand

REMARKS
By default, PowerShell reads input from the console in what is known as
"Cooked Mode"
-- in which the Windows console subsystem handles all the
keypresses, F7 menus, and
other input. When you press Enter or Tab, Windows
PowerShell gets the text that you
have typed up to that point. There is no way
for it to know that you pressed Ctrl-R, Ctrl-
A, Ctrl-E, or any other keys
before pressing Enter or Tab. In Windows PowerShell version
3, the
PSConsoleHostReadLine function solves this issue. When you define a function
named PSConsoleHostReadline in the Windows PowerShell console host, Windows
PowerShell calls that function instead of the "Cooked Mode" input mechanism.
See Also
about_Prompts
about_PSCustomObject
Article • 01/24/2023 • 3 minutes to read

Short description
Explains the differences between the [psobject] and [pscustomobject] type
accelerators.

Long description
The [pscustomobject] type accelerator was added in PowerShell 3.0.

Prior to adding this type accelerator, creating an object with member


properties and
values was more complicated. Originally, you had to use
New-Object to create the object
and Add-Member to add properties. For
example:

PowerShell

PS> $object1 = New-Object -TypeName PSObject

PS> Add-Member -InputObject $object1 -MemberType NoteProperty -Name one -


Value 1

PS> Add-Member -InputObject $object1 -MemberType NoteProperty -Name two -


Value 2

PS> $object1 | 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()

one NoteProperty int one=1

two NoteProperty int two=2

PS> $object1

one two

--- ---

1 2

Later, you could use the Property parameter of New-Object to pass a


Hashtable
containing the members and values. For example:
PowerShell

PS> $object2 = New-Object -TypeName PSObject -Property @{one=1; two=2}

PS> $object2 | 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()

one NoteProperty int one=1

two NoteProperty int two=2

PS> $object2

one two

--- ---

1 2

Since PowerShell 3.0, casting a Hashtable to [pscustomobject] achieves


the same result.

PowerShell

PS> $object3 = [pscustomobject]@{one=1; two=2}

PS> $object3 | 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()

one NoteProperty int one=1

two NoteProperty int two=2

PS> $object3

one two

--- ---

1 2

PSObject type objects maintain the list of members in the order that the
members were
added to the object. Even though Hashtable objects don't
guarantee the order of the
key-value pairs, casting a literal hashtable to
[pscustomobject] maintains the order.
The hashtable must be a literal. If you wrap the hashtable in parentheses or if
you cast a
variable containing a hashtable, there is no guarantee that the
order is preserved.

PowerShell

$hash = @{

Name = "Server30"

System = "Server Core"

PSVersion = "4.0"

$Asset = [pscustomobject]$hash

$Asset

Output

PSVersion Name System

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

4.0 Server30 Server Core

Understanding the type accelerators


[psobject] and [pscustomobject] are type accelerators.

For more information, see about_Type_Accelerators.

Even though you might think that [pscustomobject] should map to


System.Management.Automation.PSCustomObject, the types are different.

PowerShell

PS> [pscustomobject] -eq [System.Management.Automation.PSCustomObject]

False

Both type accelerators are mapped to the same class, PSObject:

PowerShell

PS> [pscustomobject]

IsPublic IsSerial Name BaseType

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

True True PSObject System.Object

PS> [psobject]

IsPublic IsSerial Name BaseType

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

True True PSObject System.Object

When the [pscustomobject] type accelerator was added to PowerShell, it


included extra
code to handle conversion of a Hashtable to a PSObject
type. This extra code is only
invoked when a new object is being created.
Therefore, you can't use [pscustomobject]
for type coercion or type
comparison, because all objects are treated as PSObject types.

For example, using the -is operator to check that an object returned by a
cmdlet is a
[pscustomobject] is the same as comparing it to [psobject] .

PowerShell

PS> (Get-Item /) -is [pscustomobject]

True

PS> (Get-Item /) -is [psobject]

True

When you cast any object to [psobject] you get the type of the original
object.
Therefore, casting anything other than a Hashtable to
[pscustomobject] results in the
same type.

PowerShell

PS> ([psobject]@{Property = 'Value'}).GetType().FullName

System.Collections.Hashtable

PS> ([pscustomobject]123).GetType().Name

Int32

PS> ([pscustomobject]@{Property = 'Value'}).GetType().FullName

System.Management.Automation.PSCustomObject

While, casting an object to [psobject] appears to have no affect on the type,


PowerShell adds an invisible [psobject] wrapper around the object. This can
have
subtle side effects.

Wrapped objects will match their original type and the [psobject] type.

PowerShell

PS> 1 -is [Int32]

True

PS> 1 -is [psobject]

False

PS> ([psobject] 1) -is [Int32]

True

PS> ([psobject] 1) -is [psobject]

True

The format operator ( -f ) doesn't recognized an array wrapped by


[psobject] .

PowerShell

PS> '{0} {1}' -f (1, 2)

1 2

PS> '{0} {1}' -f ([psobject] (1, 2))

Error formatting a string: Index (zero based) must be greater than or


equal

to zero and less than the size of the argument list..

At line:1 char:1

+ '{0} {1}' -f ([psobject] (1, 2))

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : InvalidOperation: ({0} {1}:String) [],


RuntimeException

+ FullyQualifiedErrorId : FormatError

Notes
In Windows PowerShell, objects created by casting a Hashtable to
[pscustomobject] do
not have the Length or Count properties.
Attempting to access these members returns
$null .

For example:

PowerShell

PS> $object = [PSCustomObject]@{key = 'value'}

PS> $object

key

---

value

PS> $object.Count

PS> $object.Length

See also
about_Object_Creation
about_Objects
System.Management.Automation.PSObject
System.Management.Automation.PSCustomObject
about_PSItem
Article • 12/07/2022 • 6 minutes to read

Short description
The automatic variable that contains the current object in the pipeline object.

Long description
PowerShell includes the $PSItem variable and its alias, $_ , as
automatic variables in
scriptblocks that process the current object, such
as in the pipeline. This article uses
$PSItem in the examples, but $PSItem
can be replaced with $_ in every example.

You can use this variable in commands that perform an action on every object in
a
pipeline.

There are a few common use cases for $PSItem :

in the scriptblock for the Process parameter of the


ForEach-Object cmdlet
in the scriptblock for the FilterScript parameter of the Where-Object
cmdlet
in the intrinsic methods ForEach and Where
with delay-bind scriptblock parameters
in a switch statement's conditional values and associated scriptblocks
in the process block of a function
in a filter definition
in the scriptblock of the ValidateScript attribute

The rest of this article includes examples of using $PSItem for these use
cases.

ForEach-Object Process
The ForEach-Object cmdlet is designed to operate
on objects in the pipeline, executing
the Process parameter's scriptblock
once for every object in the pipeline.

You can use $PSItem in the Process parameter's scriptblock but not in the
Begin or End
parameter scriptblocks. If you reference $PSItem in the
Begin or End parameter
scriptblocks, the value is $null because those
scriptblocks don't operate on each object
in the pipeline.
PowerShell

$parameters = @{

Begin = { Write-Host "PSItem in Begin is: $PSItem" }

Process = {

Write-Host "PSItem in Process is: $PSItem"

$PSItem + 1

End = { Write-Host "PSItem in End is: $PSItem" }

$result = 1, 2, 3 | ForEach-Object @parameters

Write-Host "Result is: $result"

Output

PSItem in Begin is:

PSItem in Process is: 1

PSItem in Process is: 2

PSItem in Process is: 3

PSItem in End is:

Result is: 2 3 4

Where-Object FilterScript
The Where-Object cmdlet is designed to filter objects in the pipeline.

You can use $PSItem in the scriptblock of the FilterScript parameter,


which executes
once for each input object in the pipeline.

PowerShell

1, 2, 3 | Where-Object -FilterScript { ($PSItem % 2) -eq 0 }

Output

In this example, the FilterScript checks to see if the current object is


even, filtering out
any odd values, and returns only 2 from the original
list.

ForEach and Where methods


Both the ForEach and Where intrinsic methods for arrays take a
scriptblock as an input
parameter. You can use the $PSItem in those
scriptblocks to access the current object.

PowerShell

@('a', 'b', 'c').ForEach({ $PSItem.ToUpper() }).Where({ $PSItem -ceq 'B' })

Output

In this example, the scriptblock of the ForEach method uppercases the


current object.
Then the scriptblock of the Where method returns only B .

Delay-bind scriptblock parameters


Delay-bind scriptblocks let you use $PSItem to define parameters for a
pipelined cmdlet
before executing it.

PowerShell

dir config.log | Rename-Item -NewName { "old_$($_.Name)" }

Switch statement scriptblocks


In switch statements, you can use $PSItem in both action scriptblocks
and statement
condition scriptblocks.

PowerShell

$numbers = 1, 2, 3

switch ($numbers) {

{ ($PSItem % 2) -eq 0 } { "$PSItem is even" }

default { "$PSItem is odd" }

Output

1 is odd

2 is even

3 is odd

In this example, the statement condition scriptblock checks whether the current
object is
even. If it's even, the associated action scriptblock outputs a
message indicating the
current object is even.

The action scriptblock for the default condition outputs a message indicating
the
current object is odd.

Function process blocks


When you define a function, you can use $PSItem in the process block
definition but
not in the begin or end block definitions. If you
reference $PSItem in the begin or end
blocks, the value is $null
because those blocks don't operate on each object in the
pipeline.

When you use $PSItem in the process block definition, the value is the
value is the
current object if the function is called in the pipeline and
otherwise $null .

PowerShell

function Add-One {

process { $PSItem + 1 }

1, 2, 3 | Add-One

Output

 Tip

While you can use $PSItem in advanced functions, there's little


reason to do so. If
you intend to receive input from the pipeline,
it's best to define parameters with
one of the ValueFromPipeline* arguments
for the Parameter attribute.

Using the Parameter attribute and cmdlet binding for advanced functions
makes the
implementation more explicit and predictable than processing the
current object to get
the required values.
One good use of $PSItem in advanced functions is to inspect the current
object itself for
debugging or logging when the function has multiple
parameters that take input from
the pipeline.

PowerShell

function Write-JsonLog {

[CmdletBinding()]

param(

[parameter(ValueFromPipelineByPropertyName)]

[string]$Message

begin {

$entries = @()

process {

$entries += [pscustomobject]@{

Message = $Message

TimeStamp = [datetime]::Now

if ($PSItem) {

$props = $PSItem | ConvertTo-Json

$number = $entries.Length

Write-Verbose "Input object $number is:`n$props"

end {

ConvertTo-Json -InputObject $entries

This example function outputs an array of JSON objects with a message and
timestamp.
When called in a pipeline, it uses the Message property of the
current object for each
entry. It also writes the JSON representation of the
current object itself to the verbose
stream, so you can see the actual input
compared to the output logs.

PowerShell

$Items = @(

[pscustomobject]@{

Name = 'First Item'

Message = 'A simple note'


}

[pscustomobject]@{

Name = 'Item with extra properties'

Message = 'Missing message, has info instead'

Info = 'Some metadata'


Source = 'Where this came from'

[pscustomobject]@{

Name = 'Last Item'

Message = 'This also gets logged'

$Items | Write-JsonLog -Verbose

Output

VERBOSE: Input object 1 is:

"Name": "First Item",

"Message": "A simple note"

VERBOSE: Input object 2 is:

"Name": "Item with extra properties",

"Message": "Missing message, has info instead",

"Info": "Some metadata",

"Source": "Where this came from"

VERBOSE: Input object 3 is:

"Name": "Last Item",

"Message": "This also gets logged"

"Message": "A simple note",

"TimeStamp": "\/Date(1670344068257)\/"

},

"Message": "Missing message, has info instead",

"TimeStamp": "\/Date(1670344068259)\/"

},

"Message": "This also gets logged",

"TimeStamp": "\/Date(1670344068261)\/"

Filter definitions
You can use $PSItem in the statement list of a filter's definition.

When you use $PSItem in a filter definition, the value is the current
object if the filter
is called in the pipeline and otherwise $null .

PowerShell
filter Test-IsEven { ($PSItem % 2) -eq 0 }

1, 2, 3 | Test-IsEven

Output

False

True

False

In this example, the Test-IsEven filter outputs $true if the current object
is an even
number and $false if it isn't.

The ValidateScript attribute scriptblock


You can use $PSItem in the scriptblock of a ValidateScript attribute.
When used with
ValidateScript, $PSItem is the value of the current object
being validated. When the
variable or parameter value is an array, the
scriptblock is called once for each object in
the array with $PSItem as the
current object.

PowerShell

function Add-EvenNumber {

param(

[ValidateScript({ 0 -eq ($PSItem % 2) })]

[int[]]$Number

begin {

[int]$total = 0
}

process {

foreach ($n in $Number) {

$total += $n

end {

$total

Add-EvenNumber -Number 2, 4, 6

Add-EvenNumber -Number 1, 2

Output

12

Add-EvenNumber : Cannot validate argument on parameter 'Number'. The

" 0 -eq ($PSItem % 2) " validation script for the argument with value "1"

did not return a result of True. Determine why the validation script

failed, and then try the command again.

At line:1 char:24

+ Add-EvenNumber -Number 1, 2

+ ~~~~

+ CategoryInfo : InvalidData: (:) [Add-EvenNumber],

ParameterBindingValidationException

+ FullyQualifiedErrorId : ParameterArgumentValidationError,

Add-EvenNumber

In this example the scriptblock for the ValidateScript attribute runs once
for each value
passed to the Number parameter, returning an error if any
value isn't even.

The Add-EvenNumber function adds the valid input numbers and returns the
total.

See also
about_Arrays
about_automatic_variables
about_Comparison_Operators
about_functions
about_Script_Blocks
about_Switch
ForEach-Object
Where-Object
about_PSModulePath
Article • 03/24/2023 • 2 minutes to read

Short description
This article describes the purpose and usage of the $env:PSModulePath
environment
variable.

Long description
The $env:PSModulePath environment variable contains a list of folder
locations that are
searched to find modules and resources. PowerShell
recursively searches each folder for
module ( .psd1 or .psm1 ) files.

Install-Module has a Scope parameter that allows you to specify whether


the module is
installed for the current user or for all users. For more
information, see Install-Module.

By default, the effective locations assigned to $env:PSModulePath are:

System-wide locations: These folders contain modules that ship with


PowerShell.
These modules are stored in the $PSHOME\Modules folder. This is
also the location
where the Windows management modules are installed.

Modules installed in the AllUsers scope are stored in


$env:ProgramFiles\WindowsPowerShell\Modules .

User-installed modules: These are modules installed in the


CurrentUser scope. The
location of the CurrentUser scope is typically
the
$HOME\Documents\WindowsPowerShell\Modules folder. The specific location
of the
Documents folder varies by version of Windows and when you use
folder

redirection. Also, Microsoft OneDrive can change the location of your


Documents
folder. You can verify the location of your Documents folder
using the following
command: [Environment]::GetFolderPath('MyDocuments') .

Application specific modules: Setup programs can install modules in other


directories, such as the Program Files directory. The installer may append
the
application location to the value of $env:PSModulePath .

PowerShell PSModulePath construction


The value of $env:PSModulePath is constructed each time PowerShell starts.
The value
varies by version of PowerShell and how it's launched.

Windows PowerShell startup


Windows PowerShell uses the following logic to construct the PSModulePath at
startup:

If PSModulePath doesn't exist, combine CurrentUser, AllUsers, and


the $PSHOME
modules paths
If PSModulePath does exist:
If PSModulePath contains $PSHOME modules path:
AllUsers modules path is inserted before $PSHOME modules path
else:
Just use PSModulePath as defined since the user deliberately removed
the
$PSHOME location

The CurrentUser module path is prefixed only if the User scope


$env:PSModulePath
doesn't exist. Otherwise, the User scope
$env:PSModulePath is used as defined.

Module search behavior


PowerShell recursively searches each folder in the PSModulePath for module
( .psd1 or
.psm1 ) files. This search pattern allows multiple versions of the
same module to be
installed in different folders. For example:

Output

Directory: C:\Program Files\WindowsPowerShell\Modules\PowerShellGet

Mode LastWriteTime Length Name

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

d---- 8/14/2020 5:56 PM 1.0.0.1

d---- 9/13/2019 3:53 PM 2.1.2

By default, PowerShell loads the highest version number of a module when


multiple
versions are found. To load a specific version, use Import-Module
with the
FullyQualifiedName parameter. For more information, see
Import-Module.

Modifying PSModulePath
For most situations, you should be installing modules in the default module
locations.
However, you may have a need to change the value of the
PSModulePath environment
variable.

For example, to temporarily add the C:\Program Files\Fabrikam\Modules


directory to
$env:PSModulePath for the current session, type:

PowerShell

$Env:PSModulePath = $Env:PSModulePath+";C:\Program Files\Fabrikam\Modules"

To change the value of PSModulePath in every session, edit the registry key
storing the
PSModulePath values. The PSModulePath values are stored in the
registry as unexpanded
strings. To avoid permanently saving the
PSModulePath values as expanded strings, use
the GetValue method on the
subkey and edit the value directly.

The following example adds the C:\Program Files\Fabrikam\Modules path to the


value
of the PSModulePath environment variable without expanding the
un-expanded strings.

PowerShell

$key = (Get-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\Session


Manager').OpenSubKey('Environment', $true)

$path = $key.GetValue('PSModulePath','','DoNotExpandEnvironmentNames')

$path += ';%ProgramFiles%\Fabrikam\Modules'

$key.SetValue('PSModulePath',$path,
[Microsoft.Win32.RegistryValueKind]::ExpandString)

To add a path to the user setting, change the registry provider from HKLM:\
to HKCU:\ .

PowerShell

$key = (Get-Item 'HKCU:\').OpenSubKey('Environment', $true)

$path = $key.GetValue('PSModulePath','','DoNotExpandEnvironmentNames')

$path += ';%ProgramFiles%\Fabrikam\Modules'

$key.SetValue('PSModulePath',$path,
[Microsoft.Win32.RegistryValueKind]::ExpandString)

See also
about_Modules
about_PSSessions
Article • 09/19/2022 • 7 minutes to read

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.

Beginning in Windows PowerShell 3.0, PSSessions are independent of the


sessions in
which they are created. Active PSSessions are maintained on the
remote computer (or
the computer at the remote end or "server-side" of the
connection). As a result, you can
disconnect from the PSSession and reconnect
to it at a later time from the same
computer or from a different computer.

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 user-managed 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, disconnect and reconnect to
them, and run multiple commands in the same
PSSession. The PSSession remains
available until you delete it or it times
out.

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

PowerShell

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.

PowerShell

$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:

PowerShell

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 without the ComputerName parameter. 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.

PowerShell

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.

Output

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.

PowerShell

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

PowerShell

$ps01 = Get-PSSession -Id 1

Beginning in Windows PowerShell 3.0, PSSessions are maintained on the remote


computer. To get PSSessions that you created on particular remote computers,
use the
ComputerName parameter of the Get-PSSession cmdlet. The
following command gets
the PSSessions that you created on the Server01 remote
computer. This includes
PSSessions created in the current session and in other
sessions on the local computer or
other computers.

PowerShell

Get-PSSession -ComputerName Server01

In Windows PowerShell 2.0, 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:

PowerShell

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.

PowerShell

Remove-PSSession -Session $ps

or

PowerShell

Remove-PSSession -Id 1

To remove a PSSession from a remote computer, use the ComputerName


parameter of
the Remove-PSSession cmdlet.

PowerShell

Remove-PSSession -ComputerName Server01 -Id 1

If you do not delete the PSSession, the PSSession remains available for use
until it times
out.

You can also use the IdleTimeout parameter of the New-PSSessionOption


cmdlet to set
an expiration time for an idle PSSession. For more information,
see New-
PSSessionOption.

The PSSession Cmdlets


For a list of PSSession cmdlets, type:

PowerShell

Get-Help *-PSSession

Connect-PSSession: Connects a PSSession to the current session


Disconnect-PSSession: Disconnects a PSSession from the current session
Enter-PSSession: Starts an interactive session
Exit-PSSession: Ends an interactive session
Get-PSSession: Gets the PSSessions in the current session
New-PSSession: Creates a new PSSession on a local or remote computer
Receive-PSSession: Gets the results of commands that ran in a disconnected
session
Remove-PSSession: Deletes the PSSessions in the current session

For More Information


For more information about PSSessions, see about_PSSession_Details.

See also
about_Remote
about_Remote_Disconnected_Sessions
about_Remote_Requirements
Invoke-Command
Connect-PSSession
Disconnect-PSSession
Enter-PSSession
Exit-PSSession
Get-PSSession
New-PSSession
Remove-PSSession
about_PSSession_Details
Article • 09/19/2022 • 8 minutes to read

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 My PSSessions in Other Sessions?


Beginning in Windows PowerShell 3.0, the ComputerName
parameter of the Get-
PSSession cmdlet gets PSSessions
that you created on the specified remote computers.

Active PSSessions are maintained on the remote computer


(the "server-side" of a
connection) and you can get them
from any session on any computer.

For example, if you create a PSSession from the Server01


computer to the Server02
computer, and then switch to the
Server03 computer, you can use a command like the
following
one to get the session.

PowerShell

Get-PSSession -ComputerName Server02

Even if you disconnect from the session, the session is


maintained on the remote
computer until you delete it or it
times out.

In Windows PowerShell 2.0, you can get only the PSSessions


that you have created in
the current session. You cannot get
PSSessions that you created in other sessions.

For more information, see Get-PSSession.


Can I See the PSSessions That Others Have
Created on My Computer?
You can get and manage only the PSSessions that others have created
only if you can
supply the credentials of the user who created the
PSSession or the session
configuration that the PSSession uses
includes RunAs credentials. Otherwise, you can
get, connect to, use,
and manage only the PSSessions that you created.

Can I Connect to a PSSession From a Different


Computer?
Beginning in Windows PowerShell 3.0, PSSessions are independent
of the sessions in
which they were created. Active PSSessions
are maintained on the computer at the
remote or "server-side" of
a connection.

You can use the Disconnect-PSSession cmdlet to disconnect


from a PSSession. The
PSSession is disconnected from the
local session, but is maintained on the remote
computer.
Commands continue to run in the disconnected PSSession. You
can close
Windows PowerShell and shut down the originating computer
without interrupting the
PSSession.

Then, even hours later, you can use the Get-PSSession cmdlet to
get the PSSession and
the Connect-PSSession cmdlet to connect to the
PSSession from a new session on a
different computer.

For more information, see about_Remote_Disconnected_Sessions.

What Happens to My PSSession if My


Computer Stops?
Disconnected PSSessions are independent of the sessions
in which they were created. If
you disconnect a PSSession
and then close the originating computer, the PSSession is
maintained on the remote computer.

In addition, Windows PowerShell attempts to recover active


PSSessions that are
disconnected unintentionally, such as
by a computer reboot, a temporary power outage
or network
disruption. Windows PowerShell attempts to maintain or recover
the
PSSession to an Opened state, if the originating session
is still available, or to a
disconnected state if it is not.
An "active" PSSession is one that is running commands. If
a PSSession is connected (not
disconnected) and commands are
running in the PSSession when the connected session
closes,
Windows PowerShell attempts to maintain the PSSession on the
remote
computer. However, if no commands are running in the
PSSession, Windows PowerShell
closes the PSSession when the
connected session closes.

For more information, see about_Remote_Disconnected_Sessions.

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 IdleTimeOut parameter of New-PSSessionOption to close


an idle
PSSession after an interval that you specify. For more information,
see New-
PSSessionOption.

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_Disconnected_Sessions
about_Remote_Requirements
Invoke-Command
Enter-PSSession
Exit-PSSession
Get-PSSession
New-PSSession
Remove-PSSession
about_PSSnapins
Article • 09/19/2022 • 5 minutes to read

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.

NOTE: Windows PowerShell snap-ins (PSSnapins) are available for use in Windows
PowerShell 3.0 and Windows PowerShell 2.0. They might be altered or unavailable
in
subsequent versions. To package Windows PowerShell cmdlets and providers,
use
modules. For information about creating modules and converting snap-ins to
modules,
see
Writing a Windows PowerShell Module.

FINDING SNAP-INS
To get a list of the Windows PowerShell snap-ins on your computer, type:

PowerShell

Get-PSSnapin

To get the snap-in for each Windows PowerShell provider, type:

PowerShell

Get-PSProvider | Format-List name, pssnapin

To get a list of the cmdlets in a Windows PowerShell snap-in, type:

PowerShell

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 .

To get all the registered snap-ins on your system or to verify that a snap-in
is registered,
type:

PowerShell

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:

PowerShell

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:

PowerShell

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

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:

PowerShell

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.

BUILT-IN COMMANDS
In Windows PowerShell 2.0 and in older-style host programs in Windows
PowerShell 3.0
and later, the built-in commands that are installed with
Windows PowerShell are
packaged in snap-ins that are added automatically to
every Windows PowerShell
session.

Beginning in Windows PowerShell 3.0, in newer-style host programs -- those


that start
sessions by using the InitialSessionState.CreateDefault2 method --
the built-in
commands are packaged in modules. The exception is
Microsoft.PowerShell.Core, which
always appears as a snap-in. The Core snap-in
is included in every session by default.
The built-in modules are loaded
automatically on first-use.

NOTE: Remote sessions, including sessions that are started by using the
New-PSSession
cmdlet, are older-style sessions in which the built-in commands
are packaged in snap-
ins.

The following snap-ins (or modules) are installed with Windows PowerShell.

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 the Certificate provider and
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.

Microsoft.WSMan.Management - Contains the WSMan provider and cmdlets that


manage the Windows Remote Management service, such as Connect-WSMan and
Enable-WSManCredSSP.

LOGGING SNAP-IN EVENTS


Beginning in Windows PowerShell 3.0, you can record execution events for the
cmdlets
in Windows PowerShell modules and snap-ins by setting the
LogPipelineExecutionDetails property of modules and snap-ins to TRUE. For more
information, see about_EventLogs.

See also
about_Modules
about_Profiles
Get-Command
Export-Console
Add-PsSnapin
Get-PsSnapin
Remove-PsSnapin

KEYWORDS
about_Snapins
about_Snap_ins
about_Snap-ins
about_Quoting_Rules
Article • 09/19/2022 • 6 minutes to read

Short description
Describes rules for using single and double quotation marks in 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.

Double-quoted strings
A string enclosed in double quotation marks is an expandable string. Variable
names
preceded by a dollar sign ( $ ) are replaced with the variable's value
before the string is
passed to the command for processing.

For example:

PowerShell

$i = 5

"The value of $i is $i."

The output of this command is:

Output

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:

PowerShell

"The value of $(2+3) is 5."

The output of this command is:

Output

The value of 5 is 5.

Only simple variable references can be directly embedded in an expandable


string.
Variables references using array indexing or member access must be
enclosed in a
subexpression. For example:

PowerShell

"PS version: $($PSVersionTable.PSVersion)"

Output

PS version: 5.1.19041.1151

To separate a variable name from subsequent characters in the string,


enclose it in
braces ( {} ). This is especially important if the variable name
is followed by a colon ( : ).
PowerShell considers everything between the $
and the : a scope specifier, typically
causing the interpretation to fail.
For example, "$HOME: where the heart is." throws an
error, but
"${HOME}: where the heart is." works as intended.

To prevent the substitution of a variable value in a double-quoted string, use


the
backtick character ( ` ), which is the PowerShell escape character.

In the following example, the backtick character that precedes the first $i
variable
prevents PowerShell from replacing the variable name with its value.
For example:

PowerShell

$i = 5

"The value of `$i is $i."

The output of this command is:


Output

The value of $i is 5.

Single-quoted strings
A string enclosed in single quotation marks is a verbatim string. The string
is passed to
the command exactly as you type it. No substitution is performed.
For example:

PowerShell

$i = 5

'The value of $i is $i.'

The output of this command is:

Output

The value $i is $i.

Similarly, expressions in single-quoted strings are not evaluated. They are


interpreted as
string literals. For example:

PowerShell

'The value of $(2+3) is 5.'

The output of this command is:

Output

The value of $(2+3) is 5.

Including quote characters in a string


To make double-quotation marks appear in a string, enclose the entire string
in single
quotation marks. For example:

PowerShell

'As they say, "live and learn."'

The output of this command is:

Output

As they say, "live and learn."

You can also enclose a single-quoted string in a double-quoted string. For


example:

PowerShell

"As they say, 'live and learn.'"

The output of this command is:

Output

As they say, 'live and learn.'

Or, double the quotation marks around a double-quoted phrase. For example:

PowerShell

"As they say, ""live and learn."""

The output of this command is:

Output

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:

PowerShell

'don''t'

The output of this command is:

Output

don't

To force PowerShell to interpret a double quotation mark literally, use a


backtick
character. This prevents PowerShell from interpreting the quotation
mark as a string
delimiter. For example:

PowerShell

"Use a quotation mark (`") to begin a string."

'Use a quotation mark (`") to begin a string.'

Because the contents of single-quoted strings are interpreted literally, the


backtick
character is treated as a literal character and displayed in the
output.

Output

Use a quotation mark (") to begin a string.

Use a quotation mark (`") to begin a string.

Here-strings
The quotation rules for here-strings are slightly different.

A here-string is a single-quoted or double-quoted string surrounded by at signs


( @ ).
Quotation marks within a here-string are interpreted literally.

A here-string:

spans multiple lines


begins with the opening mark followed by a newline
ends with a newline followed by the closing mark
includes every line between the opening and closing marks as part of a single
string

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 block
The Help text for a script or function document

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.
Double-quotes:

@"<Enter>

<string> [string] ...<Enter>

"@

Single-quotes:

@'<Enter>

<string> [string] ...<Enter>

'@

7 Note

The final newline character is part of the closing mark. It is not added to
the here-
string.

A here-string contains all the text between the opening and closing marks. In
the here-
string, all quotation marks are interpreted literally. For example:

PowerShell

@"

For help, type "get-help"

"@

The output of this command is:

Output

For help, type "get-help"

Using a here-string can simplify using a string in a command. For example:

PowerShell

@"

Use a quotation mark (') to begin a string.

"@

The output of this command is:

Output

Use a quotation mark (') to begin a string.

In single-quoted here-strings, variables are interpreted literally and


reproduced exactly.
For example:

PowerShell

@'

The $profile variable contains the path

of your PowerShell profile.

'@

The output of this command is:

Output

The $profile variable contains the path

of your PowerShell profile.

In double-quoted here-strings, variables are replaced by their values. For


example:

PowerShell

@"

Even if you have not created a profile,

the path of the profile file is:

$profile.

"@

The output of this command is:

Output

Even if you have not created a profile,

the path of the profile file is:

C:\Users\User1\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.

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

7 Note

PowerShell allows double- or single-quoted strings to span multiple lines


without
using the @ syntax of here-strings. However, full here-string
syntax is the preferred
usage.

Interpretation of expandable strings


Expanded strings don't necessarily look the same as the default output that you
see in
the console.

Collections, including arrays, are converted to strings by placing a single


space between
the string representations of the elements. A different separator
can be specified by
setting preference variable $OFS . For more information,
see the $OFS preference
variable.

Instances of any other type are converted to strings by calling the


ToString() method
which may not give a meaningful representation. For
example:

PowerShell

"hashtable: $(@{ key = 'value' })"

Output

hashtable: System.Collections.Hashtable

To get the same output as in the console, use a subexpression in which you pipe
to Out-
String . Apply the Trim() method if you want to remove any leading
and trailing empty

lines.

PowerShell

"hashtable:`n$((@{ key = 'value' } | Out-String).Trim())"

Output

hashtable:

Name Value

---- -----

key value

Passing quoted strings to external commands


Some native commands expect arguments that contain quote characters. PowerShell
interprets the quoted string before passing it to the external command. This
interpretation removes the outer quote characters.

For more information about this behavior, see the


about_Parsing
article.

See also
about_Parsing
about_Special_Characters
ConvertFrom-StringData
about_Redirection
Article • 02/14/2023 • 6 minutes to read

Short description
Explains how to redirect output from PowerShell to text files.

Long description
By default, PowerShell sends output to the PowerShell host. Usually this is the
console
application. However, you can redirect 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 PowerShell redirection operators. Using the redirection operator with
a file
target is functionally equivalent to piping to Out-File with no
extra parameters.

For more information about streams, see


about_Output_Streams.

Redirectable output streams


PowerShell supports redirection of the following output streams.

Stream # Description Introduced in Write Cmdlet

1 Success Stream PowerShell 2.0 Write-Output

2 Error Stream PowerShell 2.0 Write-Error

3 Warning Stream PowerShell 3.0 Write-Warning

4 Verbose Stream PowerShell 3.0 Write-Verbose

5 Debug Stream PowerShell 3.0 Write-Debug


Stream # Description Introduced in Write Cmdlet

6 Information Stream PowerShell 5.0 Write-Information , Write-Host

* All Streams PowerShell 3.0

There is also a Progress stream in PowerShell, but it does not support


redirection.

) Important

The Success and Error streams are similar to the stdout and stderr
streams of other
shells. However, stdin is not connected to the PowerShell
pipeline for input.

PowerShell redirection operators


The PowerShell redirection operators are as follows, where n represents
the stream
number. The Success stream ( 1 ) is the default if no stream
is specified.

Operator Description Syntax

> Send specified stream to a file. n>

>> Append specified stream to a file. n>>

>&1 Redirects the specified stream to the Success stream. n>&1

7 Note

Unlike some Unix shells, you can only redirect other streams to the
Success stream.

Examples

Example 1: Redirect errors and output to a file


This example runs dir on one item that will succeed, and one that will error.

PowerShell

dir 'C:\', 'fakepath' 2>&1 > .\dir.log

It uses 2>&1 to redirect the Error stream to the Success stream, and
> to send the
resultant Success stream to a file called dir.log

Example 2: Send all Success stream data to a file


This example sends all Success stream data to a file called script.log .

PowerShell

.\script.ps1 > script.log

Example 3: Send Success, Warning, and Error streams to a


file
This example shows how you can combine redirection operators to achieve a
desired
result.

PowerShell

&{

Write-Warning "hello"

Write-Error "hello"

Write-Output "hi"

} 3>&1 2>&1 > C:\Temp\redirection.log

3>&1 redirects the Warning stream to the Success stream.


2>&1 redirects the Error stream to the Success stream (which also
now includes all

Warning stream data)


> redirects the Success stream (which now contains both Warning
and Error

streams) to a file called C:\temp\redirection.log )

Example 4: Redirect all streams to a file


This example sends all streams output from a script called script.ps1 to a
file called
script.log

PowerShell

.\script.ps1 *> script.log

Example 5: Suppress all Write-Host and Information


stream data
This example suppresses all information stream data. To read more about
Information
stream cmdlets, see
Write-Host and
Write-Information

PowerShell

&{

Write-Host "Hello"

Write-Information "Hello" -InformationAction Continue

} 6> $null

Example 6: Show the effect of Action Preferences


Action Preference variables and parameters can change what gets written to a
particular
stream. The script in this example shows how the value of
$ErrorActionPreference
affects what gets written to the Error stream.

PowerShell

$ErrorActionPreference = 'Continue'

$ErrorActionPreference > log.txt

get-item /not-here 2>&1 >> log.txt

$ErrorActionPreference = 'SilentlyContinue'

$ErrorActionPreference >> log.txt

get-item /not-here 2>&1 >> log.txt

$ErrorActionPreference = 'Stop'

$ErrorActionPreference >> log.txt

Try {

get-item /not-here 2>&1 >> log.txt

catch {

"`tError caught!" >> log.txt

$ErrorActionPreference = 'Ignore'

$ErrorActionPreference >> log.txt

get-item /not-here 2>&1 >> log.txt

$ErrorActionPreference = 'Inquire'

$ErrorActionPreference >> log.txt

get-item /not-here 2>&1 >> log.txt

$ErrorActionPreference = 'Continue'

When we run this script we get prompted when $ErrorActionPreference is set to


Inquire .

PowerShell

PS C:\temp> .\test.ps1

Confirm

Cannot find path 'C:\not-here' because it does not exist.

[Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is
"Y"): H

Get-Item: C:\temp\test.ps1:23

Line |

23 | get-item /not-here 2>&1 >> log.txt

| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

| The running command stopped because the user selected the Stop
option.

When we examine the log file we see the following:

PS C:\temp> Get-Content .\log.txt


Continue

Get-Item: C:\temp\test.ps1:3

Line |

3 | get-item /not-here 2>&1 >> log.txt

| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

| Cannot find path 'C:\not-here' because it does not exist.

SilentlyContinue

Stop

Error caught!

Ignore

Inquire

Notes
The redirection operators that do not append data ( > and n> ) overwrite the
current
contents of the specified file without warning.

However, if the file is a read-only, hidden, or system file, the redirection


fails. The
append redirection operators ( >> and n>> ) 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 UTF8NoBOM
encoding. If the
file has a different encoding, the output might not be
formatted correctly. To write to
files with a different encoding, use the
Out-File cmdlet with its Encoding parameter.

Width of output when writing to a file


When you are writing to a file using either Out-File or the redirection
operators,
PowerShell formats table output to the file based on the width of
the console it is
running within. For instance, when logging table output
to file using a command like
Get-ChildItem Env:\Path > path.log on a system
where the console width is set to 80
columns, the output in the file is
truncated to 80 characters:

Output

Name Value

---- -----

Path C:\Program Files\PowerShell\7;C:\WINDOWS…

Considering that the console width may be set arbitrarily on systems where
your script is
run, you may prefer that PowerShell format table output to
files based on a width that
you specify instead.

The Out-File cmdlet provides a Width parameter that allows you to set
the width you
would like for table output. Rather than having to add
-Width 2000 everywhere you
invoke Out-File , you can use the
$PSDefaultParameterValues variable to set this value
for all usages of the
Out-File cmdlet in a script. And since the redirection operators ( >
and
>> ) are effectively aliases for Out-File , setting the Out-File:Width
parameter for
the whole script impacts the formatting width for the
redirection operators as well. Put
the following command near the top of your
script to set Out-File:Width for the whole
script:

PowerShell

$PSDefaultParameterValues['out-file:width'] = 2000

Increasing the output width will increase memory consumption when logging
table
formatted output. If you are logging a lot of tabular data to file and
you know you can
get by with a smaller width, use the smaller width.
In some cases, such as Get-Service output, in order to use the extra width
you will need
to pipe the output through Format-Table -AutoSize before
outputting to file.

PowerShell

$PSDefaultParameterValues['out-file:width'] = 2000

Get-Service | Format-Table -AutoSize > services.log

For more information about $PSDefaultParameterValues , see


about_Preference_Variables.

Potential confusion with comparison operators


The > operator is not to be confused with the
Greater-than comparison
operator (often
denoted as > in other programming languages).

Depending on the objects being compared, the output using > can appear to be
correct
(because 36 is not greater than 42).

PowerShell

PS> if (36 > 42) { "true" } else { "false" }

false

However, a check of the local filesystem can see that a file called 42 was
written, with
the contents 36 .

PowerShell

PS> dir

Mode LastWriteTime Length Name

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

------ 1/02/20 10:10 am 3 42

PS> cat 42

36

Attempting to use the reverse comparison < (less than), yields a system error:

PowerShell

PS> if (36 < 42) { "true" } else { "false" }

At line:1 char:8

+ if (36 < 42) { "true" } else { "false" }

+ ~

The '<' operator is reserved for future use.

+ CategoryInfo : ParserError: (:) [],


ParentContainsErrorRecordException

+ FullyQualifiedErrorId : RedirectionNotSupported

If numeric comparison is the required operation, -lt and -gt should be


used. For more
information, see the -gt operator in
about_Comparison_Operators.

See also
about_Command_Syntax
about_Operators
about_Output_Streams
about_Path_Syntax
Out-File
Tee-Object
Write-Debug
Write-Error
Write-Host
Write-Information
Write-Output
Write-Progress
Write-Verbose
Write-Warning
about_Ref
Article • 09/19/2022 • 2 minutes to read

Short description
Describes how to create and use a reference type variable. You can use
reference type
variables to permit a function to change the value
of a variable that is passed to it.

Long description
You can pass variables to functions by reference or by value.

When you pass a variable by value, you are passing a copy of the data.

In the following example, the function changes the value of the variable passed
to it. In
PowerShell, integers are value types so they are passed by value.
Therefore, the value of
$var is unchanged outside the scope of the function.

PowerShell

Function Test($data)

$data = 3

$var = 10

Test -data $var

$var

Output

10

In the following example, a variable containing a Hashtable is passed to a


function.
Hashtable is an object type so by default it is passed to the
function by reference.

When passing a variable by reference, the function can change the data and
that change
persists after the function executes.

PowerShell

Function Test($data)

$data.Test = "New Text"

$var = @{}

Test -data $var

$var

Output

Name Value

---- -----

Test New Text

The function adds a new key-value pair that persists outside of the function's
scope.

Writing functions to accept reference parameters


You can code your functions to take a parameter as a reference, regardless of
the type
of data passed. This requires that you specify the parameters type
as
System.Management.Automation.PSReference , or [ref] .

When using references, you must use the Value property of the
System.Management.Automation.PSReference type to access your data.

PowerShell

Function Test([ref]$data)

$data.Value = 3

To pass a variable to a parameter that expects a reference, you must type


cast your
variable as a reference.

7 Note

The brackets and parenthesis are BOTH required.

PowerShell

$var = 10

Test -data ([ref]$var)

$var

Output

Passing references to .NET methods


Some .NET methods may require you to pass a variable as a reference. When
the
method's definition uses the keywords in , out , or ref on a
parameter, it expects a
reference.

PowerShell

[int] | Get-Member -Static -Name TryParse

Output

Name MemberType Definition

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

TryParse Method static bool TryParse(string s, [ref] int result)

The TryParse method attempts to parse a string as an integer. If the method


succeeds,
it returns $true , and the result is stored in the variable you
passed by reference.

PS> $number = 0

PS> [int]::TryParse("15", ([ref]$number))

True

PS> $number

15

References and scopes


References allow the value of a variable in the parent scope to be changed
within a child
scope.

PowerShell

# Create a value type variable.

$i = 0

# Create a reference type variable.

$iRef = [ref]0

# Invoke a scriptblock to attempt to change both values.

&{$i++;$iRef.Value++}

# Output the results.

"`$i = $i;`$iRef = $($iRef.Value)"

Output

$i = 0;$iRef = 1

Only the reference type's variable was changed.

See also
about_Variables
about_Environment_Variables
about_Functions
about_Script_Blocks
about_Scopes
about_Registry_Provider
Article • 03/02/2023 • 9 minutes to read

Provider name
Registry

Drives
HKLM: , HKCU:

Capabilities
ShouldProcess, UseTransactions

Short description
Provides access to the registry keys, entries, and values in PowerShell.

Detailed description
The PowerShell Registry provider lets you get, add, change,
clear, and delete registry
keys, entries, and values in PowerShell.

The Registry drives are a hierarchical namespace containing the registry


keys and
subkeys on your computer. Registry entries and values are not
components of that
hierarchy. Instead, they are properties of each of the
keys.

The Registry provider supports the following cmdlets, which are covered
in this article.

Get-Location
Set-Location
Get-Item
Get-ChildItem
Invoke-Item
Move-Item
New-Item
Remove-Item
Clear-ItemProperty
Get-ItemProperty
New-ItemProperty
Remove-ItemProperty
Set-ItemProperty
Get-Acl
Set-Acl

Types exposed by this provider


Registry keys are represented as instances of the
Microsoft.Win32.RegistryKey
class.
Registry entries are represented as instances of the
PSCustomObject
class.

Navigating the Registry drives


The Registry provider exposes its data store as two default drives. The
registry location
HKEY_LOCAL_MACHINE is mapped to the HKLM: drive and
HKEY_CURRENT_USER is
mapped to the HKCU: drive. To work with the registry,
you can change your location to
the HKLM: drive using the following command.

PowerShell

Set-Location HKLM:

To return to a file system drive, type the drive name. For example, type:

PowerShell

Set-Location C:

You can also work with the Registry provider from any other PowerShell
drive. To
reference a registry key from another location, use the drive name
( HKLM: , HKCU: ) in the
path. Use a backslash ( \ ) or a forward slash ( / ) to
indicate a level of the Registry drive.

PowerShell

PS C:\> cd HKLM:\Software

7 Note
PowerShell uses aliases to allow you a familiar way to work with provider
paths.
Commands such as dir and ls are now aliases for
Get-ChildItem,
cd is an alias for
Set-Location,
and pwd is an alias for Get-Location.

This last example shows another path syntax you can use to navigate the
Registry
provider. This syntax uses the provider name, followed by two
colons :: . This syntax
allows you to use the full HIVE name, instead of the
mapped drive name HKLM .

PowerShell

cd "Registry::HKEY_LOCAL_MACHINE\Software"

Displaying the contents of registry keys


The registry is divided into keys, subkeys, and entries. For more information
about
registry structure, see Structure of the Registry.

In a Registry drive, each key is a container. A key can contain any number
of keys. A
registry key that has a parent key is called a subkey. You can
use Get-ChildItem to view
registry keys and Set-Location to navigate to
a key path.

Registry values are attributes of a registry key. In the Registry drive,


they are called Item
Properties. A registry key can have both children
keys and item properties.

In this example, the difference between Get-Item and Get-ChildItem is


shown. When
you use Get-Item on the "Spooler" registry key, you can view its
properties.

PowerShell

Get-Item -Path HKLM:\SYSTEM\CurrentControlSet\Services\Spooler

Output

Hive: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services

Name Property

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

Spooler DependOnService : {RPCSS, http}

Description : @%systemroot%\system32\spoolsv.exe,-2

DisplayName : @%systemroot%\system32\spoolsv.exe,-1

ErrorControl : 1

FailureActions : {16, 14, 0, 0...}

Group : SpoolerGroup

ImagePath : C:\WINDOWS\System32\spoolsv.exe

ObjectName : LocalSystem

RequiredPrivileges : {SeTcbPrivilege, SeImpersonatePrivilege,


...

ServiceSidType : 1

Start : 2

Type : 27

Each registry key can also have subkeys. When you use Get-Item on a registry
key, the
subkeys are not displayed. The Get-ChildItem cmdlet will show you
children items of
the "Spooler" key, including each subkey's properties. The
parent keys properties are not
shown when using Get-ChildItem .

PowerShell

Get-ChildItem -Path HKLM:\SYSTEM\CurrentControlSet\Services\Spooler

Output

Hive: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Spooler

Name Property

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

Performance Close : PerfClose

Collect : PerfCollect

Collect Timeout : 2000

Library : C:\Windows\System32\winspool.drv

Object List : 1450

Open : PerfOpen

Open Timeout : 4000

Security Security : {1, 0, 20, 128...}

The Get-Item cmdlet can also be used on the current location. The following
example
navigates to the "Spooler" registry key and gets the item properties.
The dot . is used
to indicate the current location.

PowerShell

cd HKLM:\System\CurrentControlSet\Services\Spooler

Get-Item .

Output

Hive: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services

Name Property

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

Spooler DependOnService : {RPCSS, http}

Description : @%systemroot%\system32\spoolsv.exe,-2

...

For more information on the cmdlets covered in this section, see the following
articles.

-Get-Item
-Get-ChildItem

Viewing registry key values


Registry key values are stored as properties of each registry key. The
Get-ItemProperty
cmdlet views registry key properties using the name you
specify. The result is a
PSCustomObject containing the properties you
specify.

The Following example uses the Get-ItemProperty cmdlet to view all


properties. Storing
the resulting object in a variable allows you to access
the desired property value.

PowerShell

$p = Get-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Services\Spooler

$p.DependOnService

Output

RPCSS

http

Specifying a value for the -Name parameter selects the properties you
specify and
returns the PSCustomObject. The following example shows
the difference in output
when you use the -Name parameter.

PowerShell

Get-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Wbem

Output

BUILD : 17134.1

Installation Directory : C:\WINDOWS\system32\WBEM

MOF Self-Install Directory : C:\WINDOWS\system32\WBEM\MOF

PSPath :
Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Wb
em

PSParentPath :
Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft

PSChildName : Wbem
PSDrive : HKLM
PSProvider : Microsoft.PowerShell.Core\Registry

PowerShell

Get-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Wbem -Name BUILD

Output

BUILD : 17134.1

PSPath :
Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Wb
em

PSParentPath :
Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft

PSChildName : Wbem

PSDrive : HKLM

PSProvider : Microsoft.PowerShell.Core\Registry

Beginning in PowerShell 5.0, the Get-ItemPropertyValue cmdlet returns


only the value of
the property you specify.

PowerShell

Get-ItemPropertyValue -Path HKLM:\SOFTWARE\Microsoft\Wbem -Name BUILD

Output

17134.1

For more information on the cmdlets used in this section, see the following
articles.

Get-ItemProperty
Get-ItemPropertyValue

Changing registry key values


The Set-ItemProperty cmdlet will set attributes for registry keys. The
following example
uses Set-ItemProperty to change the spooler service start
type to manual. The example
changes the StartType back to Automatic
using the Set-Service cmdlet.
PowerShell

Get-Service spooler | Select-Object Name, StartMode

Output

Name StartType

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

spooler Automatic

PowerShell

$path = "HKLM:\SYSTEM\CurrentControlSet\Services\Spooler\"

Set-ItemProperty -Path $path -Name Start -Value 3

Get-Service spooler | Select-Object Name, StartMode

Output

Name StartType

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

spooler Manual

PowerShell

Set-Service -Name Spooler -StartupType Automatic

Each registry key has a default value. You can change the default value
for a registry key
with either Set-Item or Set-ItemProperty .

PowerShell

Set-ItemProperty -Path HKLM:\SOFTWARE\Contoso -Name "(default)" -Value "one"

Set-Item -Path HKLM:\SOFTWARE\Contoso -Value "two"

For more information on the cmdlets used in this section, see the following
articles.

Set-Item
Set-ItemProperty

Creating registry keys and values


The New-Item cmdlet will create registry keys with a name that you provide.
You can also
use the mkdir function, which calls the New-Item cmdlet
internally.
PowerShell

mkdir ContosoCompany

Output

Hive: HKEY_LOCAL_MACHINE\SOFTWARE

Name Property

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

ContosoCompany

You can use the New-ItemProperty cmdlet to create values in a registry key
that you
specify. The following example creates a new DWORD value on the
ContosoCompany
registry key.

PowerShell

$path = "HKLM:\SOFTWARE\ContosoCompany"

New-ItemProperty -Path $path -Name Test -Type DWORD -Value 1

7 Note

Review the dynamic parameters section in this article for other allowed type
values.

For detailed cmdlet usage, see New-ItemProperty.

Copying registry keys and values


In the Registry provider, use the Copy-Item cmdlet copies registry keys
and values. Use
the Copy-ItemProperty cmdlet to copy registry values only.
The following command
copies the "Contoso" registry key, and its properties to
the specified location
"HKLM:\Software\Fabrikam".

Copy-Item creates the destination key if it does not exist. If the


destination key exists,

Copy-Item creates a duplicate of the source key


as a child item (subkey) of the
destination key.

PowerShell

Copy-Item -Path HKLM:\Software\Contoso -Destination HKLM:\Software\Fabrikam

The following command uses the Copy-ItemProperty cmdlet to copy the "Server"
value
from the "Contoso" key to the "Fabrikam" key.

PowerShell

$source = "HKLM:\SOFTWARE\Contoso"

$dest = "HKLM:\SOFTWARE\Fabrikam"

Copy-ItemProperty -Path $source -Destination $dest -Name Server

For more information on the cmdlets used in this section, see the following
articles.

Copy-Item
Copy-ItemProperty

Moving registry keys and values


The Move-Item and Move-ItemProperty cmdlets behave like their "Copy"
counterparts. If
the destination exists, Move-Item moves the source key
underneath the destination key.
If the destination key does not exist, the
source key is moved to the destination path.

The following command moves the "Contoso" key to the path


HKLM:\SOFTWARE\Fabrikam .

PowerShell

Move-Item -Path HKLM:\SOFTWARE\Contoso -Destination HKLM:\SOFTWARE\Fabrikam

This command moves all of the properties from HKLM:\SOFTWARE\ContosoCompany


to
HKLM:\SOFTWARE\Fabrikam .

PowerShell

$source = "HKLM:\SOFTWARE\Contoso"

$dest = "HKLM:\SOFTWARE\Fabrikam"

Move-ItemProperty -Path $source -Destination $dest -Name *

For more information on the cmdlets used in this section, see the following
articles.

Move-Item
Move-ItemProperty

Renaming registry keys and values


You can rename registry keys and values just like you would files and folders.
Rename-
Item renames registry keys, while Rename-ItemProperty renames
registry values.

PowerShell

$path = "HKLM:\SOFTWARE\Contoso"

Rename-ItemProperty -Path $path -Name ContosoTest -NewName FabrikamTest

Rename-Item -Path $path -NewName Fabrikam

Changing security descriptors


You can restrict access to registry keys using the Get-Acl and Set-Acl
cmdlets. The
following example adds a new user with full control to the
HKLM:\SOFTWARE\Contoso
registry key.

PowerShell

$acl = Get-Acl -Path HKLM:\SOFTWARE\Contoso

$rule = New-Object System.Security.AccessControl.RegistryAccessRule `

("CONTOSO\jsmith", "FullControl", "Allow")

$acl.SetAccessRule($rule)

$acl | Set-Acl -Path HKLM:\SOFTWARE\Contoso

For more examples and cmdlet usage details see the following articles.

Get-Acl
Set-Acl

Removing and clearing registry keys and values


You can remove contained items by using Remove-Item , but you will be
prompted to
confirm the removal if the item contains anything else. The
following example attempts
to delete a key HKLM:\SOFTWARE\Contoso .

PowerShell

dir HKLM:\SOFTWARE\Contoso\

Output

Hive: HKEY_LOCAL_MACHINE\SOFTWARE\Contoso

Name Property

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

ChildKey

PowerShell

Remove-Item -Path HKLM:\SOFTWARE\Contoso

Output

Confirm

The item at HKLM:\SOFTWARE\Contoso 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.

PowerShell

Remove-Item -Path HKLM:\SOFTWARE\Contoso -Recurse

If you wanted to remove all items within HKLM:\SOFTWARE\Contoso but not


HKLM:\SOFTWARE\Contoso itself, use a trailing backslash \ followed by a
wildcard.

PowerShell

Remove-Item -Path HKLM:\SOFTWARE\Contoso\* -Recurse

This command deletes the "ContosoTest" registry value from the


HKLM:\SOFTWARE\Contoso registry key.

PowerShell

Remove-ItemProperty -Path HKLM:\SOFTWARE\Contoso -Name ContosoTest

Clear-Item clears all registry values for a key. The following example
clears all values
from the HKLM:\SOFTWARE\Contoso registry key. To clear
only a specific property, use
Clear-ItemProperty .

PowerShell

Get-Item .\Contoso\

Output

Hive: HKEY_LOCAL_MACHINE\SOFTWARE

Name Property

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

Contoso Server : {a, b, c}

HereString : {This is text which contains

newlines. It also contains "quoted" strings}

(default) : 1

PowerShell

Clear-Item .\Contoso\

Get-Item .\Contoso\

Output

Hive: HKEY_LOCAL_MACHINE\SOFTWARE

Name Property

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

Contoso

For more examples and cmdlet usage details see the following articles.

Clear-Item
Clear-ItemProperty
Remove-Item
Remove-ItemProperty

Dynamic parameters
Dynamic parameters are cmdlet parameters that are added by a PowerShell
provider
and are available only when the cmdlet is being used in the
provider-enabled drive.

Type <Microsoft.Win32.RegistryValueKind>
Establishes or changes the data type of a registry value. The default is String (REG_SZ).

This parameter works as designed on the


Set-ItemProperty
cmdlet. It is also available on
the
Set-Item cmdlet in the
registry drives, but it has no effect.

Value Description
Value Description

String Specifies a null-terminated string. Used for REG_SZ values.

ExpandString Specifies a null-terminated string that contains unexpanded

references to environment variables that are expanded when

the value is retrieved. Used for REG_EXPAND_SZ values.

Binary Specifies binary data in any form. Used for REG_BINARY values.

DWord Specifies a 32-bit binary number. Used for REG_DWORD values.

MultiString Specifies an array of null-terminated strings terminated by

two null characters. Used for REG_MULTI_SZ values.

QWord Specifies a 64-bit binary number. Used for REG_QWORD values.

Unknown Indicates an unsupported registry data type, such as

REG_RESOURCE_LIST values.

Cmdlets supported

Set-Item
Set-ItemProperty

Using the pipeline


Provider cmdlets accept pipeline input. You can use the pipeline to simplify
task by
sending provider data from one cmdlet to another provider cmdlet. To
read more about
how to use the pipeline with provider cmdlets, see the cmdlet
references provided
throughout this article.

Getting help
Beginning in Windows PowerShell 3.0, you can get customized help topics for
provider
cmdlets that explain how those cmdlets behave in a file system drive.

To get the help topics that are customized for the file system drive, run a
Get-Help
command in a file system drive or use the Path parameter to
specify a file system drive.

PowerShell
Get-Help Get-ChildItem

PowerShell

Get-Help Get-ChildItem -Path HKLM:

See also
about_Providers
about_Regular_Expressions
Article • 04/11/2023

Short description
Describes regular expressions in PowerShell.

Long description

7 Note

This article will show you the syntax and methods for using regular
expressions in
PowerShell, not all syntax is discussed. For a more complete
reference, see the
Regular Expression Language - Quick Reference.

A regular expression is a pattern used to match text. It can be made up of


literal
characters, operators, and other constructs.

This article demonstrates regular expression syntax in PowerShell. PowerShell


has several
operators and cmdlets that use regular expressions. You can read
more about their
syntax and usage at the links below.

Select-String
-match and -replace operators
-split operator
switch statement with -regex option

PowerShell regular expressions are case-insensitive by default. Each method


shown
above has a different way to force case sensitivity.

For Select-String , use the CaseSensitive parameter.


For operators that use regular expressions, use the case-sensitive version:
-cmatch ,
-creplace , or -csplit

For the switch statement, use the -casesensitive option

Character literals
A regular expression can be a literal character or a string. The expression
causes the
engine to match the text specified exactly.
PowerShell

# This statement returns true because book contains the string "oo"

'book' -match 'oo'

Character classes
While character literals work if you know the exact pattern, character classes
allow you
to be less specific.

Character groups
[character group] allows you to match any number of characters one time,
while

[^character group] only matches characters NOT in the group.

PowerShell

# This expression returns true if the pattern matches big, bog, or bug.

'big' -match 'b[iou]g'

If your list of characters to match includes the hyphen character ( - ), it


must be at the
beginning or end of the list to distinguish it from a character
range expression.

Character ranges
A pattern can also be a range of characters. The characters can be alphabetic [A-Z] ,
numeric [0-9] , or even ASCII-based [ -~] (all printable characters).

PowerShell

# This expression returns true if the pattern matches any 2 digit number.

42 -match '[0-9][0-9]'

Numbers
The \d character class will match any decimal digit. Conversely, \D will
match any non-
decimal digit.

PowerShell
# This expression returns true if it matches a server name.

# (Server-01 - Server-99).

'Server-01' -match 'Server-\d\d'

Word characters
The \w character class will match any word character [a-zA-Z_0-9] . To match
any non-
word character, use \W .

PowerShell

# This expression returns true.

# The pattern matches the first word character 'B'.

'Book' -match '\w'

Wildcards
The period ( . ) is a wildcard character in regular expressions. It will match
any character
except a newline ( \n ).

PowerShell

# This expression returns true.

# The pattern matches any 4 characters except the newline.

'a1\ ' -match '....'

Whitespace
You can match any whitespace character with the \s character class. You can
match any
non-whitespace character with \S . You can match literal space
characters with .

PowerShell

# This expression returns true.

# The pattern uses the whitespace character class to match the leading

# space and a literal space to matching the trailing space.

' - ' -match '\s- '

Quantifiers
Quantifiers control how many instances of each element should be present in the
input
string.

The following are a few of the quantifiers available in PowerShell:

Quantifier Description

* Zero or more times.

+ One or more times.

? Zero or one time.

{n,m} At least n , but no more than m times.

The asterisk ( * ) matches the previous element zero or more times. The result
is that
even an input string without the element would be a match.

PowerShell

# This returns true for all account name strings even if the name is absent.

'ACCOUNT NAME: Administrator' -match 'ACCOUNT NAME:\s*\w*'

The plus sign ( + ) matches the previous element one or more times.

PowerShell

# This returns true if it matches any server name.

'DC-01' -match '[A-Z]+-\d\d'

The question mark ? matches the previous element zero or one time. Like
asterisk * , it
will even match strings where the element is absent.

PowerShell

# This returns true for any server name, even server names without dashes.

'SERVER01' -match '[A-Z]+-?\d\d'

The {n, m} quantifier can be used several different ways to allow granular
control over
the quantifier. The second element m and the comma , are
optional.

Quantifier Description

{n} Match EXACTLY n number of times.


Quantifier Description

{n,} Match at LEAST n number of times.

{n,m} Match between n and m number of times.

PowerShell

# This returns true if it matches any phone number.

'111-222-3333' -match '\d{3}-\d{3}-\d{4}'

Anchors
Anchors allow you to cause a match to succeed or fail based on the matches
position
within the input string.

The two commonly used anchors are ^ and $ . The caret ^ matches the start
of a string,
and $ , which matches the end of a string. The anchors allow you
to match your text at a
specific position while also discarding unwanted
characters.

PowerShell

# The pattern expects the string 'fish' to be the only thing on the line.

# This returns FALSE.

'fishing' -match '^fish$'

7 Note

When defining a regex containing an $ anchor, be sure to enclose the regex


using
single quotes ( ' ) instead of double quotes ( " ) or PowerShell will
expand the
expression as a variable.

When using anchors in PowerShell, you should understand the difference between
Singleline and Multiline regular expression options.

Multiline: Multiline mode forces ^ and $ to match the beginning end


of every
LINE instead of the beginning and end of the input string.
Singleline: Singleline mode treats the input string as a SingleLine.
It forces the .
character to match every character (including newlines),
instead of matching every
character EXCEPT the newline \n .
To read more about these options and how to use them, visit the
Regular Expression
Language - Quick Reference.

Escaping characters
The backslash ( \ ) is used to escape characters so they aren't parsed by the
regular
expression engine.

The following characters are reserved: []().\^$|?*+{} .

You'll need to escape these characters in your patterns to match them in your
input
strings.

PowerShell

# This returns true and matches numbers with at least 2 digits of precision.

# The decimal point is escaped using the backslash.

'3.141' -match '3\.\d{2,}'

There`s a static method of the regex class that can escape text for you.

PowerShell

[regex]::escape('3.\d{2,}')

Output

3\.\\d\{2,}

7 Note

This escapes all reserved regular expression characters, including existing


backslashes used in character classes. Be sure to only use it on the portion
of your
pattern that you need to escape.

Other character escapes


There are also reserved character escapes that you can use to match special
character
types.

The following are a few commonly used character escapes:


Character Escape Description

\t Matches a tab

\n Matches a newline

\r Matches a carriage return

Groups, Captures, and Substitutions


Grouping constructs separate an input string into substrings that can be
captured or
ignored. Grouped substrings are called subexpressions. By default
subexpressions are
captured in numbered groups, though you can assign names to
them as well.

A grouping construct is a regular expression surrounded by parentheses. Any


text
matched by the enclosed regular expression is captured. The following
example breaks
the input text into two capturing groups.

PowerShell

'The last logged on user was CONTOSO\jsmith' -match '(.+was )(.+)'

Output

True

Use the $Matches Hashtable automatic variable to retrieve captured text.


The text
representing the entire match is stored at key 0 . It is important to
note that the
$Matches hashtable contains only the first occurrence of any
matching pattern.

PowerShell

$Matches.0

Output

The last logged on user was CONTOSO\jsmith

Captures are stored in numeric Integer keys that increase from left to
right. Capture 1
contains all the text until the username, capture 2
contains just the username.

PowerShell
$Matches

Output

Name Value

---- -----

2 CONTOSO\jsmith

1 The last logged on user was

0 The last logged on user was CONTOSO\jsmith

) Important

The 0 key is an Integer. You can use any Hashtable method to access
the value
stored.

PS> 'Good Dog' -match 'Dog'

True

PS> $Matches[0]

Dog

PS> $Matches.Item(0)

Dog

PS> $Matches.0

Dog

Named Captures
By default, captures are stored in ascending numeric order, from left to right.
You can
also assign a name to a capturing group. This name becomes a
key on the $Matches
Hashtable automatic variable.

Inside a capturing group, use ?<keyname> to store captured data under a named
key.

PS> $string = 'The last logged on user was CONTOSO\jsmith'

PS> $string -match 'was (?<domain>.+)\\(?<user>.+)'

True

PS> $Matches

Name Value

---- -----

domain CONTOSO

user jsmith

0 was CONTOSO\jsmith

PS> $Matches.domain

CONTOSO

PS> $Matches.user

jsmith

The following example stores the newest log entry in the Windows Security Log.
The
provided regular expression extracts the username and domain from the
message and
stores them under the keys:N for name and D for domain.

PowerShell

$log = (Get-EventLog -LogName Security -Newest 1 -InstanceId 4689).message

$r = '(?s).*Account Name:\s*(?<N>.*).*Account Domain:\s*(?<D>[A-Z,0-9]*)'

$log -match $r

Output

True

PowerShell

$Matches

Output

Name Value

---- -----

D CONTOSO

N jsmith

0 A process has exited....

For more information, see


Grouping Constructs in Regular Expressions.

Substitutions in Regular Expressions


Using the regular expressions with the -replace operator allows you to
dynamically
replace text using captured text.
<input> -replace <original>, <substitute>

<input> : The string to be searched


<original> : A regular expression used to search the input string

<substitute> : A regular expression substitution expression to replace


matches
found in the input string.

7 Note

The <original> and <substitute> operands are subject to rules of the


regular
expression engine such as character escaping.

Capturing groups can be referenced in the <substitute> string. The


substitution is done
by using the $ character before the group identifier.

Two ways to reference capturing groups are by Number and by Name.

By Number - Capturing Groups are numbered from left to right.

PowerShell

'John D. Smith' -replace '(\w+) (\w+)\. (\w+)', '$1.$2.$3@contoso.com'

Output

John.D.Smith@contoso.com

By Name - Capturing Groups can also be referenced by name.

PowerShell

'CONTOSO\Administrator' -replace '\w+\\(?<user>\w+)',


'FABRIKAM\${user}'

Output

FABRIKAM\Administrator

The $& expression represents all the text matched.

PowerShell

'Gobble' -replace 'Gobble', '$& $&'

Output

Gobble Gobble

2 Warning

Since the $ character is used in string expansion, you'll need to use


literal strings
with substitution, or escape the $ character when using
double quotes.

PowerShell

'Hello World' -replace '(\w+) \w+', '$1 Universe'

"Hello World" -replace "(\w+) \w+", "`$1 Universe"

Output

Hello Universe

Hello Universe

Additionally, if you want to have the $ as a literal character, use $$


instead of the
normal escape characters. When using double quotes, still
escape all instances of $
to avoid incorrect substitution.

PowerShell

'5.72' -replace '(.+)', '$$$1'

"5.72" -replace "(.+)", "`$`$`$1"

Output

$5.72

$5.72

For more information, see Substitutions in Regular Expressions.

See also
about_Operators
about_Comparison_Operators
about_Remote
Article • 09/19/2022 • 5 minutes to read

Short description
Describes how to run remote commands in 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 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:

PowerShell

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:

PowerShell

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 PowerShell


remoting, you
can use the ComputerName parameter of these cmdlets on any
computer that is
running PowerShell. The computers do not have to be
configured for 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 Stop-Computer

Get-WinEvent Test-Connection
Get-WmiObject Write-EventLog

For example, the following command gets the services on


the Server01 remote
computer:
PowerShell

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:

PowerShell

Get-Command | Where-Object {

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

PowerShell

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.

PowerShell

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

PowerShell

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.

PowerShell

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:

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

PowerShell

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

PowerShell

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:

PowerShell

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
PowerShell Remoting FAQ.

For help in resolving remoting errors, see about_Remote_Troubleshooting.

For information about PSSessions and persistent connections, see


about_PSSessions.

For information about PowerShell background jobs, see about_Jobs.

KEYWORDS
about_Remoting

See also
about_PSSessions
about_Remote_Disconnected_Sessions
about_Remote_Requirements
about_Remote_TroubleShooting
about_Remote_Variables
Invoke-Command
Enter-PSSession
New-PSSession
PowerShell Remoting FAQ
about_Remote_Disconnected_Sessions
Article • 09/19/2022 • 16 minutes to read

Short description
Explains how to disconnect and reconnect to a PowerShell Session (PSSession).

Long description
Beginning in PowerShell 3.0, you can disconnect from a PSSession and reconnect
to the
PSSession on the same computer or a different computer. The session
state is
maintained and commands in the PSSession continue to run while the
session is
disconnected.

The Disconnected Sessions feature is only available when the remote computer is
running PowerShell 3.0 or a later version.

The Disconnected Sessions feature allows you to close the session in which a
PSSession
was created, and even close PowerShell, and shut down the computer,
without
disrupting commands running in the PSSession. Disconnected sessions are
useful for
running commands that take an extended time to complete, and
provides the time and
device flexibility that IT professionals require.

You can't disconnect from an interactive session that is started by using the
Enter-
PSSession cmdlet.

You can use disconnected sessions to manage PSSessions that were disconnected
unintentionally as the result of a computer or network outage.

In real-world use, the Disconnected Sessions feature allows you to begin


solving a
problem, turn your attention to a higher priority issue, and then
resume work on the
solution, even on a different computer in a different
location.

Disconnected session cmdlets


The following cmdlets support the Disconnected Sessions feature:

Connect-PSSession : Connects to a disconnected PSSession.

Disconnect-PSSession : Disconnects a PSSession.


Get-PSSession : Gets PSSessions on the local computer or on remote computers.
Receive-PSSession : Gets the results of commands that ran in disconnected

sessions.
Invoke-Command : InDisconnectedSession parameter creates a PSSession and

disconnects immediately.

How the Disconnected Sessions feature works


Beginning in PowerShell 3.0, PSSessions are independent of the sessions in
which they're
created. Active PSSessions are maintained on the remote computer
or server-side of the
connection, even if the session in which the
PSSession was created is closed and the
originating computer is shut down or
disconnected from the network.

In PowerShell 2.0, the PSSession is deleted from the remote computer when it's
disconnected from the originating session or the session in which it was
created ends.

When you disconnect a PSSession, the PSSession remains active and is maintained
on
the remote computer. The session state changes from Running to
Disconnected. You
can reconnect to a disconnected PSSession from the
current session or from a different
session on the same computer, or from a
different computer. The remote computer that
maintains the session must be
running and be connected to the network.

Commands in a disconnected PSSession continue to run uninterrupted on the


remote
computer until the command completes or the output buffer fills. To
prevent a full
output buffer from suspending a command, use the
OutputBufferingMode parameter
of the Disconnect-PSSession ,
New-PSSessionOption , or New-PSTransportOption cmdlets.

Disconnected sessions are maintained in the disconnected state on the remote


computer. They're available for you to reconnect, until you delete the
PSSession, such as
by using the Remove-PSSession cmdlet, or until the idle
timeout of the PSSession expires.
You can adjust the idle timeout of a
PSSession by using the IdleTimeoutSec or
IdleTimeout parameters of the
Disconnect-PSSession , New-PSSessionOption , or New-
PSTransportOption
cmdlets.

Another user can connect to PSSessions that you created, but only if they can
provide
the credentials that were used to create the session, or use the
RunAs credentials of the
session configuration.

How to get PSSessions


Beginning in PowerShell 3.0, the Get-PSSession cmdlet gets PSSessions on the
local
computer and remote computers. It can also get PSSessions that were
created in the
current session.

To get PSSessions on the local computer or remote computers, use the


ComputerName
or ConnectionUri parameters. Without parameters,
Get-PSSession gets PSSession that
were created in the local session,
regardless of where they terminate.

When getting PSSessions, remember to look for them on the computer on which
they're
maintained, that is, the remote or server-side computer.

For example, if you create a PSSession to the Server01 computer, get the
session from
the Server01 computer. If you create a PSSession from another
computer to the local
computer, get the session from the local computer.

The following command sequence shows how Get-PSSession works.

The first command creates a session to the Server01 computer. The session
resides on
the Server01 computer.

PowerShell

New-PSSession -ComputerName Server01

Output

Id Name ComputerName State ConfigurationName Availability

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

2 Session2 Server01 Opened Microsoft.PowerShell Available

To get the session, use the ComputerName parameter of Get-PSSession with


a value of
Server01.

PowerShell

Get-PSSession -ComputerName Server01

Output

Id Name ComputerName State ConfigurationName Availability

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

2 Session2 Server01 Opened Microsoft.PowerShell Available

If the value of the ComputerName parameter of Get-PSSession is localhost,


Get-
PSSession gets PSSessions that terminate at and are maintained on the
local computer.
It doesn't get PSSessions on the Server01 computer, even if
they were started on the
local computer.

PowerShell

Get-PSSession -ComputerName localhost

To get sessions that were created in the current session, use the
Get-PSSession cmdlet
without parameters. In this example, Get-PSSession
gets the PSSession that was created
in the current session and connects to the
Server01 computer.

PowerShell

Get-PSSession

Output

Id Name ComputerName State ConfigurationName Availability

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

2 Session2 Server01 Opened Microsoft.PowerShell Available

How to disconnect sessions


To disconnect a PSSession, use the Disconnect-PSSession cmdlet. To identify
the
PSSession, use the Session parameter, or pipeline a PSSession from the
New-PSSession
or Get-PSSession cmdlets to Disconnect-PSSession .

The following command disconnects the PSSession to the Server01 computer.


Notice
that the value of the State property is Disconnected and the
Availability is None.

PowerShell

Get-PSSession -ComputerName Server01 | Disconnect-PSSession

Output

Id Name ComputerName State ConfigurationName Availability

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

2 Session2 Server01 Disconnected Microsoft.PowerShell None

To create a disconnected session, use the InDisconnectedSession parameter


of the
Invoke-Command cmdlet. It creates a session, starts the command, and
disconnects
immediately, before the command can return any output.

The following command runs a Get-WinEvent command in a disconnected session


on
the Server02 remote computer.

PowerShell

Invoke-Command -ComputerName Server02 -InDisconnectedSession -ScriptBlock {

Get-WinEvent -LogName "*PowerShell*" }

Output

Id Name ComputerName State ConfigurationName Availability

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

4 Session3 Server02 Disconnected Microsoft.PowerShell None

How to connect to disconnected sessions


You can connect to any available disconnected PSSession from the session in
which you
created the PSSession or from other sessions on the local computer or
other computers.

You can create a PSSession, run commands in the PSSession, disconnect from the
PSSession, close PowerShell, and shut down the computer. Hours later, you can
open a
different computer, get the PSSession, connect to it, and get the
results of commands
that ran in the PSSession while it was disconnected. Then
you can run more commands
in the session.

To connect a disconnected PSSession, use the Connect-PSSession cmdlet. Use


the
ComputerName or ConnectionUri parameters to identify the PSSession,
or pipeline a
PSSession from Get-PSSession to Connect-PSSession .

The following command gets the sessions on the Server02 computer. The output
includes two disconnected sessions, both of which are available.

PowerShell

Get-PSSession -ComputerName Server02

Output

Id Name ComputerName State ConfigurationName Availability

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

2 Session2 juneb-srv8320 Disconnected Microsoft.PowerShell None

4 Session3 juneb-srv8320 Disconnected Microsoft.PowerShell None

The following command connects to Session2. The PSSession is now open and
available.

PowerShell

Connect-PSSession -ComputerName Server02 -Name Session2

Output

Id Name ComputerName State ConfigurationName Availability

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

2 Session2 juneb-srv8320 Opened Microsoft.PowerShell Available

How to get the results


To get the results of commands that ran in a disconnected PSSession, use the
Receive-
PSSession cmdlet.

You can use Receive-PSSession rather than using the Connect-PSSession


cmdlet. If the
session is already reconnected, Receive-PSSession gets the
results of commands that
ran when the session was disconnected. If the
PSSession is still disconnected, Receive-
PSSession connects to it and then
gets the results of commands that ran while it was

disconnected.

Receive-PSSession can return the results in a job (asynchronously) or to the


host

program (synchronously). Use the OutTarget parameter to select Job


or Host. The
default value is Host. However, if the command that's
being received was started in the
current session as a Job, it's returned
as a Job by default.

The following command uses the Receive-PSSession cmdlet to connect to the


PSSession
on the Server02 computer and get the results of the Get-WinEvent
command that ran in
the Session3 session. The command uses the OutTarget
parameter to get the results in a
Job.

PowerShell

Receive-PSSession -ComputerName Server02 -Name Session3 -OutTarget Job

Output

Id Name PSJobTypeName State HasMoreData Location

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

3 Job3 RemoteJob Running True Server02

To get the job's results, use the Receive-Job cmdlet.

PowerShell

Get-Job | Receive-Job -Keep

Output

ProviderName: PowerShell

TimeCreated Id LevelDisplayName Message PSComputerName

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

5/14/2012 7:26:04 PM 400 Information Engine stat Server02

5/14/2012 7:26:03 PM 600 Information Provider "W Server02

5/14/2012 7:26:03 PM 600 Information Provider "C Server02

5/14/2012 7:26:03 PM 600 Information Provider "V Server02

State and Availability properties


The State and Availability properties of a disconnected PSSession tell
you whether the
session is available for you to reconnect to it.

When a PSSession is connected to the current session, its state is Opened


and its
availability is Available. When you disconnect from the PSSession,
the PSSession state is
Disconnected and its availability is None.

The value of the State property is relative to the current session. A value
of
Disconnected means that the PSSession isn't connected to the current
session. But, it
doesn't mean that the PSSession is disconnected from all
sessions. It might be
connected to a different session.

To determine whether you can connect or reconnect to the PSSession, use the
Availability property. A value of None indicates that you can connect
to the session. A
value of Busy indicates that you can't connect to the
PSSession because it's connected
to another session.

The following example is run in two PowerShell sessions on the same computer.
Note
the changing values of the State and Availability properties in
each session as the
PSSession is disconnected and reconnected.

PowerShell
# Session 1

New-PSSession -ComputerName Server30 -Name Test

Output

Id Name ComputerName State ConfigurationName Availability

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

1 Test Server30 Opened Microsoft.PowerShell Available

PowerShell

# Session 2

Get-PSSession -ComputerName Server30 -Name Test

Output

Id Name ComputerName State ConfigurationName Availability

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

1 Test Server30 Disconnected Microsoft.PowerShell Busy

PowerShell

# Session 1

Get-PSSession -ComputerName Server30 -Name Test | Disconnect-PSSession

Output

Id Name ComputerName State ConfigurationName Availability

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

1 Test Server30 Disconnected Microsoft.PowerShell None

PowerShell

# Session 2

Get-PSSession -ComputerName Server30

Output

Id Name ComputerName State ConfigurationName Availability

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

1 Test Server30 Disconnected Microsoft.PowerShell None

PowerShell
# Session 2

Connect-PSSession -ComputerName Server30 -Name Test

Output

Id Name ComputerName State ConfigurationName Availability

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

3 Test Server30 Opened Microsoft.PowerShell Available

PowerShell

# Session 1

Get-PSSession -ComputerName Server30

Output

Id Name ComputerName State ConfigurationName Availability

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

1 Test Server30 Disconnected Microsoft.PowerShell Busy

Output

# Idle Timeout

Disconnected sessions are maintained on the remote computer until you delete
them,
such as by using the Remove-PSSession cmdlet, or they time out. The
IdleTimeout
property of a PSSession determines how long a disconnected
session is maintained
before it's deleted.

PSSessions are idle when the heartbeat thread receives no response.


Disconnecting a
session makes it idle and starts the IdleTimeout clock,
even if commands are still
running in the disconnected session. PowerShell
considers disconnected sessions to be
active, but idle.

When creating and disconnecting sessions, verify that the idle timeout in the
PSSession
is long enough to maintain the session for your needs, but not so
long that it consumes
unnecessary resources on the remote computer.

The IdleTimeoutMs property of the session configuration determines the


default idle
timeout of sessions that use the session configuration. You can
override the default
value, but the value that you use can't exceed the
MaxIdleTimeoutMs property of the
session configuration.
To find the value of the IdleTimeoutMs and MaxIdleTimeoutMs values of a
session
configuration, use the following command format.

PowerShell

Get-PSSessionConfiguration |

Format-Table Name, IdleTimeoutMs, MaxIdleTimeoutMs

You can override the default value in the session configuration and set the
idle timeout
of a PSSession when you create a PSSession and when you
disconnect.

If you're a member of the Administrators group on the remote computer, you can
create
and change the IdleTimeoutMs and MaxIdleTimeoutMs properties of
session
configurations.

Idle timeout values


The idle timeout value of session configurations and session options is in
milliseconds.
The idle timeout value of sessions and session configuration
options is in seconds.

You can set the idle timeout of a PSSession when you create the PSSession
( New-
PSSession , Invoke-Command ) and when you disconnect from it
( Disconnect-PSSession ).

However, you can't change the IdleTimeout value


when you connect to the PSSession
( Connect-PSSession ) or get results
( Receive-PSSession ).

The Connect-PSSession and Receive-PSSession cmdlets have a


SessionOption
parameter that takes a SessionOption object, such as one
returned by the New-
PSSessionOption cmdlet. The IdleTimeout value in
SessionOption object and the

IdleTimeout value in the


$PSSessionOption preference variable don't change the value
of the
IdleTimeout of the PSSession in a Connect-PSSession or
Receive-PSSession
command.

To create a PSSession with a particular idle timeout value, create a


$PSSessionOption
preference variable. Set the value of the IdleTimeout
property to the desired value (in
milliseconds).

When you create PSSessions, the values in $PSSessionOption variable take


precedence
over the values in the session configuration.

For example, the following command sets an idle timeout of 48 hours:

PowerShell
$PSSessionOption = New-PSSessionOption -IdleTimeoutMSec 172800000

To create a PSSession with a particular idle timeout value, use the


IdleTimeoutMSec
parameter of the New-PSSessionOption cmdlet. Then, use
the session option in the value
of the SessionOption parameter of the
New-PSSession or Invoke-Command cmdlets.

The values set when creating the session take precedence over the values set
in the
$PSSessionOption preference variable and the session configuration.

For example:

PowerShell

$o = New-PSSessionOption -IdleTimeoutMSec 172800000

New-PSSession -SessionOption $o

To change the idle timeout of a PSSession when disconnecting, use the


IdleTimeoutSec
parameter of the Disconnect-PSSession cmdlet.

For example:

PowerShell

Disconnect-PSSession -IdleTimeoutSec 172800

To create a session configuration with a particular idle timeout and maximum


idle
timeout, use the IdleTimeoutSec and MaxIdleTimeoutSec parameters
of the New-
PSTransportOption cmdlet. Then, use the transport option in the
value of the

TransportOption parameter of
Register-PSSessionConfiguration .

For example:

PowerShell

$o = New-PSTransportOption -IdleTimeoutSec 172800 -MaxIdleTimeoutSec 259200

Register-PSSessionConfiguration -Name Test -TransportOption $o

To change the default idle timeout and maximum idle timeout of a session
configuration, use the IdleTimeoutSec and MaxIdleTimeoutSec
parameters of the New-
PSTransportOption cmdlet. Then, use the transport
option in the value of the

TransportOption parameter of
Set-PSSessionConfiguration .
For example:

PowerShell

$o = New-PSTransportOption -IdleTimeoutSec 172800 -MaxIdleTimeoutSec 259200

Set-PSSessionConfiguration -Name Test -TransportOption $o

Output buffering mode


The output buffering mode of a PSSession determines how command output is
managed when the output buffer of the PSSession is full.

In a disconnected session, the output buffering mode effectively determines


whether
the command continues to run while the session is disconnected.

The valid values as follows:

Block. When the output buffer is full, execution is suspended until the
buffer is
clear. The default value.
Drop. When the output buffer is full, execution continues. As new output
is
generated, the oldest output is discarded.

Block preserves data, but might interrupt the command. A value of Drop
allows the
command to complete, although data might be lost. When using the
Drop value,
redirect the command output to a file on disk. This value is
recommended for
disconnected sessions.

The OutputBufferingMode property of the session configuration determines


the default
output buffering mode of sessions that use the session
configuration.

To find a session configuration's value of the OutputBufferingMode, you can


use either
of the following command formats:

PowerShell

(Get-PSSessionConfiguration <ConfigurationName>).OutputBufferingMode

PowerShell

Get-PSSessionConfiguration | Format-Table Name, OutputBufferingMode

You can override the default value in the session configuration and set the
output
buffering mode of a PSSession when you create a PSSession, when you
disconnect, and
when you reconnect.

If you're a member of the Administrators group on the remote computer, you can
create
and change the output buffering mode of session configurations.

To create a PSSession with an output buffering mode of Drop, create a


$PSSessionOption preference variable in which the value of the
OutputBufferingMode

property is Drop.

When you create PSSessions, the values in $PSSessionOption variable take


precedence
over the values in the session configuration.

For example:

PowerShell

$PSSessionOption = New-PSSessionOption -OutputBufferingMode Drop

To create a PSSession with an output buffering mode of Drop, use the


OutputBufferingMode parameter of the New-PSSessionOption cmdlet to
create a
session option with a value of Drop. Then, use the session
option in the value of the
SessionOption parameter of the New-PSSession
or Invoke-Command cmdlets.

The values set when creating the session take precedence over the values set
in the
$PSSessionOption preference variable and the session configuration.

For example:

PowerShell

$o = New-PSSessionOption -OutputBufferingMode Drop

New-PSSession -SessionOption $o

To change the output buffering mode of a PSSession when disconnecting, use


the
OutputBufferingMode parameter of the Disconnect-PSSession cmdlet.

For example:

PowerShell

Disconnect-PSSession -OutputBufferingMode Drop

To change the output buffering mode of a PSSession when reconnecting, use the
OutputBufferingMode parameter of the New-PSSessionOption cmdlet to
create a
session option with a value of Drop. Then, use the session
option in the value of the
SessionOption parameter of Connect-PSSession
or Receive-PSSession .

For example:

PowerShell

$o = New-PSSessionOption -OutputBufferingMode Drop

Connect-PSSession -ComputerName Server01 -Name Test -SessionOption $o

To create a session configuration with a default output buffering mode of


Drop, use the
OutputBufferingMode parameter of the
New-PSTransportOption cmdlet to create a
transport option object with a
value of Drop. Then, use the transport option in the value
of the
TransportOption parameter of Register-PSSessionConfiguration .

For example:

PowerShell

$o = New-PSTransportOption -OutputBufferingMode Drop

Register-PSSessionConfiguration -Name Test -TransportOption $o

To change the default output buffering mode of a session configuration, use


the
OutputBufferingMode parameter of the New-PSTransportOption cmdlet
to create a
transport option with a value of Drop. Then, use the
Transport option in the value of the
SessionOption parameter of
Set-PSSessionConfiguration .

For example:

PowerShell

$o = New-PSTransportOption -OutputBufferingMode Drop

Set-PSSessionConfiguration -Name Test -TransportOption $o

Disconnecting loopback sessions


Loopback sessions, or local sessions, are PSSessions that originate and
terminate on the
same computer. Like other PSSessions, active loopback sessions
are maintained on the
computer on the remote end of the connection (the local
computer), so you can
disconnect from and reconnect to loopback sessions.

By default, loopback sessions are created with a network security token that
doesn't
permit commands run in the session to access other computers. You can
reconnect to
loopback sessions that have a network security token from any
session on the local
computer or a remote computer.

However, if you use the EnableNetworkAccess parameter of the


New-PSSession , Enter-
PSSession , or Invoke-Command cmdlet, the loopback
session is created with an interactive
security token. The interactive token
enables commands that run in the loopback
session to get data from other
computers.

You can disconnect loopback sessions with interactive tokens and then reconnect
to
them from the same session or a different session on the same computer.
However, to
prevent malicious access, you can reconnect to loopback sessions
with interactive
tokens only from the computer on which they were created.

Waiting for jobs in disconnected sessions


The Wait-Job cmdlet waits until a job completes and then returns to the
command
prompt or the next command. By default, Wait-Job returns if the
session in which a job
is running is disconnected. To direct the Wait-Job
cmdlet to wait until the session is
reconnected, in the Opened state, use
the Force parameter. For more information, see
Wait-Job.

Robust sessions and unintentional


disconnection
A PSSession might be unintentionally disconnected because of a computer failure
or
network outage. PowerShell attempts to recover the PSSession, but its
success depends
upon the severity and duration of the cause.

The state of an unintentionally disconnected PSSession might be Broken or


Closed, but
it might also be Disconnected. If the value of State is
Disconnected, you can use the
same techniques to manage the PSSession as
you would if the session were
disconnected intentionally. For example, you can
use the Connect-PSSession cmdlet to
reconnect to the session and the
Receive-PSSession cmdlet to get results of commands
that ran while the
session was disconnected.

If you close (exit) the session in which a PSSession was created while commands
are
running in the PSSession, PowerShell maintains the PSSession in the
Disconnected state
on the remote computer. If you close (exit) the session
in which a PSSession was
created, but no commands are running in the PSSession,
PowerShell doesn't attempt to
maintain the PSSession.
See also
about_Jobs
about_Remote
about_Remote_Variables
about_PSSessions
about_Session_Configurations
Invoke-Command
Connect-PSSession
Disconnect-PSSession
Get-PSSession
Receive-PSSession
about_Remote_Jobs
Article • 09/19/2022 • 11 minutes to read

Short description
Describes how to run jobs on remote computers.

Detailed Description
PowerShell concurrently runs commands and scripts through jobs. There are three
jobs
types provided by PowerShell to support concurrency.

RemoteJob - Commands and scripts run in a remote session.

BackgroundJob - Commands and scripts run in a separate process on the local

machine. For more information, see about_Jobs.


PSTaskJob or ThreadJob - Commands and scripts run in a separate thread
within

the same process on the local machine. For more information, see
about_Thread_Jobs.

Running scripts remotely, on a separate machine or in a separate process,


provide great
isolation. Any errors that occur in the remote job do not affect
other running jobs or the
parent session that started the job. However, the
remoting layer adds overhead,
including object serialization. All objects are
serialized and deserialized as they are
passed between the parent session and
the remote (job) session. Serialization of large
complex data objects can
consume large amounts of compute and memory resources
and transfer large
amounts of data across the network.

) Important

The parent session that created the job also monitors the job status and
collects
pipeline data. The job child process is terminated by the parent
process once the
job reaches a finished state. If the parent session is
terminated, all running child
jobs are terminated along with their child
processes.

There are two ways work around this situation:

1. Use Invoke-Command to create jobs that run in disconnected sessions. See


the
detached processes section of this
article.
2. Use Start-Process to create a new process rather than a job. For more
information, see
Start-Process.

Remote Jobs
You can run jobs on remote computers by using three different
methods.

Start an interactive session on a remote computer. Then 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 job on a remote computer that returns its results to the


local computer. Use
this method when you want to collect the results of
jobs and maintain them in a
central location on the local
computer.

Run a 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 job in an interactive session


You can start an interactive session with a remote computer and then start a
job during
the interactive session. For more information about interactive
sessions, see
about_Remote, and see Enter-PSSession .

The procedure for starting a 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.

1. 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 PowerShell
session
(PSSession).

The following command starts an interactive session on the Server01 computer.

PowerShell

C:\PS> Enter-PSSession -computername Server01

The command prompt changes to show that you are now connected to the
Server01 computer.

Server01\C:>

2. To start a remote job in the session, use the Start-Job cmdlet. The
following
command runs a remote 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.

PowerShell

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

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

PowerShell

Server01\C:> Get-Job $job

SessionId Name State HasMoreData Location Command

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

1 Job1 Complete True localhost Get-Eventlog


"Windows...

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

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

PowerShell

Server01\C:> Receive-Job $job > c:\logs\PsLog.txt

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

PowerShell

Server01\C:> Exit-PSSession

C:\PS>

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

PowerShell

$s = New-PSSession -computername Server01

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

1. The following command uses the AsJob parameter of Invoke-Command to


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

PowerShell

Invoke-Command -computername Server01 -scriptblock {

Get-Eventlog system} -AsJob

The results of the command resemble the following sample output.

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.

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

PowerShell

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.

Output

SessionId Name State HasMoreData Location Command

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

1 Job1 Completed True Server01 Get-Eventlog


system

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

PowerShell

$results = Receive-Job -id 1

Start a remote job that keeps the results on the remote


computer
To start a 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 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.

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

PowerShell

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

PowerShell

Invoke-Command -session $s -scriptblock {

Start-Job -scriptblock {Get-Eventlog system}}

The results resemble the following sample output.

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.

2. To manage a remote 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.

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

Output

SessionId Name State HasMoreData Location Command

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

2 Job2 Completed True LocalHost Get-Eventlog


system

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

PowerShell

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

PowerShell

Invoke-Command -session $s -command {

Receive-Job -SessionId 2 > c:\logs\pslog.txt

How to run as a detached process


As previously mentioned, when the parent session is terminated, all running
child jobs
are terminated along with their child processes. You can use
remoting on the local
machine to run jobs that are not attached to the current
PowerShell session.
Create a new PowerShell session on the local machine. The use Invoke-Command
to start a
job in this session. Invoke-Command allows you to disconnect a
remote session and
terminate the parent session. Later, you can start a new
PowerShell session and connect
to the previously disconnected session to resume
monitoring the job. However, any data
that was returned to the original
PowerShell session is lost when that session is
terminated. Only new data
objects generated after the disconnect are returned when re-
connected.

PowerShell

# Create remote session on local machine

PS> $session = New-PSSession -cn localhost

# Start remote job

PS> $job = Invoke-Command -Session $session -ScriptBlock { 1..60 | % { sleep


1; "Output $_" } } -AsJob

PS> $job

Id Name PSJobTypeName State HasMoreData Location


Command

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


-------

1 Job1 RemoteJob Running True localhost


1..60 | % { sleep 1; ...

# Disconnect the job session

PS> Disconnect-PSSession $session

Id Name Transport ComputerName ComputerType State


ConfigurationName Availability

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


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

1 Runspace1 WSMan localhost RemoteMachine Disconnected


Microsoft.PowerShell None

PS> $job

Id Name PSJobTypeName State HasMoreData Location


Command

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


-------

1 Job1 RemoteJob Disconnected True localhost


1..60 | % { sleep 1;

# Reconnect the session to a new job object

PS> $jobNew = Receive-PSSession -Session $session -OutTarget Job

PS> $job | Wait-Job | Receive-Job

Output 9

Output 10

Output 11

...

For this example, the jobs are still attached to a parent PowerShell session.
However, the
parent session is not the original PowerShell session where
Invoke-Command was run.

See also
about_Jobs
about_Job_Details
about_Remote
about_Remote_Variables
Invoke-Command
Get-Job
Remove-Job
Start-Job
Stop-Job
Wait-Job
Enter-PSSession
Exit-PSSession
New-PSSession
about_Remote_Output
Article • 09/19/2022 • 5 minutes to read

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.

PowerShell

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.

PowerShell

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.

PowerShell

$dates = invoke-command -script {get-date} -computername Server01, Server02

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

PowerShell

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.

PowerShell

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

PowerShell

C:\PS> $p = get-process PowerShell -comp Server01, Server02

C:\PS> $p | format-table -property Handles, `

@{Label="NPM(K)";Expression={int}}, `

@{Label="PM(K)";Expression={int}}, `

@{Label="WS(K)";Expression={int}}, `

@{Label="VM(M)";Expression={int}}, `

@{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
about_Remote_Variables
Invoke-Command
Get-EventLog
Out-GridView
Select-Object
Get-Process
Get-Service
Format-Table
Get-WmiObject
about_Remote_Requirements
Article • 09/19/2022 • 6 minutes to read

Short description
Describes the system requirements and configuration requirements for running
remote
commands in PowerShell.

Long description
This topic describes the system requirements, user requirements, and resource
requirements for establishing remote connections and running remote commands
in
PowerShell. It also provides instructions for configuring remote
operations.

7 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
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
To run remote sessions on Windows PowerShell 3.0, the local and remote computers
must have the following:

Windows PowerShell 3.0 or later


The Microsoft .NET Framework 4 or later
Windows Remote Management 3.0

To run remote sessions on Windows PowerShell 2.0, the local and remote
computers
must have the following:

Windows PowerShell 2.0 or later


The Microsoft .NET Framework 2.0 or later
Windows Remote Management 2.0

You can create remote sessions between computers running Windows PowerShell
2.0
and Windows PowerShell 3.0. However, features that run only on Windows
PowerShell
3.0, such as the ability to disconnect and reconnect to sessions,
are available only when
both computers are running Windows PowerShell 3.0.

To find the version number of an installed version of PowerShell,


use the
$PSVersionTable automatic variable.

Windows Remote Management (WinRM) 3.0 and Microsoft .NET Framework 4 are
included in Windows 8, Windows Server 2012, and newer releases of the Windows
operating system. WinRM 3.0 is included in Windows Management Framework 3.0
for
older operating systems. If the computer does not have the required
version of WinRM
or the Microsoft .NET Framework, the installation fails.

User permissions
To create remote sessions and run remote commands, by default, the current
user must
be a member of the Administrators group on the remote computer or
provide the
credentials of an administrator. Otherwise, the command fails.

The permissions required to create sessions and run commands on a remote


computer
(or in a remote session on the local computer) are established by the
session
configuration (also known as an endpoint) on the remote computer to
which the
session connects. Specifically, the security descriptor on the
session configuration
determines who has access to the session configuration
and who can use it to connect.

The security descriptors on the default session configurations,


Microsoft.PowerShell,
Microsoft.PowerShell32, and
Microsoft.PowerShell.Workflow, allow access only to
members of the
Administrators group.

If the current user doesn't have permission to use the session configuration,
the
command to run a command (which uses a temporary session) or create a
persistent
session on the remote computer fails. The user can use the
ConfigurationName
parameter of cmdlets that create sessions to select a
different session configuration, if
one is available.

Members of the Administrators group on a computer can determine who has


permission to connect to the computer remotely by changing the security
descriptors
on the default session configurations and by creating new session
configurations with
different security descriptors.
For more information about session configurations, see
about_Session_Configurations.

Windows network locations


Beginning in Windows PowerShell 3.0, the Enable-PSRemoting cmdlet can enable
remoting on client and server versions of Windows on private, domain, and
public
networks.

On server versions of Windows with private and domain networks, the


Enable-
PSRemoting cmdlet creates firewall rules that allow unrestricted remote
access. It also

creates a firewall rule for public networks that allows remote


access only from
computers in the same local subnet. This local subnet
firewall rule is enabled by default
on server versions of Windows on public
networks, but Enable-PSRemoting reapplies the
rule in case it was changed or
deleted.

On client versions of Windows with private and domain networks, by default,


the
Enable-PSRemoting cmdlet creates firewall rules that allow unrestricted
remote access.

To enable remoting on client versions of Windows with public networks, use the
SkipNetworkProfileCheck parameter of the Enable-PSRemoting cmdlet. It creates
a
firewall rule that allows remote access only from computers in the same
local subnet.

To remove the local subnet restriction on public networks and allow remote
access from
all locations on client and server versions of Windows, use the
Set-NetFirewallRule
cmdlet in the NetSecurity module. Run the following
command:

PowerShell

Set-NetFirewallRule -Name "WINRM-HTTP-In-TCP-PUBLIC" -RemoteAddress Any

7 Note

The name of the firewall rule can be different for different versions of
Windows. Use
Get-NetFirewallRule to see a list of rules. Before enabling the
firewall rule, view the

security settings in the rule to verify that the


configuration is appropriate for your
environment.

In Windows PowerShell 2.0, on server versions of Windows, Enable-PSRemoting


creates
firewall rules that permit remote access on all networks.
In Windows PowerShell 2.0, on client versions of Windows, Enable-PSRemoting
creates
firewall rules only on private and domain networks. If the network
location is public,
Enable-PSRemoting fails.

Run as administrator
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 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.

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


Computers running all supported versions of Windows can establish remote
connections to and run remote commands in PowerShell without any
configuration.
However, to receive connections, and allow users to create
local and remote user-
managed PowerShell sessions ("PSSessions") and
run commands on the local computer,
you must enable PowerShell
remoting on the computer.

Windows Server 2012 and newer releases of Windows Server are enabled for
PowerShell
remoting by default. If the settings are changed, you can
restore the default settings by
running the Enable-PSRemoting cmdlet.

On all other supported versions of Windows, you need to run the


Enable-PSRemoting
cmdlet to enable PowerShell remoting.

The remoting features of PowerShell are supported by the WinRM


service, which is the
Microsoft implementation of the Web Services for
Management (WS-Management)
protocol. When you enable PowerShell
remoting, you change the default configuration
of WS-Management and add system
configuration that allow users to connect to WS-
Management.

To configure PowerShell to receive remote commands:

1. Start PowerShell with the Run as administrator option.


2. At the command prompt, type: Enable-PSRemoting

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.

PowerShell

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:

Output

Id Name ComputerName State ConfigurationName

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

1 Session1 localhost Opened Microsoft.PowerShell

If the command fails, for assistance, see


about_Remote_Troubleshooting.

Understand policies
When you work remotely, you use two instances of 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 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_Remote_Variables
about_PSSessions
Invoke-Command
Enter-PSSession
New-PSSession
about_Remote_Troubleshooting
Article • 09/19/2022 • 20 minutes to read

Short description
Describes how to troubleshoot remote operations in PowerShell.

Long description
This section describes some of the problems that you might encounter when using
the
remoting features of PowerShell that are based on WS-Management technology
and it
suggests solutions to these problems.

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

7 Note

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

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, PowerShell remoting must be enabled on the
computer.
Enabling 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.

Windows PowerShell remoting is enabled on Windows Server 2012 and newer


releases
of Windows Server by default. On all other systems, run the
Enable-PSRemoting cmdlet
to enable remoting. You can also run the
Enable-PSRemoting cmdlet to re-enable
remoting on Windows Server 2012 and
newer releases of Windows Server if remoting is
disabled.
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 PowerShell commands and accept


connections, use the Enable-PSRemoting cmdlet.

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.

To set the startup type of the Windows Remote Management (WinRM) to


Automatic
on multiple computers, use the Set-Service cmdlet.

To enable a firewall exception, use the Windows Firewall: Allow Local Port
Exceptions group policy.

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 remoting on public networks

ERROR: Unable to check the status of the firewall

The Enable-PSRemoting cmdlet returns this error when the local network is
public and
the SkipNetworkProfileCheck parameter is not used in the command.

On server versions of Windows, Enable-PSRemoting succeeds on all network


location
types. It creates firewall rules that allow remote access to private
and domain ("Home"
and "Work") networks. For public networks, it creates
firewall rules that allows remote
access from the same local subnet.

On client versions of Windows, Enable-PSRemoting succeeds on private and


domain
networks. By default, it fails on public networks, but if you use the
SkipNetworkProfileCheck parameter, Enable-PSRemoting succeeds and creates
a firewall
rule that allows traffic from the same local subnet.

To remove the local subnet restriction on public networks and allow remote
access from
any location, run the following command:

PowerShell

Set-NetFirewallRule -Name "WINRM-HTTP-In-TCP-PUBLIC" -RemoteAddress Any

The Set-NetFirewallRule cmdlet is exported by the NetSecurity module.


7 Note

The name of the firewall rule can be different for different versions of
Windows. Use
Get-NetFirewallRule to see a list of rules. Before enabling
the firewall rule, view the

security settings in the rule to verify that the


configuration is appropriate for your
environment.

7 Note

In Windows PowerShell 2.0, on computers running server versions of Windows,


Enable-PSRemoting creates firewall rules that allow remote access on
private,

domain and public networks. On computers running client versions of


Windows,
Enable-PSRemoting creates firewall rules that allow remote access
only on private

and domain networks.

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.

If the policy configuration is incorrect you may receive the following 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.

A configuration error in the policy results in an empty value for the


ListeningOn
property. Use the following command to check the value.

PowerShell

PS> Get-WSManInstance winrm/config/listener -Enumerate

cfg :
http://schemas.microsoft.com/wbem/wsman/1/config/listener

xsi : http://www.w3.org/2001/XMLSchema-instance

Source : GPO

lang : en-US

Address : *

Transport : HTTP

Port : 5985

Hostname :

Enabled : true

URLPrefix : wsman

CertificateThumbprint :

ListeningOn : {}

How to set the startup type of the WinRM service

ERROR: ACCESS IS DENIED

PowerShell remoting depends upon the Windows Remote Management (WinRM)


service.
The service must be running to support remote commands.

On server versions of Windows, the startup type of the Windows Remote


Management
(WinRM) service is Automatic.

However, on client versions of Windows, 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.

PowerShell

$servers = Get-Content servers.txt

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.

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

PowerShell

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

PowerShell

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.

PowerShell

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.

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

PowerShell

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 parameter of the New-PSSession , Enter-PSSession and


Invoke-
Command cmdlets accepts 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.

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.

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:

PowerShell

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:

PowerShell
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

PowerShell

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.

PowerShell

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:

PowerShell

Set-Item wsman:\localhost\Client\TrustedHosts -Value <ComputerName>

where each value <ComputerName> must have the following format:

<Computer>.<Domain>.<Company>.<top-level-domain>

For example:

PowerShell

$server = 'Server01.Domain01.Fabrikam.com'

Set-Item wsman:\localhost\Client\TrustedHosts -Value $server

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

PowerShell

$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:

PowerShell

Set-Item wsman:\localhost\Client\TrustedHosts -Value <IP Address>

For example:

PowerShell

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.

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

PowerShell

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 PowerShell remoting uses the HTTP protocol, it is affected by HTTP


proxy
settings. In enterprises that have proxy servers, users cannot access a
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.
PowerShell

$SessionOption = New-PSSessionOption -ProxyAccessType IEConfig `

-ProxyAuthentication Negotiate -ProxyCredential Domain01\User01

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, see
about_Preference_Variables.

To set these options for all remote commands all PowerShell sessions on the
local
computer, add the $PSSessionOption preference variable to your PowerShell
profile. For
more information about 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
$env:Windir\System32 directory to the
$env: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.

PowerShell
$s = New-PSSession -ComputerName Server01 -ConfigurationName CustomShell

Invoke-Command -Session $s {$env:PROCESSOR_ARCHITECTURE}

Output

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 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 PowerShell ExecutionPolicy registry setting.

PowerShell

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

PowerShell.exe -ExecutionPolicy RemoteSigned

For more information about execution policies, see


about_Execution_Policies. For more
information,
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 WSMan 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


MaximumReceivedDataSizePerCommand and MaximumReceivedObjectSize
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, 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.

PowerShell

Set-PSSessionConfiguration -Name microsoft.PowerShell `

-MaximumReceivedObjectSizeMB 11 -Force

For more information about the New-PSSessionOption cmdlet, see


New-PSSessionOption .

For more information about the WS-Management quotas, see


about_WSMan_Provider.

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, PowerShell uses the shortest timeout
settings.

The following timeouts are available in the basic configuration.

The WSMan 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, 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 commands 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.

PowerShell

$pso = New-PSSessionoption -OperationTimeout 240000

New-PSSession -ComputerName Server01 -sessionOption $pso

For more information about the WS-Management timeouts, see the Help topic for
the
WSMan provider (type Get-Help WSMan ).

For more information about the New-PSSessionOption 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 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 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.

How to recover from an operation failure


ERROR: The I/O operation has been aborted because of either a thread exit

or an application request.

This error is returned when an operation is terminated before it completes.


Typically, it
occurs when the WinRM service stops or restarts while other WinRM
operations are in
progress.

To resolve this issue, verify that the WinRM service is running and try the
command
again.

1. Start PowerShell with the Run as administrator option.

2. Run the following command:

Start-Service WinRM

3. Re-run the command that generated the error.

Linux and macOS limitations

Authentication
Only basic authentication works on macOS and attempting to use other
authentication
schemes may result in the process crashing.

Please see the


OMI authentication
instructions.

See also
about_Remote
about_Remote_Requirements
about_Remote_Variables
Import-Module
Export-PSSession
Import-PSSession
about_Remote_Variables
Article • 09/19/2022 • 4 minutes to read

Short description
Explains how to use local and remote variables in remote commands.

Long description
You can use variables in commands that you run on remote computers. Assign a
value
to the variable and then use the variable in place of the value.

By default, the variables in remote commands are assumed to be defined in the


session
that runs the command. Variables that are defined in a local session,
must be identified
as local variables in the command.

Using remote variables


PowerShell assumes that the variables used in remote commands are defined in
the
session in which the command runs.

In this example, the $ps variable is defined in the temporary session in


which the Get-
WinEvent command runs.

PowerShell

Invoke-Command -ComputerName S1 -ScriptBlock {

$ps = "*PowerShell*"; Get-WinEvent -LogName $ps

When the command runs in a persistent session, PSSession, the remote


variable must
be defined in that session.

PowerShell

$s = New-PSSession -ComputerName S1

Invoke-Command -Session $s -ScriptBlock {$ps = "*PowerShell*"}

Invoke-Command -Session $s -ScriptBlock {Get-WinEvent -LogName $ps}

Using local variables


You can use local variables in remote commands, but the variable must be
defined in the
local session.

Beginning in PowerShell 3.0, you can use the Using scope modifier to identify
a local
variable in a remote command.

The syntax of Using is as follows:

$Using:<VariableName>

In the following example, the $ps variable is created in the local session,
but is used in
the session in which the command runs. The Using scope
modifier identifies $ps as a
local variable.

PowerShell

$ps = "*PowerShell*"

Invoke-Command -ComputerName S1 -ScriptBlock {

Get-WinEvent -LogName $Using:ps

The Using scope modifier can be used in a PSSession.

PowerShell

$s = New-PSSession -ComputerName S1

$ps = "*PowerShell*"

Invoke-Command -Session $s -ScriptBlock {Get-WinEvent -LogName $Using:ps}

A variable reference such as $using:var expands to the value of variable $var


from the
caller's context. You do not get access to the caller's variable object.
The Using scope
modifier cannot be used to modify a local variable within the
PSSession. For example,
the following code does not work:

PowerShell

$s = New-PSSession -ComputerName S1

$ps = "*PowerShell*"

Invoke-Command -Session $s -ScriptBlock {$Using:ps = 'Cannot assign new


value'}

For more information about Using , see about_Scopes

Using splatting
PowerShell splatting passes a collection of parameter names and values to a
command.
For more information, see about_Splatting.

In this example, the splatting variable, $Splat is a hash table that is set
up on the local
computer. The Invoke-Command connects to a remote computer
session. The ScriptBlock
uses the Using scope modifier with the At ( @ )
symbol to represent the splatted variable.

PowerShell

$Splat = @{ Name = "Win*"; Include = "WinRM" }

Invoke-Command -Session $s -ScriptBlock { Get-Service @Using:Splat }

Other situations where the 'Using' scope modifier is


needed
For any script or command that executes out of session, you need the Using
scope
modifier to embed variable values from the calling session scope, so that
out of session
code can access them. The Using scope modifier is supported in
the following contexts:

Remotely executed commands, started with Invoke-Command using the


ComputerName or Session parameter (remote session)
Background jobs, started with Start-Job (out-of-process session)
Thread jobs started via Start-ThreadJob (separate thread session)

Depending on the context, embedded variable values are either independent


copies of
the data in the caller's scope or references to it. In remote and
out-of-process sessions,
they are always independent copies. In thread
sessions, they are passed by reference.

Serialization of variable values


Remotely executed commands and background jobs run out-of-process.
Out-of-process
sessions use XML-based serialization and deserialization to make
the values of variables
available across the process boundaries. The
serialization process converts objects to a
PSObject that contains the
original objects properties but not its methods.

For a limited set of types, deserialization rehydrates objects back to the


original type.
The rehydrated object is a copy of the original object instance.
It has the type properties
and methods. For simple types, such as
System.Version, the copy is exact. For complex
types, the copy is
imperfect. For example, rehydrated certificate objects do not include
the
private key.

Instances of all other types are PSObject instances. The PSTypeNames


property contains
the original type name prefixed with Deserialized, for
example,
Deserialized.System.Data.DataTable

Using local variables with ArgumentList


parameter
You can use local variables in a remote command by defining parameters for the
remote
command and using the ArgumentList parameter of the Invoke-Command
cmdlet to
specify the local variable as the parameter value.

Use the param keyword to define parameters for the remote command. The
parameter names are placeholders that don't need to match the local
variable's
name.

Use the parameters defined by the param keyword in the command.

Use the ArgumentList parameter of the Invoke-Command cmdlet to specify


the local
variable as the parameter value.

For example, the following commands define the $ps variable in the local
session and
then use it in a remote command. The command uses $log as the
parameter name and
the local variable, $ps , as its value.

PowerShell

$ps = "*PowerShell*"

Invoke-Command -ComputerName S1 -ScriptBlock {

param($log)

Get-WinEvent -LogName $log

} -ArgumentList $ps

See also
about_PSSessions
about_Remote
about_Scopes
about_Splatting
about_Variables
Invoke-Command
Enter-PSSession
New-PSSession
Start-ThreadJob
about_Requires
Article • 09/19/2022 • 4 minutes to read

Short description
Prevents a script from running without the required elements.

Long description
The #Requires statement prevents a script from running unless the PowerShell
version,
modules (and version), or snap-ins (and version), and edition
prerequisites are met. If
the prerequisites aren't met, PowerShell doesn't run
the script or provide other runtime
features, such as tab completion.

Syntax

#Requires -Version <N>[.<n>]

#Requires -PSSnapin <PSSnapin-Name> [-Version <N>[.<n>]]

#Requires -Modules { <Module-Name> | <Hashtable> }

#Requires -PSEdition <PSEdition-Name>

#Requires -ShellId <ShellId> -PSSnapin <PSSnapin-Name> [-Version <N>[.<n>]]

#Requires -RunAsAdministrator

For more information about the syntax, see


ScriptRequirements.

Rules for use


A script can include more than one #Requires statement. The #Requires
statements can
appear on any line in a script.

Placing a #Requires statement inside a function does NOT limit its scope. All
#Requires
statements are always applied globally, and must be met, before the
script can execute.

2 Warning

Even though a #Requires statement can appear on any line in a script, its
position
in a script does not affect the sequence of its application. The
global state the
#Requires statement presents must be met before script
execution.
Example:

PowerShell

Get-Module AzureRM.Netcore | Remove-Module

#Requires -Modules AzureRM.Netcore

You might think that the above code shouldn't run because the required module
was
removed before the #Requires statement. However, the #Requires state
had to be met
before the script could even execute. Then the first line of the
script invalidated the
required state.

Parameters

-Assembly <Assembly path> | <.NET assembly specification>

) Important

The -Assembly syntax is deprecated. It serves no function. The syntax was


added in
PowerShell 5.1 but the supporting code was never implemented. The
syntax is still
accepted for backward compatibility.

Specifies the path to the assembly DLL file or a .NET assembly name. The
Assembly
parameter was introduced in PowerShell 5.0. For more information
about .NET
assemblies, see Assembly names.

For example:

#Requires -Assembly path\to\foo.dll

#Requires -Assembly "System.Management.Automation, Version=3.0.0.0,

Culture=neutral, PublicKeyToken=31bf3856ad364e35"

-Version <N>[.<n>]
Specifies the minimum version of PowerShell that the script requires. Enter a
major
version number and optional minor version number.

For example:

PowerShell

#Requires -Version 5.1

-PSSnapin <PSSnapin-Name> [-Version <N>[.<n>]]


Specifies a PowerShell snap-in that the script requires. Enter the snap-in name
and an
optional version number.

For example:

PowerShell

#Requires -PSSnapin DiskSnapin -Version 1.2

-Modules <Module-Name> | <Hashtable>


Specifies PowerShell modules that the script requires. Enter the module name
and an
optional version number.

If the required modules aren't in the current session, PowerShell imports them.
If the
modules can't be imported, PowerShell throws a terminating error.

For each module, type the module name (<String>) or a hashtable. The value
can be a
combination of strings and hashtables. The hashtable has the
following keys.

ModuleName - Required Specifies the module name.

GUID - Optional Specifies the GUID of the module.


It's also Required to specify at least one of the three below keys.
ModuleVersion - Specifies a minimum acceptable version of the module.
MaximumVersion - Specifies the maximum acceptable version of the module.

RequiredVersion - Specifies an exact, required version of the module.


This can't

be used with the other Version keys.

7 Note
RequiredVersion was added in Windows PowerShell 5.0.
MaximumVersion was added

in Windows PowerShell 5.1.

For example:

Require that Hyper-V (version 1.1 or greater) is installed.

PowerShell

#Requires -Modules @{ ModuleName="Hyper-V"; ModuleVersion="1.1" }

Requires that Hyper-V (only version 1.1 ) is installed.

PowerShell

#Requires -Modules @{ ModuleName="Hyper-V"; RequiredVersion="1.1" }

Requires that Hyper-V (version 1.1 or lesser) is installed.

PowerShell

#Requires -Modules @{ ModuleName="Hyper-V"; MaximumVersion="1.1" }

Requires that any version of PSScheduledJob and PSWorkflow , is installed.

PowerShell

#Requires -Modules PSWorkflow, PSScheduledJob

When using the RequiredVersion key, ensure your version string exactly matches
the
version string you wish to require.

PowerShell

Get-Module Hyper-V

Output

ModuleType Version Name ExportedCommands

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

Binary 2.0.0.0 hyper-v {Add-VMAssignableDevice, ...}

The following example fails because 2.0.0 doesn't exactly match


2.0.0.0.
PowerShell

#Requires -Modules @{ ModuleName="Hyper-V"; RequiredVersion="2.0.0" }

-PSEdition <PSEdition-Name>
Specifies a PowerShell edition that the script requires. Valid values are
Core for
PowerShell and Desktop for Windows PowerShell.

For example:

PowerShell

#Requires -PSEdition Core

-ShellId

Specifies the shell that the script requires. Enter the shell ID. If you use
the ShellId
parameter, you must also include the PSSnapin parameter.
You can find the current
ShellId by querying the $ShellId automatic
variable.

For example:

PowerShell

#Requires -ShellId MyLocalShell -PSSnapin Microsoft.PowerShell.Core

7 Note

This parameter is intended for use in mini-shells, which have been deprecated.

-RunAsAdministrator

When this switch parameter is added to your #Requires statement, it specifies


that the
PowerShell session in which you're running the script must be started
with elevated user
rights. The RunAsAdministrator parameter is ignored on a
non-Windows operating
system. The RunAsAdministrator parameter was
introduced in PowerShell 4.0.

For example:

PowerShell
#Requires -RunAsAdministrator

Examples
The following script has two #Requires statements. If the requirements
specified in both
statements aren't met, the script doesn't run. Each
#Requires statement must be the
first item on a line:

PowerShell

#Requires -Modules PSWorkflow

#Requires -Version 3

Param

[parameter(Mandatory=$true)]

[String[]]

$Path

...

See also
about_Automatic_Variables
about_Language_Keywords
about_PSSnapins
Get-PSSnapin
about_Reserved_Words
Article • 09/19/2022 • 2 minutes to read

Short description
Lists the reserved words that cannot be used as identifiers because they
have a special
meaning in PowerShell.

Long description
There are certain words that have special meaning in PowerShell. When these
words
appear without quotation marks, 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 PowerShell:

assembly exit process

base filter public

begin finally return

break for sequence

catch foreach static

class from (*) switch

command function throw

configuration hidden trap

continue if try

data in type

define (*) inlinescript until

do interface using

dynamicparam module var (*)

else namespace while

elseif parallel workflow

end param

enum private

(*) These keywords are reserved for future use.

Several language keywords, including Foreach , If , For , and While , have


their own help
articles. To view them, type Get-Help about_ and add the
keyword. For example, to get
information about the Foreach statement, type:
PowerShell

Get-Help about_ForEach

For information about the Filter statement or the Return statement syntax,
type:

PowerShell

Get-Help about_Functions

For information about other reserved words, type:

PowerShell

Get-Help <Reserved_Word>

7 Note

Not every reserved word has its own help article. If Get-Help does not
return an
article, you can search for articles that talk about the reserved
word using the
following command:

PowerShell

Get-Help <Reserved_Word> -Category:HelpFile

See also
about_Command_Syntax
about_Language_Keywords
about_Parsing
about_Quoting_Rules
about_Script_Blocks
about_Special_Characters
about_Return
Article • 09/19/2022 • 3 minutes to read

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

7 Note

Beginning in PowerShell 5.0, PowerShell added language for defining


classes, by
using formal syntax. In the context of a PowerShell class,
nothing is output from a
method except what you specify using a
return statement. You can read more
about PowerShell classes in
about_Classes.

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:

PowerShell
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. Odd numbers are not multiplied
because the return statement exits
before that statement can execute.

PowerShell

function MultiplyEven

param($number)

if ($number % 2) { return "$number is not even" }

$number * 2

1..10 | ForEach-Object {MultiplyEven -Number $_}

Output

1 is not even

3 is not even

5 is not even

12

7 is not even

16

9 is not even

20

In 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:

PowerShell

$a

return

The following statement also returns the value of $a :


PowerShell

return $a

The following example includes a statement intended to let the user know that
the
function is performing a calculation:

PowerShell

function calculation {

param ($value)

"Please wait. Working on calculation..."

$value += 73

return $value

$a = calculation 14

The "Please wait. Working on calculation..." string is not displayed. Instead,


it is assigned
to the $a variable, as in the following example:

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.

If you would like to display a message within your function, beginning in


PowerShell 5.0,
you can use the Information stream. The code below corrects
the above example using
the Write-Information cmdlet with a
InformationAction of Continue.

PowerShell

function calculation {

param ($value)

Write-Information "Please wait. Working on calculation..." -


InformationAction Continue

$value += 73

return $value

$a = calculation 14

Output

Please wait. Working on calculation...

C:\PS> $a

87

Return values and the Pipeline


When you return a collection from your script block or function, PowerShell
automatically unrolls the members and passes them one at a time through the
pipeline.
This is due to PowerShell's one-at-a-time processing. For more
information, see
about_pipelines.

This concept is illustrated by the following sample function that returns an


array of
numbers. The output from the function is piped to the Measure-Object
cmdlet which
counts the number of objects in the pipeline.

PowerShell

function Test-Return

$array = 1,2,3

return $array

Test-Return | Measure-Object

Output

Count : 3

Average :

Sum :

Maximum :

Minimum :

Property :

To force a script block or function to return collection as a single


object to the pipeline,
use one of the following two methods:

Unary array expression

Utilizing a unary expression you can send your return value down the pipeline
as a
single object as illustrated by the following example.

PowerShell
function Test-Return

$array = 1,2,3

return (, $array)

Test-Return | Measure-Object

Output

Count : 1

Average :

Sum :

Maximum :

Minimum :

Property :

Write-Output with NoEnumerate parameter.

You can also use the Write-Output cmdlet with the NoEnumerate
parameter. The
example below uses the Measure-Object cmdlet to count the
objects sent to the
pipeline from the sample function by the return
keyword.

PowerShell

function Test-Return

$array = 1, 2, 3

return Write-Output -NoEnumerate $array

Test-Return | Measure-Object

Output

Count : 1

Average :

Sum :

Maximum :

Minimum :

Property :

See also
about_Classes
about_Functions
about_Language_Keywords
about_Scopes
about_Script_Blocks
Write-Information
about_Run_With_PowerShell
Article • 09/19/2022 • 2 minutes to read

Short description
Explains how to use the "Run with PowerShell" feature to run a script from a
file system
drive.

Long description
Beginning in Windows PowerShell 3.0, you can use the "Run with PowerShell"
feature to
run scripts from File Explorer in Windows 8 and Windows Server 2012
and from
Windows Explorer in earlier versions of Windows.

The "Run with PowerShell" feature is designed to run scripts that do not have
required
parameters and do not return output to the command prompt.

When you use the "Run with PowerShell" feature, the Windows PowerShell console
window appears only briefly, if at all. You cannot interact with it.

To use the "Run with PowerShell" feature:

In File Explorer (or Windows Explorer), right-click the script file name and
then select
"Run with PowerShell".

The "Run with PowerShell" feature starts a Windows PowerShell session that has
an
execution policy of Bypass, runs the script, and closes the session.

It runs a command that has the following format:

PowerShell.exe -File <FileName> -ExecutionPolicy Bypass

"Run with PowerShell" sets the Bypass execution policy only for the session
(the current
instance of the PowerShell process) in which the script runs.
This feature does not
change the execution policy for the computer or the
user.

The "Run with PowerShell" feature is affected only by the AllSigned execution
policy. If
the AllSigned execution policy is effective for the computer or the
user, "Run with
PowerShell" runs only signed scripts. "Run with PowerShell" is
not affected by any other
execution policy. For more information, see
about_Execution_Policies.

Troubleshooting Note: Run with PowerShell command might prompt you to confirm
the
execution policy change.

See also
about_Execution_Policies
about_Group_Policy_Settings
about_Scripts
about_Scopes
Article • 03/30/2023 • 16 minutes to read

Short description
Explains the concept of scope in PowerShell and shows how to set and change
the
scope of elements.

Long description
PowerShell protects access to variables, aliases, functions, and PowerShell
drives
(PSDrives) by limiting where they can be read and changed. PowerShell
uses scope rules
to ensure that you don't inadvertently change an item that
shouldn't be changed.

The following are the basic rules of scope:

Scopes may nest. An outer scope is referred to as a parent scope. Any nested
scopes are child scopes of that parent.

An item is visible in the scope that it was created in and in any child
scopes, unless
you explicitly make it private.

You can declare variables, aliases, functions, and PowerShell drives for a
scope
outside of the current scope.

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 by the new item, but it
isn't overridden or
changed.

PowerShell scopes
PowerShell supports the following scopes:

Global: The scope that's in effect when PowerShell starts or when you
create a new
session or runspace. Variables and functions that are present
when PowerShell
starts have been created in the global scope, such as
automatic variables and
preference variables. The variables, aliases, and
functions in your PowerShell
profiles are also created in the global scope.
The global scope is the root parent
scope in a session.
Local: The current scope. The local scope can be the global scope or any
other
scope.
Script: The scope that's 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.

Parent and child scopes


You can create a new child scope by calling a script or function. The calling
scope is the
parent scope. The called script or function is the child scope.
The functions or scripts
you call may call other functions, creating a
hierarchy of child scopes whose root scope
is the global scope.

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 don't
affect the parent scope, unless you explicitly specify
the scope when you create the
items.

7 Note

Functions from a module don't run in a child scope of the calling scope.
Modules
have their own session state that's linked to the global scope.
All module code runs
in a module-specific hierarchy of scopes that has its
own root scope.

Inheritance
A child scope doesn't 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 aren't 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 article. It includes all
the variables that have the AllScope
option, plus some automatic variables.

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:
PowerShell

Get-Variable -Scope local

To get all the variables in the global scope, type:

PowerShell

Get-Variable -Scope global

Scope modifiers
A variable, alias, or function name can include any one of the following
optional scope
modifiers:

global: - Specifies that the name exists in the Global scope.

local: - Specifies that the name exists in the Local scope. The current
scope is
always the Local scope.

private: - Specifies that the name is Private and only visible to the
current scope.

7 Note

private isn't a scope. It's an option that changes the visibility


of an item

outside of the scope where the item is defined.

script: - Specifies that the name exists in the Script scope.


Script scope is the

nearest ancestor script file's scope or Global if


there is no nearest ancestor script
file.

using: - Used to access variables defined in another scope while running


scripts

via cmdlets like Start-Job and Invoke-Command .

workflow: - Specifies that the name exists within a workflow. Note:


Workflows

aren't supported in PowerShell v6 and higher.

<variable-namespace> - A modifier created by a PowerShell PSDrive


provider. For
example:

Namespace Description
Namespace Description

Alias: Aliases defined in the current scope

Env: Environment variables defined in the current scope

Function: Functions defined in the current scope

Variable: Variables defined in the current scope

The default scope for scripts is the script scope. The default scope for
functions and
aliases is the local scope, even if they're defined in a
script.

Using scope modifiers


To specify the scope of a new variable, alias, or function, use a scope
modifier.

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 following command, which doesn't use a scope modifier, creates a variable
in the
current or local scope:

PowerShell

$a = "one"

To create the same variable in the global scope, use the scope global:
modifier:

PowerShell

$global:a = "one"

Get-Variable a | Format-List *

Notice the Visibility and Options property values.


Output

Name : a

Description :

Value : one

Visibility : Public

Module :

ModuleName :

Options : None

Attributes : {}

Compare that to a private variable:

PowerShell

$private:pVar = 'Private variable'

Get-Variable pVar | Format-List *

Using the private scope modifier sets the Options property to Private .

Output

Name : pVar

Description :

Value : Private variable

Visibility : Public

Module :

ModuleName :

Options : Private

Attributes : {}

To create the same variable in the script scope, use the script: scope
modifier:

PowerShell

$script:a = "one"

You can also use a scope modifier with functions. The following function
definition
creates a function in the global scope:

PowerShell

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:

PowerShell

$test

$global:test

The using: scope modifier


Using is a special scope modifier that identifies a local variable in a remote
command.
Without a modifier, PowerShell expects variables in remote commands to
be defined in
the remote session.

The using scope modifier is introduced in PowerShell 3.0.

For any script or command that executes out of session, you need the using
scope
modifier to embed variable values from the calling session scope, so that
out of session
code can access them. The using scope modifier is supported in
the following contexts:

Remotely executed commands, started with Invoke-Command using the


ComputerName, HostName, SSHConnection or Session parameters
(remote
session)
Background jobs, started with Start-Job (out-of-process session)
Thread jobs, started via Start-ThreadJob or ForEach-Object -Parallel
(separate
thread session)

Depending on the context, embedded variable values are either independent


copies of
the data in the caller's scope or references to it. In remote and
out-of-process sessions,
they're always independent copies.

For more information, see about_Remote_Variables.

In thread sessions, they're passed by reference. This means it's possible to


modify child
scope variables in a different thread. To safely modify variables
requires thread
synchronization.

For more information see:

Start-ThreadJob
ForEach-Object
Serialization of variable values
Remotely executed commands and background jobs run out-of-process.
Out-of-process
sessions use XML-based serialization and deserialization to make
the values of variables
available across the process boundaries. The
serialization process converts objects to a
PSObject that contains the
original objects properties but not its methods.

For a limited set of types, deserialization rehydrates objects back to the


original type.
The rehydrated object is a copy of the original object instance.
It has the type properties
and methods. For simple types, such as
System.Version, the copy is exact. For complex
types, the copy is
imperfect. For example, rehydrated certificate objects don't include
the
private key.

Instances of all other types are PSObject instances. The PSTypeNames


property contains
the original type name prefixed with Deserialized, for
example,
Deserialized.System.Data.DataTable

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 aren't retroactively inherited by parent
scopes.

An item that has the AllScope property is visible in the child scope, and
it's 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:

PowerShell

Get-Help * -Parameter scope

To find the variables that are visible in a particular scope, use the Scope
parameter of
Get-Variable . The visible variables include global variables,
variables in the parent
scope, and variables in the current scope.
For example, the following command gets the variables that are visible in the
local
scope:

PowerShell

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:

PowerShell

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:

PowerShell

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 doesn't have a Scope parameter.

7 Note

For the cmdlets that use the Scope parameter, you can also refer to
scopes by
number. The number 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.

Using dot-source notation with scope


Scripts and functions follow 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 the contents of a script or function to the current scope
using dot-
source notation. When you run a script or function using dot-source
notation, it runs in
the current scope. Any functions, aliases, and variables
in the script or function are
added to the current scope.

For example, to run the Sample.ps1 script from the C:\Scripts directory in
the script
scope (the default for scripts), just enter the full path to the
script file on the command
line.

PowerShell

c:\scripts\sample.ps1

Also, using the call operator ( & ) to run a function or script runs it in
script scope. Using
the call operator is no different than running the script by name.

PowerShell

& c:\scripts\sample.ps1

You can read more about the call operator in about_operators.

To run the Sample.ps1 script in the local scope type a dot and a space ( . )
before the
path to the script:

PowerShell

. c:\scripts\sample.ps1

Now, any functions, aliases, or variables defined in the script are added to
the current
scope.

Restricting without scope


PowerShell has some options and features that are similar to scope and may
interact
with scopes. These feature may be confused with scope or the behavior
of scope.

Sessions, modules, and nested prompts are self-contained environments, not


child
scopes of the global scope in the session.

Sessions
A session is an environment in which PowerShell runs. When you create a session
on a
remote computer, 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 isn't a
child scope of the session in which it 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 PowerShell module to share and deliver 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 aren't
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.

By default, modules are loaded into the top-level of the current session
state not the
current scope. The current session state could be a module
session state or the global
session state. Adding a module to a session does
not change the scope. If you are in the
global scope, then modules are loaded
into the global session state. Any exports are
placed into the global tables.
If you load module2 from within module1, module2 is
loaded into the session
state of module1 not the global session state. Any exports from
module2 are
placed at the top of the module1 session state. If you use
Import-Module -
Scope local , then the exports are placed into the current
scope object rather than at the
top level. If you are in a module and use
Import-Module -Scope global (or Import-Module
-Global ) to load another
module, that module and its exports are loaded into the global

session state
instead of the module's local session state. This feature was designed for
writing module that manipulate modules. The WindowsCompatibility module
does this
to import proxy modules into the global session state.

Within the session state, modules have their own scope. Consider the following
module
C:\temp\mod1.psm1 :

PowerShell

$a = "Hello"

function foo {

"`$a = $a"

"`$global:a = $global:a"

Now we create a global variable $a , give it a value and call the function
foo.

PowerShell

$a = "Goodbye"

foo

The module declares the variable $a in the module scope then the function
foo outputs
the value of the variable in both scopes.

Output

$a = Hello

$global:a = Goodbye

Nested prompts
Nested prompts don't 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're
created, but they can't 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 don't
display the private
variable. Using the global scope modifier in this instance
doesn't display the private
variable.

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, in which it was created. A container could
be a module, script, or
snap-in. 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 can't 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
can't view or
change the item in any scope.
If you try to view or change the value of a variable that has private
visibility,
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 doesn't affect the global scope.

First, to display the value of the $ConfirmPreference variable in the local


scope, use the
following command:

PS> $ConfirmPreference

High

Create a Scope.ps1 script that contains the following commands:

PowerShell

$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:
Output

The value of $ConfirmPreference is Low.

Next, test the current value of the $ConfirmPreference variable in the current
scope.

PS> $ConfirmPreference

High

This example shows that changes to the value of a variable in the script scope
doesn't
affect the variable`s value 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.

PowerShell

$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 :

PowerShell

$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:

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.

PS> $test

Global

Example 3: Change the value of a variable in a parent


scope
Unless you protect an item 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.

PowerShell

$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:

PowerShell

$global:test = "Local"

"The global value of `$test is $global:test."

When the script is complete, the global value of $test is changed.

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 only be viewed or
changed in the scope in which they were created.
The following command creates a private variable called $ptest in the local
scope.

PowerShell

New-Variable -Name ptest -Value 1 -Option Private

You can display and change the value of $ptest in the local scope.

PS> $ptest

PS> $ptest = 2

PS> $ptest

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:

PowerShell

"The value of `$Ptest is $Ptest."

"The value of `$Ptest is $global:Ptest."

The $ptest variable isn't visible in the script scope, the output is empty.

PowerShell

"The value of $Ptest is ."

"The value of $Ptest is ."

Example 5: Using a local variable in a remote command


For variables in a remote command created in the local session, use the using
scope
modifier. PowerShell assumes that the variables in remote commands were
created in
the remote session.

The syntax is:


$using:<VariableName>

For example, the following commands create a $Cred variable in the local
session and
then use the $Cred variable in a remote command:

PowerShell

$Cred = Get-Credential

Invoke-Command $s {Remove-Item .\Test*.ps1 -Credential $using:Cred}

The using scope modifier was introduced in PowerShell 3.0.

See also
about_Variables
about_Environment_Variables
about_Functions
about_Script_Blocks
Start-ThreadJob
about_Scripts
Article • 09/19/2022 • 10 minutes to read

Short description
Describes how to run and write scripts in PowerShell.

Long description
A script is a plain text file that contains one or more PowerShell commands.
PowerShell
scripts have a .ps1 file extension.

Running a script is a lot like running a cmdlet. You type the path and file
name of the
script and use parameters to submit data and set options. You can
run scripts on your
computer or in a remote session on a different computer.

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
filename. 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 run a script


Before you can run a script on Windows, you need to change the default
PowerShell
execution policy. Execution policy does not apply to PowerShell
running on non-
Windows platforms.

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.

The execution policy is saved in the registry, so you need to change it only
once on each
computer.

To change the execution policy, use the following procedure.

At the command prompt, type:


PowerShell

Set-ExecutionPolicy AllSigned

or

PowerShell

Set-ExecutionPolicy RemoteSigned

The change is effective immediately.

To run a script, type the full name and the full path to the script file.

For example, to run the Get-ServiceLog.ps1 script in the C:\Scripts directory,


type:

PowerShell

C:\Scripts\Get-ServiceLog.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:

PowerShell

.\Get-ServiceLog.ps1

If the script has parameters, type the parameters and parameter values after
the script
file name.

For example, the following command uses the ServiceName parameter of the
Get-
ServiceLog script to request a log of WinRM service activity.

PowerShell

.\Get-ServiceLog.ps1 -ServiceName WinRM

As a security feature, PowerShell does not run scripts when you double-click
the script
icon in File 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 PowerShell, see
about_Command_Precedence.
Run with PowerShell
Beginning in PowerShell 3.0, you can run scripts from File Explorer.

To use the "Run with PowerShell" feature:

Run File Explorer, right-click the script filename and then select "Run with
PowerShell".

The "Run with PowerShell" feature is designed to run scripts that do not have
required
parameters and do not return output to the command prompt.

For more information, see about_Run_With_PowerShell.

Running scripts on other computers


To run a script on one or more remote computers, use the FilePath parameter of
the
Invoke-Command cmdlet.

Enter the path and filename 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 Get-ServiceLog.ps1 script on the remote


computers
named Server01 and Server02.

PowerShell

Invoke-Command -ComputerName Server01,Server02 -FilePath `

C:\Scripts\Get-ServiceLog.ps1

Get help for scripts


The Get-Help cmdlet gets the help topics for scripts as well as for cmdlets
and other
types of commands. To get the help topic for a script, type
Get-Help followed by the
path and filename 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:

PowerShell

get-help C:\admin\scripts\ServicesLog.ps1

How to write a script


A script can contain any valid 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, open a new file in a text editor, type the commands, and
save them in a
file with a valid filename with the .ps1 file 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 filename is
created from the current
date.

PowerShell

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

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

PowerShell

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:

PowerShell

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.

Writing help for scripts


You can write a help topic 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.

Returning an exit value


By default, scripts do not return an exit status when the script ends. You must
use the
exit statement to return an exit code from a script. By default, the
exit statement
returns 0 . You can provide a numeric value to return a
different exit status. A nonzero
exit code typically signals a failure.

On Windows, any number between [int]::MinValue and [int]::MaxValue is


allowed.

In PowerShell, the exit statement sets the value of the $LASTEXITCODE


variable. In the
Windows Command Shell (cmd.exe), the exit statement sets the
value of the
%ERRORLEVEL% environment variable.

Any argument that is non-numeric or outside the platform-specific range is


translated to
the value of 0 .

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:

PowerShell

. C:\scripts\UtilityFunctions.ps1
or

PowerShell

. .\UtilityFunctions.ps1

After the UtilityFunctions.ps1 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.

PowerShell

#In UtilityFunctions.ps1

function New-Profile

Write-Host "Running New-Profile function"

$profileName = split-path $profile -leaf

if (test-path $profile)

{write-error "Profile $profileName already exists 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.

PowerShell

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.

PowerShell

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

For more information about modules, see about_Modules.

Other script features


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


PowerShell. For
more information, see about_Requires.

$PSCommandPath - Contains the full path and name of the script that is
being run.
This parameter is valid in all scripts. This automatic variable is
introduced in
PowerShell 3.0.
$PSScriptRoot - Contains the directory from which a script is being run. In

PowerShell 2.0, this variable is valid only in script modules ( .psm1 ).


Beginning in
PowerShell 3.0, it is valid in all scripts.

$MyInvocation - The $MyInvocation automatic variable contains information


about
the current script, including information about how it was started or
"invoked." 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 filename of the
script. $MyInvocation .Line contains the command that
started the script,
including all parameters and values.

Beginning in PowerShell 3.0, $MyInvocation has two new properties that


provide
information about the script that called or invoked the current
script. The values of
these properties are populated only when the invoker or
caller is a script.

PSCommandPath contains the full path and name of the script that called or
invoked the current script.

PSScriptRoot contains the directory of the script that called or invoked


the
current script.

Unlike the $PSCommandPath and $PSScriptRoot automatic variables, which


contain
information about the current script, the PSCommandPath and
PSScriptRoot
properties of the $MyInvocation variable contain
information about the script that
called the current 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_Internationalization.

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_Run_With_PowerShell
about_Scopes
about_Script_Blocks
about_Signing
Invoke-Command
about_Script_Blocks
Article • 11/29/2022 • 3 minutes to read

Short description
Defines what a script block is and explains how to use script blocks in
the PowerShell
programming language.

Long description
In the 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.

You can also specify a return value using the return keyword. The return
keyword does
not affect or suppress other output returned from your script
block. However, the
return keyword exits the script block at that line. For
more information, see
about_Return.

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>

7 Note
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:

PowerShell

Invoke-Command -ScriptBlock { Get-Process }

Output

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

...

Invoke-Command can also execute script blocks that have parameter blocks.
Parameters

are assigned by position using the ArgumentList parameter.

PowerShell

Invoke-Command -ScriptBlock { param($p1, $p2)

"p1: $p1"

"p2: $p2"

} -ArgumentList "First", "Second"

Output

p1: First

p2: Second

The script block in the preceding example uses the param keyword to
create a
parameters $p1 and $p2 . The string "First" is bound to the
first parameter ( $p1 ) and
"Second" is bound to ( $p2 ).

For more information about the behavior of ArgumentList, see


about_Splatting.

You can use variables to store and execute script blocks. The example below
stores a
script block in a variable and passes it to Invoke-Command .

PowerShell

$a = { Get-Service BITS }

Invoke-Command -ScriptBlock $a

Output

Status Name DisplayName

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

Running BITS Background Intelligent Transfer Ser...

The call operator is another way to execute script blocks stored in a variable.
Like
Invoke-Command , the call operator executes the script block in a child
scope. The call
operator can make it easier for you to use parameters with your
script blocks.

PowerShell

$a ={ param($p1, $p2)

"p1: $p1"

"p2: $p2"

&$a -p2 "First" -p1 "Second"

Output

p1: Second

p2: First

You can store the output from your script blocks in a variable using
assignment.

PS> $a = { 1 + 1}

PS> $b = &$a

PS> $b

PS> $a = { 1 + 1}

PS> $b = Invoke-Command $a

PS> $b

For more information about the call operator, see about_Operators.

Using delay-bind script blocks with parameters


A typed parameter that accepts pipeline input enables use of delay-bind
script blocks on
the parameter. You can use delay-bind script blocks as a
shorthand to define parameters
for a pipelined cmdlet before executing it.

Within the delay-bind script block, you can reference the piped in object
using the
pipeline variable $_ .

PowerShell

# Both examples rename config.log to old_config.log

# Without delay-binding

dir config.log | ForEach-Object -Process {

Rename-Item -Path $_ -NewName "old_$($_.Name)"

# With delay-binding

dir config.log | Rename-Item -NewName { "old_$($_.Name)" }

In more complex cmdlets, delay-bind script blocks allow the reuse of one piped
in
object to populate other parameters.

Notes on delay-bind script blocks as parameters:

You must explicitly specify any parameter names you use with delay-bind
script
blocks.

The parameter must not be untyped, and the parameter's type cannot be
[scriptblock] or [object] .

You receive an error if you use a delay-bind script block without providing
pipeline
input.

PowerShell

Rename-Item -NewName {$_.Name + ".old"}

Output

Rename-Item : Cannot evaluate parameter 'NewName' because its argument


is

specified as a script block and there is no input. A script block


cannot

be evaluated without input.

At line:1 char:23

+ Rename-Item -NewName {$_.Name + ".old"}

+ ~~~~~~~~~~~~~~~~~~

+ CategoryInfo : MetadataError: (:) [Rename-Item],

ParameterBindingException

+ FullyQualifiedErrorId : ScriptBlockArgumentNoInput,

Microsoft.PowerShell.Commands.RenameItemCommand

See also
about_Functions
about_Functions_Advanced
about_Operators
about_Script_Internationalization
Article • 09/19/2022 • 5 minutes to read

Short description
Describes the script internationalization features that make it easy for
scripts to display
messages and instructions to users in their user interface
(UI) language.

Long description
The PowerShell script internationalization features allow you to better serve
users
throughout the world by displaying help and user messages in the user's
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.

To support international Help text, PowerShell 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.

PowerShell

$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:

PowerShell

ConvertFrom-StringData -StringData @'

helloWorld = Hallo, Welt.

errorMsg1 = Das Feld Benutzername darf nicht leer sein.

promptMsg = Geben Sie Ihren Benutzernamen ein.

'@

Similarly, the World.psd1 file in the ar-SA subdirectory of the script


directory might
includes the following statement:

PowerShell

ConvertFrom-StringData -StringData @'

helloWorld = ‫
مرحًبا أيها العاَل م‬
errorMsg1 = ‫
ال يمكنك ترك حقل اسم المستخدم فارًغا‬
promptMsg = ‫
يرجى إدخال اسم المستخدم الخاص بك‬
'@

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.

PowerShell

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:

PowerShell

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.

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

PowerShell

$Day = Data {

#culture="en-US"

ConvertFrom-StringData -StringData @'

messageDate = Today is

d0 = Sunday

d1 = Monday

d2 = Tuesday

d3 = Wednesday

d4 = Thursday

d5 = Friday

d6 = Saturday

'@

Import-LocalizedData -BindingVariable Day

#Build an array of weekdays.

$a = $Day.d0, $Day.d1, $Day.d2, $Day.d3, $Day.d4, $Day.d5, $Day.d6

# 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 :

PowerShell

# culture="de-DE"

ConvertFrom-StringData @'

messageDate = Heute ist

    d0 = Sonntag

    d1 = Montag

    d2 = Dienstag

    d3 = Mittwoch

    d4 = Donnerstag

    d5 = Freitag

    d6 = Samstag

'@

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:

Output

Heute ist Freitag

See also
about_Data_Sections
about_Automatic_Variables
about_Hash_Tables
about_Quoting_Rules
Import-LocalizedData
ConvertFrom-StringData
about_Session_Configurations
Article • 09/19/2022 • 7 minutes to read

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, also known as an "endpoint" is a group of settings on
the local
computer that define the environment for the PowerShell sessions that
are created when
remote or local users connect to PowerShell on 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.

Beginning in PowerShell 3.0, you can use a session configuration file to


define the
elements of a session configuration. This feature makes it easy to
customize sessions
without writing code and to discover the properties of a
session configuration. To create
a session configuration file, use the
New-PSSessionConfiguration cmdlet. For more
information about session
configuration files, see
about_Session_Configuration_Files.

Session configurations are a feature of Web Services for Management


(WS-
Management) based 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, start PowerShell with the


"Run as
administrator" option.

About Session Configurations

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

Built-in Session Configurations

PowerShell 3.0 includes built-in session configurations named


Microsoft.PowerShell and
Microsoft.PowerShell.Workflow. On computers running
64-bit versions of Windows,
PowerShell also provides Microsoft.PowerShell32, a
32-bit session configuration.

The Microsoft.PowerShell session configuration is 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:


PowerShell

PS C:> Get-PSSessionConfiguration | Format-List -Property Name, Permission

Name : microsoft.powershell
Permission : BUILTIN\Administrators AccessAllowed

Name : microsoft.powershell.workflow

Permission : BUILTIN\Administrators AccessAllowed

Name : microsoft.powershell32

Permission : BUILTIN\Administrators AccessAllowed

The session configuration object is expanded in PowerShell 3.0 to


display the properties
of the session configuration that are configured by
using a session configuration file.

For example, to see all of the properties of a session configuration


object, type:

PowerShell

PS C:> Get-PSSessionConfiguration | Format-List -Property *

You can also use the WSMan provider in PowerShell to view session
configurations. The
WSMan 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:

PowerShell

PS C:> dir wsman:\localhost\plugin\microsoft*

WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Plugin

Type Keys Name

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

Container {Name=microsoft.powershell} microsoft.powershell

Container {Name=microsoft.powershell.wor... microsoft.powershell.workflow

Container {Name=microsoft.powershell32} microsoft.powershell32

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.

PowerShell

PS C:> 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:

PowerShell

PS C:> 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\Pl

ugin

Type Keys Name

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

Container {Name=microsoft.powershell} microsoft.powershell

Container {Name=microsoft.powershell.wor... microsoft.powershell.workflow

Container {Name=microsoft.powershell32} microsoft.powershell32

Changing the Security Descriptor of a Session Configuration

In Windows Server 2012 and newer releases of Windows Server, the built-in
session
configurations are enabled for remote users by default. In other
supported versions of
Windows, you must change the security descriptors of the
session configurations to
allow remote access.

To enable remote access to the session configurations on the computer, use the
Enable-
PSRemoting cmdlet.

Also, by default, only 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.

PowerShell

Set-PSSessionConfiguration -name Microsoft.PowerShell `

-ShowSecurityDescriptorUI

To deny everyone permission to all the session configurations on the computer,


use the
Disable-PSSessionConfiguration cmdlet. For example, the following
command disables
the default session configurations on the computer.

PowerShell

PS C:> Disable-PSSessionConfiguration -Name Microsoft.PowerShell

To prevent remote users from connecting to the computer, but allow local users
to
connect, use the Disable-PSRemoting cmdlet. Disable-PSRemoting adds a
"Network_Deny_All" entry to all session configurations on the computer.

PowerShell

PS C:> Disable-PSRemoting

To allow remote users to use all session configurations on the computer, use
the Enable-
PSRemoting or Enable-PSSessionConfiguration cmdlet. For example,
the following
command enables remote access to the built-in session
configurations.

PowerShell

PS C:> 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:

PowerShell

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

PowerShell

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.

PowerShell

PS C:> Unregister-PSSessionConfiguration -Name NewConfig

For more information, see Unregister-PSSessionConfiguration.

Restoring a Session Configuration


To restore a default session configuration that was deleted (unregistered)
accidentally,
use the Enable-PSRemoting cmdlet.

The Enable-PSRemoting cmdlet recreates all default sessions configurations


that do not
exist on the computer. It does not overwrite or change the
property values of existing
session configurations.

To restore the original property values of a default session configuration,


use the
Unregister-PSSessionConfiguration to delete the session configuration
and then use the
Enable-PSRemoting cmdlet to recreate it.

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.

PowerShell

PS C:> 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.

KEYWORDS
about_Endpoints
about_SessionConfigurations

See also
about_Preference_Variables
about_PSSessions
about_Remote
about_Session_Configuration_Files
New-PSSession
Disable-PSSessionConfiguration
Enable-PSSessionConfiguration
Get-PSSessionConfiguration
Register-PSSessionConfiguration
Set-PSSessionConfiguration
Unregister-PSSessionConfiguration
New-PSSessionConfigurationFile
Test-PSSessionConfigurationFile
about_Session_Configuration_Files
Article • 09/19/2022 • 9 minutes to read

Short description
Describes session configuration files, which are used in a session
configuration (also
known as an "endpoint") to define the environment of
sessions that use the session
configuration.

Long description
A "session configuration file" is a text file with a .pssc file name extension
that contains a
hash table of session configuration properties and values. You
can use a session
configuration file to set the properties of a session
configuration. Doing so defines the
environment of any Windows PowerShell
sessions that use that session configuration.

Session configuration files make it easy to create custom session


configurations without
using complex C# assemblies or scripts.

A "session configuration" or "endpoint" is a collection of local computer


settings that
determine such things as which users can create sessions on the
computer; which
commands users can run in those sessions; and whether the
session should run as a
privileged virtual account. For more information about
session configurations, see
about_Session_Configurations.

Session configurations were introduced in Windows PowerShell 2.0, and session


configuration files were introduced in Windows PowerShell 3.0. You must use
Windows
PowerShell 3.0 to include a session configuration file in a session
configuration.
However, users of Windows PowerShell 2.0 (and later) are
affected by the settings in the
session configuration.

Creating Custom Sessions


You can customize many features of a Windows PowerShell session by specifying
session properties in a session configuration. You can customize a session by
writing a
C# program that defines a custom runspace, or you can use a session
configuration file
to define the properties of sessions created by using the
session configuration. As a
general rule, it is easier to use the session
configuration file than to write a C# program.
You can use a session configuration file to create items such as
fully-functioning
sessions for highly trusted users; locked-down sessions that
allow minimal access;
sessions designed for particular and that contain only
the modules required for those
tasks; and sessions where unprivileged users
can only run specific commands as a
privileged account.

In addition to that, you can manage whether users of the session can use
Windows
PowerShell language elements such as script blocks, or whether they
can only run
commands. You can manage the version of Windows PowerShell users
can run in the
session; manage which modules are imported into the session;
and manage which
cmdlets, functions, and aliases session users can run. When
using the RoleDefinitions
field, you can give users different capabilities in
the session based on group
membership.

For more information about RoleDefinitions and how to define this Value, see
the help
topic for the New-PSRoleCapabilityFile Cmdlet.

Creating a Session Configuration File


The easiest way to create a session configuration file is by using the
New-
PSSessionConfigurationFile cmdlet. This cmdlet generates a file that uses
the correct
syntax and format, and that automatically verifies many of the
configuration file
property values.

For detailed descriptions of the properties that you can set in a session
configuration
file, see the help topic for the New-PSSessionConfigurationFile
cmdlet.

The following command creates a session configuration file that uses the
default values.
The resulting configuration file uses only the default values
because no parameters
other than the Path parameter (which specifies the file
path) are included:

PowerShell

New-PSSessionConfigurationFile -Path .\Defaults.pssc

To view the new configuration file in your default text editor, use the
following
command:

PowerShell

Invoke-Item -Path .\Defaults.pssc

To create a session configuration for sessions in which user can run commands,
but not
use other elements of the Windows PowerShell language, type:

PowerShell

New-PSSessionConfigurationFile -LanguageMode NoLanguage

-Path .\NoLanguage.pssc

In the preceding command, setting the LanguageMode parameter to NoLanguage


prevents users from doing such things as writing or running scripts, or using
variables.

To create a session configuration for sessions in which users can use only Get
cmdlets,
type:

PowerShell

New-PSSessionConfigurationFile -VisibleCmdlets Get-*

-Path .\GetSessions.pssc

In the preceding example, setting the VisibleCmdlets parameter to Get-* limits


users to
cmdlets that have names that start with the string value "Get-".

To create a session configuration for sessions that run under a privileged


virtual account
instead of the user's credentials, type:

PowerShell

New-PSSessionConfigurationFile -RunAsVirtualAccount

-Path .\VirtualAccount.pssc

To create a session configuration for sessions in which the commands visible


to the user
are specified in a role capabilities file, type:

PowerShell

New-PSSessionConfigurationFile -RoleDefinitions

@{ 'CONTOSO\User' = @{ RoleCapabilities = 'Maintenance' }}

-Path .\Maintenance.pssc

Using a Session Configuration File


You can include a session configuration file when you create a session
configuration or
add you can add a file to the session configuration at a
later time.
To include a session configuration file when creating a session configuration,
use the
Path parameter of the Register-PSSessionConfiguration cmdlet.

For example, the following command uses the NoLanguage.pssc file when it
creates a
NoLanguage session configuration.

PowerShell

Register-PSSessionConfiguration -Name NoLanguage

-Path .\NoLanguage.pssc

When a new NoLanguage session starts, users will only have access to Windows
PowerShell commands.

To add a session configuration file to an existing session configuration, use


the Set-
PSSessionConfiguration cmdlet and the Path parameter. This affects any
new sessions
created with the specified session configuration. Note that the
Set-
PSSessionConfiguration cmdlet changes the session itself and does not
modify the
session configuration file.

For example, the following command adds the NoLanguage.pssc file to the
LockedDown
session configuration.

PowerShell

Set-PSSessionConfiguration -Name LockedDown

-Path .\NoLanguage.pssc

When users use the LockedDown session configuration to create a session, they
will be
able to run cmdlets but they will not be able to create or use
variables, assign values, or
use other Windows PowerShell language elements.

The following command uses the New-PSSession cmdlet to create a session on the
computer Srv01 that uses the LockedDown session configuration, saving an
object
reference to the session in the $s variable. The ACL (access control
list) of the session
configuration determines who can use it to create a
session.

PowerShell

$s = New-PSSession -ComputerName Srv01

-ConfigurationName LockedDown

Because the NoLanguage constraints were added to the LockedDown session


configuration, users in LockedDown sessions will only be able to run Windows
PowerShell commands and cmdlets. For example, the following two commands use
the
Invoke-Command cmdlet to run commands in the session referenced in the $s
variable.
The first command, which runs the Get-UICulture cmdlet and does not
use any variables,
succeeds. The second command, which gets the value of the
$PSUICulture variable, fails.

Invoke-Command -Session $s {Get-UICulture}

en-US

Invoke-Command -Session $s {$PSUICulture}

The syntax is not supported by this runspace. This might be

because it is in no-language mode.

+ CategoryInfo : ParserError: ($PSUICulture:String) [],

ParseException

+ FullyQualifiedErrorId : ScriptsNotAllowed

Editing a Session Configuration File


All settings in a session configuration except for RunAsVirtualAccount and
RunAsVirtualAccountGroups can be modified by editing the session configuration
file
used by the session configuration. To do this, begin by locating the
active copy of the
session configuration file.

When you use a session configuration file in a session configuration, Windows


PowerShell creates an active copy of the session configuration file and stores
it in the
$pshome\SessionConfig directory on the local computer.

The location of the active copy of a session configuration file is stored in


the
ConfigFilePath property of the session configuration object.

The following command gets the location of the session configuration file for
the
NoLanguage session configuration.

PowerShell

(Get-PSSessionConfiguration -Name NoLanguage).ConfigFilePath

That command returns a file path similar to the following:

C:\WINDOWS\System32\WindowsPowerShell\v1.0\SessionConfig\

NoLanguage_0c115179-ff2a-4f66-a5eb-e56e5692ba22.pssc

You can edit the .pssc file in any text editor. After the file is saved it
will be employed by
any new sessions that use the session configuration.

If you need to modify the RunAsVirtualAccount or the RunAsVirtualAccountGroups


settings, you must un-register the session configuration and re-register a
session
configuration file that includes the edited values.

Testing a Session Configuration File


Use the Test-PSSessionConfigurationFile cmdlet to test manually edited session
configuration files. That's important: if the file syntax and values are not
valid users will
not be able to use the session configuration to create a
session.

For example, the following command tests the active session configuration file
of the
NoLanguage session configuration.

PowerShell

Test-PSSessionConfigurationFile -Path C:\WINDOWS\System32\

WindowsPowerShell\v1.0\SessionConfig\

NoLanguage_0c115179-ff2a-4f66-a5eb-e56e5692ba22.pssc

If the syntax and values in the configuration file are valid


Test-
PSSessionConfigurationFile returns True. If the syntax and values are not
valid then the
cmdlet returns False.

You can use Test-PSSessionConfigurationFile to test any session configuration


file,
including files that the New-PSSessionConfiguration cmdlet creates. For
more
information, see the help topic for the Test-PSSessionConfigurationFile
cmdlet.

Removing a Session Configuration File


You cannot remove a session configuration file from a session configuration.
However,
you can replace the file with a new file that uses the default
settings. This effectively
cancels the settings used by the original
configuration file.

To replace a session configuration file, create a new session configuration


file that uses
the default settings, then use the Set-PSSessionConfiguration
cmdlet to replace the
custom session configuration file with the new file.

For example, the following commands create a Default session configuration


file and
then replace the active session configuration file in the NoLanguage
session
configuration.
PowerShell

New-PSSessionConfigurationFile -Path .\Default.pssc

Set-PSSessionConfiguration -Name NoLanguage

-Path .\Default.pssc

When these commands finish, the NoLanguage session configuration will actually
provide full language support (the default setting) for all sessions created
with that
session configuration.

Viewing the Properties of a Session Configuration The session configuration


objects that
represent session configurations using session configuration
files have additional
properties that make it easy to discover and analyze the
session configuration. (Note
that the type name shown below includes a
formatted view definition.) You can view the
properties by running the
Get-PSSessionConfiguration cmdlet and piping the returned
data to the
Get-Member cmdlet:

PowerShell

Get-PSSessionConfiguration NoLanguage | Get-Member

Output

TypeName: Microsoft.PowerShell.Commands.PSSessionConfigurationCommands

#PSSessionConfiguration

Name MemberType Definition

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

Equals Method bool Equals(System.O...

GetHashCode Method int GetHashCode()

GetType Method type GetType()

ToString Method string ToString()

Architecture NoteProperty System.String Archit...

Author NoteProperty System.String Author...

AutoRestart NoteProperty System.String AutoRe...

Capability NoteProperty System.Object[] Capa...

CompanyName NoteProperty System.String Compan...

configfilepath NoteProperty System.String config...

Copyright NoteProperty System.String Copyri...

Enabled NoteProperty System.String Enable...

ExactMatch NoteProperty System.String ExactM...

ExecutionPolicy NoteProperty System.String Execut...

Filename NoteProperty System.String Filena...

GUID NoteProperty System.String GUID=0...

ProcessIdleTimeoutSec NoteProperty System.String Proces...

IdleTimeoutms NoteProperty System.String IdleTi...

lang NoteProperty System.String lang=e...

LanguageMode NoteProperty System.String Langua...

MaxConcurrentCommandsPerShell NoteProperty System.String MaxCon...

MaxConcurrentUsers NoteProperty System.String MaxCon...

MaxIdleTimeoutms NoteProperty System.String MaxIdl...

MaxMemoryPerShellMB NoteProperty System.String MaxMem...

MaxProcessesPerShell NoteProperty System.String MaxPro...

MaxShells NoteProperty System.String MaxShells

MaxShellsPerUser NoteProperty System.String MaxShe...

Name NoteProperty System.String Name=N...

PSVersion NoteProperty System.String PSVersion

ResourceUri NoteProperty System.String Resour...

RunAsPassword NoteProperty System.String RunAsP...

RunAsUser NoteProperty System.String RunAsUser

SchemaVersion NoteProperty System.String Schema...

SDKVersion NoteProperty System.String SDKVer...

OutputBufferingMode NoteProperty System.String Output...

SessionType NoteProperty System.String Sessio...

UseSharedProcess NoteProperty System.String UseSha...

SupportsOptions NoteProperty System.String Suppor...

xmlns NoteProperty System.String xmlns=...

XmlRenderingType NoteProperty System.String XmlRen...

Permission ScriptProperty System.Object Permis...

These properties make it easy to search for specific session configurations.


For example,
you can use the ExecutionPolicy property to find a session
configuration that supports
sessions with the RemoteSigned execution policy.
Note that, because the
ExecutionPolicy property exists only on sessions that
use session configuration files, the
command might not return all qualifying
session configurations.

PowerShell

Get-PSSessionConfiguration |

where {$_.ExecutionPolicy -eq "RemoteSigned"}

The following command gets session configurations in which the RunAsUser is


the
Exchange administrator.

PowerShell

Get-PSSessionConfiguration |

where {$_.RunAsUser -eq "Exchange01\Admin01"}

To view information about the role definitions associated with a configuration


use the
Get-PSSessionCapability cmdlet. This cmdlet enables you to determine
the commands
and environment available to specific users in specific
endpoints.

Notes
Session configurations also support a type of session known as an "empty"
session. An
Empty session type enables you to create custom sessions with
selected commands. If
you do not add modules, functions, or scripts to an
empty session, the session is limited
to expressions and might not be of any
practical use. The SessionType property tells you
whether or not you are
working with an empty session.

See also
about_Session_Configurations
New-PSRoleCapabilityFile
New-PSSession
Get-PSSessionCapability
Disable-PSSessionConfiguration
Enable-PSSessionConfiguration
Get-PSSessionConfiguration
Register-PSSessionConfiguration
Set-PSSessionConfiguration
Unregister-PSSessionConfiguration
New-PSSessionConfigurationFile
Test-PSSessionConfigurationFile
about_Signing
Article • 09/19/2022 • 8 minutes to read

Short description
Explains how to sign scripts so that they comply with the PowerShell execution
policies.

Long description
The Restricted execution policy does not permit any scripts to run. The
AllSigned and
RemoteSigned execution policies prevent 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 PowerShell execution policies, see


about_Execution_Policies.

To permit signed scripts to run


When you start 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:

PowerShell

Get-ExecutionPolicy

To run unsigned scripts that you write on your local computer and signed
scripts from
other users, start PowerShell with the Run as Administrator
option and then use the
following command to change the execution policy on
the computer to RemoteSigned:

PowerShell

Set-ExecutionPolicy RemoteSigned

For more information, see the help topic for the Set-ExecutionPolicy cmdlet.
Running unsigned scripts using the
RemoteSigned execution policy
If your PowerShell execution policy is RemoteSigned, PowerShell
will not run unsigned
scripts that are downloaded from the internet, including
unsigned scripts you receive
through email and instant messaging programs.

If you try to run a downloaded script, PowerShell displays the following error
message:

Output

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, use the Unblock-File cmdlet or use the following
procedure.

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, PowerShell displays the following
message:

Output

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

For more information about how to sign a script file, see


Set-AuthenticodeSignature.

The New-SelfSignedCertificate cmdlet, introduced in the PKI module in


PowerShell 3.0,
creates a self-signed certificate that is Appropriate for
testing. For more information, see
the help topic for the
New-SelfSignedCertificate cmdlet.

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
certification 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
New-SelfSignedCertificate cmdlet in the
PKI
module. This module is introduced in PowerShell 3.0 and is included in
Windows 8 and
Windows Server 2012. For more information, see the help topic for
the New-
SelfSignedCertificate cmdlet.

PowerShell
$params = @{

Subject = 'CN=PowerShell Code Signing Cert'

Type = 'CodeSigning'

CertStoreLocation = 'Cert:\CurrentUser\My'

HashAlgorithm = 'sha256'

$cert = New-SelfSignedCertificate @params

Using Makecert.exe
To create a self-signed certificate in earlier versions of Windows, use the
Certificate
Creation tool MakeCert.exe . This tool is included in the
Microsoft .NET 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).

To use the MakeCert.exe tool to create a certificate, run the following


commands in an
SDK Command Prompt window.

7 Note

The first command creates a local certification authority for your computer.
The
second command generates a personal certificate from the certification
authority.
You can copy or type the commands exactly as they appear. No
substitutions are
necessary, although you can change the certificate name.

PowerShell

makecert -n "CN=PowerShell Local Certificate Root" -a sha256 `

-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 sha256 `

-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 PowerShell prompt, type:

PowerShell

Get-ChildItem cert:\CurrentUser\my -codesigning

This command uses the 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:

Output

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.

) Important

The script must be saved using ASCII or UTF8NoBOM encoding. You can sign a
script file that uses a different encoding, but the script fails to run or
the module
containing the script fails to import. The script will also fail
if the file contains
Unicode (UTF8) characters.

To use this script, copy the following text into a text file, and name it
Add-Signature.ps1 .

PowerShell
## 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
PowerShell command prompt:

PowerShell

$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 PowerShell execution policy
requires a digital
signature from a trusted authority. If you try, PowerShell
displays the following error
message:

Output

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 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 protection for your private key


If you have a private key and certificate on your computer, malicious programs might be
able to sign scripts on your behalf, which authorizes PowerShell to run them.

To prevent automated signing on your behalf, use Certificate Manager


Certmgr.exe to
export your signing key and certificate to a .pfx file. Certificate
Manager is included in
the Microsoft .NET SDK, the Microsoft Windows SDK, and
in Internet Explorer.

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
timestamp 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
Set-AuthenticodeSignature
Get-ExecutionPolicy
Set-ExecutionPolicy
Introduction to Code Signing
about_Simplified_Syntax
Article • 09/19/2022 • 2 minutes to read

Short description
Describes easier, more natural-language ways of scripting filters for
collections of
objects.

Long description
Simplified syntax, introduced in Windows PowerShell 3.0, lets you build some
filter
commands without using script blocks. The simplified syntax more
closely resembles
natural language, and is primarily useful with collections
of objects that get piped into
commands Where-Object and ForEach-Object and
their corresponding aliases where
and foreach .

You can use a method on the members of a collection (most commonly, an array)
without referring to the automatic variable $_ inside a script block.

Consider the following two invocations:

Standard Syntax
PowerShell

dir Cert:\LocalMachine\Root | where { $_.FriendlyName -eq 'Verisign' }

dir Cert:\ -Recurse | foreach { $_.GetKeyAlgorithm() }

Simplified syntax
Under the simplified syntax, comparison operators that work on members of objects in a
collection are treated as parameters. You can invoke a method on objects in a
collection
without referring to the automatic variable $_ inside a script block.
Compare the
following two invocations to those of the previous example:

PowerShell

dir Cert:\LocalMachine\Root | where FriendlyName -eq 'Verisign'

dir Cert:\ -Recurse | foreach GetKeyAlgorithm

While both syntaxes work, the simplified syntax returns results without
referring to the
automatic variable $_ inside a script block.
The method name GetKeyAlgorithm is
treated as a parameter of ForEach-Object .
The second command returns the same
results, but without errors,
because the simplified syntax does not attempt to return
results for items
for which the specified argument did not apply.

In this example, the Process property Description is passed as the member name
parameter to the ForEach-Object command. The results are descriptions of active
processes.

PowerShell

Get-Process | foreach Description

In this example, the DirectoryInfo method GetFiles is passed as the member name
parameter of the ForEach-Object command.
The method is called with the search
pattern parameter .* .
The results are FileInfo records for all Unix-style hidden files in
user home directories.

PowerShell

Get-ChildItem /home -Directory | foreach GetFiles .*

See also
about_Comparison_Operators
about_Foreach
Foreach-Object
Where-Object
about_Special_Characters
Article • 01/12/2023 • 4 minutes to read

Short description
Describes the special character sequences that control how PowerShell
interprets the
next characters in the sequence.

Long description
PowerShell supports a set of special character sequences that are used to
represent
characters that aren't part of the standard character set. The
sequences are commonly
known as escape sequences.

Escape sequences begin with the backtick character, known as the grave accent
(ASCII
96), and are case-sensitive. The backtick character can also be referred
to as the escape
character.

Escape sequences are only interpreted when contained in double-quoted ( " )


strings.

PowerShell recognizes these escape sequences:

Sequence Description

`0 Null

`a Alert

`b Backspace

`f Form feed

`n New line

`r Carriage return

`t Horizontal tab

`v Vertical tab

PowerShell also has a special token to mark where you want parsing to stop. All
characters that follow this token are used as literal values that aren't
interpreted.

Special parsing tokens:


Sequence Description

-- Treat the remaining values as arguments not parameters

--% Stop parsing anything that follows

Null (`0)
The null ( `0 ) character appears as an empty space in PowerShell output.
This
functionality allows you to use PowerShell to read and process text files
that use null
characters, such as string termination or record termination
indicators. The null special
character isn't equivalent to the $null
variable, which stores a null value.

Alert (`a)
The alert ( `a ) character sends a beep signal to the computer's speaker.
You can use this
character to warn a user about an impending action. The
following example sends two
beep signals to the local computer's speaker.

PowerShell

for ($i = 0; $i -le 1; $i++){"`a"}

Backspace (`b)
The backspace ( `b ) character moves the cursor back one character, but it
doesn't delete
any characters.

The example writes the word backup and then moves the cursor back twice.
Then, at the
new position, writes a space followed by the word out.

PowerShell

"backup`b`b out"

Output

back out

Form feed (`f)


The form feed ( `f ) character is a print instruction that ejects the
current page and
continues printing on the next page. The form feed character
only affects printed
documents. It doesn't affect screen output.

New line (`n)


The new line ( `n ) character inserts a line break immediately after the
character.

This example shows how to use the new line character to create line breaks in a
Write-
Host command.

PowerShell

"There are two line breaks to create a blank line`n`nbetween the words."

Output

There are two line breaks to create a blank line

between the words.

Carriage return (`r)


The carriage return ( `r ) character moves the output cursor to the
beginning of the
current line and continues writing. Any characters on the
current line are overwritten.

In this example, the text before the carriage return is overwritten.

PowerShell

Write-Host "These characters are overwritten.`rI want this text instead "

Notice that the text before the `r character isn't deleted, it's
overwritten.

Output

I want this text instead written.


Horizontal tab (`t)
The horizontal tab ( `t ) character advances to the next tab stop and
continues writing at
that point. By default, the PowerShell console has a tab
stop at every eighth space.

This example inserts two tabs between each column.

PowerShell

"Column1`t`tColumn2`t`tColumn3"

Output

Column1 Column2 Column3

Vertical tab (`v)


The vertical tab ( `v ) character advances to the next vertical tab stop
and writes the
remaining output at that point. The rendering of the the
vertical tab is device and
terminal dependent.

PowerShell

Write-Host "There is a vertical tab`vbetween the words."

The following examples show the rendered output of the vertical tab in some
common
environments.

The Windows Console host application interprets ( `v ) as a special


character with no
extra spacing added.

Output

There is a vertical tab♂between the words.

The Windows Terminal renders the vertical tab character as a carriage


return and line
feed. The rest of the output is printed at the beginning of the
next line.

Output

There is a vertical tab

between the words.

On printers or in a unix-based consoles, the vertical tab character advances to


the next
line and writes the remaining output at that point.

Output

There is a vertical tab

between the words.

Line continuation
The backtick character can also be used at the end of a line as a signal to the
PowerShell
parser that the command continues on the next line. For more
information, see
about_Parsing.

The end-of-parameters token ( -- )


The end-of-parameters token ( -- ) indicates that all arguments following it
are to be
passed in their actual form as though double quotes were placed
around them. For
example, using -- you can output the string -InputObject
without using quotes or
having it interpreted as a parameter:

PowerShell

Write-Output -- -InputObject

Output

-InputObject

This is a convention specified in the POSIX Shell and Utilities specification.

Stop-parsing token (--%)


The stop-parsing ( --% ) token prevents PowerShell from interpreting strings as
PowerShell commands and expressions. This allows those strings to be passed to
other
programs for interpretation.

Place the stop-parsing token after the program name and before program
arguments
that might cause errors.

In this example, the Icacls command uses the stop-parsing token.


PowerShell

icacls X:\VMS --% /grant Dom\HVAdmin:(CI)(OI)F

PowerShell sends the following string to Icacls .

X:\VMS /grant Dom\HVAdmin:(CI)(OI)F

Here is another example. The showArgs function outputs the values passed to
it. In this
example, we pass the variable named $HOME to the function twice.

PowerShell

function showArgs {

"`$args = " + ($args -join '|')

showArgs $HOME --% $HOME

You can see in the output that, for the first parameter, the variable $HOME
is interpreted
by PowerShell so that the value of the variable is passed to the
function. The second use
of $HOME comes after the stop-parsing token, so the
string "$HOME" is passed to the
function without interpretation.

Output

$args = C:\Users\username|--%|$HOME

For more information about the stop-parsing token, see about_Parsing.

See also
about_Quoting_Rules
about_Splatting
Article • 12/12/2022 • 7 minutes to read

Short description
Describes how to use splatting to pass parameters to commands in PowerShell.

Long description
Splatting is a method of passing a collection of parameter values to a command
as a
unit. PowerShell associates each value in the collection with a command
parameter.
Splatted parameter values are stored in named splatting variables,
which look like
standard variables, but begin with an At symbol ( @ ) instead
of a dollar sign ( $ ). The At
symbol tells PowerShell that you are passing a
collection of values, instead of a single
value.

Splatting makes your commands shorter and easier to read. You can reuse the
splatting
values in different command calls and use splatting to pass parameter
values from the
$PSBoundParameters automatic variable to other scripts and
functions.

Beginning in Windows PowerShell 3.0, you can also use splatting to represent
all
parameters of a command.

Syntax

<CommandName> <optional parameters> @<HashTable> <optional parameters>

<CommandName> <optional parameters> @<Array> <optional parameters>

To provide parameter values for positional parameters, in which parameter names


are
not required, use the array syntax. To provide parameter name and value
pairs, use the
hash table syntax. The splatted value can appear anywhere in the
parameter list.

When splatting, you do not need to use a hash table or an array to pass all
parameters.
You may pass some parameters by using splatting and pass others by
position or by
parameter name. Also, you can splat multiple objects in a single
command so you don't
pass more than one value for each parameter.
Splatting with hash tables
Use a hash table to splat parameter name and value pairs. You can use this
format for all
parameter types, including positional and switch parameters.
Positional parameters
must be assigned by name.

The following examples compare two Copy-Item commands that copy the Test.txt
file to
the Test2.txt file in the same directory.

The first example uses the traditional format in which parameter names are
included.

PowerShell

Copy-Item -Path "test.txt" -Destination "test2.txt" -WhatIf

The second example uses hash table splatting. The first command creates a hash
table
of parameter-name and parameter-value pairs and stores it in the
$HashArguments
variable. The second command uses the $HashArguments
variable in a command with
splatting. The At symbol ( @HashArguments ) replaces
the dollar sign ( $HashArguments ) in
the command.

To provide a value for the WhatIf switch parameter, use $True or $False .

PowerShell

$HashArguments = @{

Path = "test.txt"

Destination = "test2.txt"

WhatIf = $true

Copy-Item @HashArguments

7 Note

In the first command, the At symbol ( @ ) indicates a hash table, not a


splatted value.
The syntax for hash tables in PowerShell is:
@{<name>=<value>; <name>=<value>;
...}

Splatting with arrays


Use an array to splat values for positional parameters, which do not require
parameter
names. The values must be in position-number order in the array.
The following examples compare two Copy-Item commands that copy the Test.txt
file to
the Test2.txt file in the same directory.

The first example uses the traditional format in which parameter names are
omitted. The
parameter values appear in position order in the command.

PowerShell

Copy-Item "test.txt" "test2.txt" -WhatIf

The second example uses array splatting. The first command creates an array of
the
parameter values and stores it in the $ArrayArguments variable. The
values are in
position order in the array. The second command uses the
$ArrayArguments variable in a
command in splatting. The At symbol
( @ArrayArguments ) replaces the dollar sign
( $ArrayArguments ) in the
command.

PowerShell

$ArrayArguments = "test.txt", "test2.txt"

Copy-Item @ArrayArguments -WhatIf

Using the ArgumentList parameter


Several cmdlets have an ArgumentList parameter that is used to pass
parameter values
to a script block that is executed by the cmdlet. The
ArgumentList parameter takes an
array of values that is passed to the
script block. PowerShell is effectively using array
splatting to bind the
values to the parameters of the script block. When using
ArgumentList, if
you need to pass an array as a single object bound to a single
parameter, you
must wrap the array as the only element of another array.

The following example has a script block that takes a single parameter that is
an array of
strings.

PowerShell

$array = 'Hello', 'World!'

Invoke-Command -ScriptBlock {

param([string[]]$words) $words -join ' '

} -ArgumentList $array

In this example, only the first item in $array is passed to the script block.

Output
Hello

PowerShell

$array = 'Hello', 'World!'

Invoke-Command -ScriptBlock {

param([string[]]$words) $words -join ' '

} -ArgumentList (,$array)

In this example, $array is wrapped in an array so that the entire


array is passed to the
script block as a single object.

Output

Hello World!

Examples

Example 1: Reuse splatted parameters in different


commands
This example shows how to reuse splatted values in different commands. The
commands in this example use the Write-Host cmdlet to write messages to the
host
program console. It uses splatting to specify the foreground and
background colors.

To change the colors of all commands, just change the value of the $Colors
variable.

The first command creates a hash table of parameter names and values and stores
the
hash table in the $Colors variable.

PowerShell

$Colors = @{ForegroundColor = "black"; BackgroundColor = "white"}

The second and third commands use the $Colors variable for splatting in a
Write-Host
command. To use the $Colors variable , replace the dollar sign
( $Colors ) with an At
symbol ( @Colors ).

PowerShell
#Write a message with the colors in $Colors

Write-Host "This is a test." @Colors

#Write second message with same colors. The position of splatted

#hash table does not matter.

Write-Host @Colors "This is another test."

Example 2: Forward parameters using


$PSBoundParameters
This example shows how to forward their parameters to other commands using
splatting and the $PSBoundParameters automatic variable.

The $PSBoundParameters automatic variable is a dictionary object


(System.Collections.Generic.Dictionary) that contains all the parameter names
and values
that are used when a script or function is run.

In the following example, we use the $PSBoundParameters variable to forward


the
parameters values passed to a script or function from Test2 function to
the Test1
function. Both calls to the Test1 function from Test2 use
splatting.

PowerShell

function Test1

param($a, $b, $c)

"a = $a"

"b = $b"

"c = $c"

function Test2

param($a, $b, $c)

#Call the Test1 function with $a, $b, and $c.

Test1 @PSBoundParameters

#Call the Test1 function with $b and $c, but not with $a

Test1 -b $PSBoundParameters.b -c $PSBoundParameters.c

Test2 -a 1 -b 2 -c 3

Output
a = 1

b = 2

c = 3

a =

b = 2

c = 3

Splatting command parameters


You can use splatting to represent the parameters of a command. This technique
is
useful when you are creating a proxy function, that is, a function that
calls another
command. This feature is introduced in Windows PowerShell 3.0.

To splat the parameters of a command, use @Args to represent the command


parameters. This technique is easier than enumerating command parameters and
it
works without revision even if the parameters of the called command change.

The feature uses the $Args automatic variable, which contains all unassigned
parameter
values.

For example, the following function calls the Get-Process cmdlet. In this
function, @Args
represents all the parameters of the Get-Process cmdlet.

PowerShell

function Get-MyProcess { Get-Process @Args }

When you use the Get-MyProcess function, all unassigned parameters and
parameter
values are passed to @Args , as shown in the following commands.

PowerShell

Get-MyProcess -Name PowerShell

Output

Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName

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

463 46 225484 237196 719 15.86 3228 powershell

PowerShell

Get-MyProcess -Name PowerShell_Ise -FileVersionInfo

Output

ProductVersion FileVersion FileName

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

6.2.9200.16384 6.2.9200.1638... C:\Windows\system32\WindowsPowerShell\...

You can use @Args in a function that has explicitly declared parameters. You
can use it
more than once in a function, but all parameters that you enter are
passed to all
instances of @Args , as shown in the following example.

PowerShell

function Get-MyCommand

Param ([switch]$P, [switch]$C)

if ($P) { Get-Process @Args }

if ($C) { Get-Command @Args }

Get-MyCommand -P -C -Name PowerShell

Output

Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName

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

408 28 75568 83176 620 1.33 1692 powershell

Path : C:\Windows\System32\WindowsPowerShell\v1.0\powershell.e

Extension : .exe

Definition : C:\Windows\System32\WindowsPowerShell\v1.0\powershell.e

Visibility : Public

OutputType : {System.String}

Name : powershell.exe

CommandType : Application

ModuleName :

Module :

RemotingCapability : PowerShell

Parameters :

ParameterSets :

HelpUri :

FileVersionInfo : File: C:\Windows\System32\WindowsPowerShell

\v1.0\powershell.exe

InternalName: POWERSHELL

OriginalFilename: PowerShell.EXE.MUI

FileVersion: 10.0.14393.0 (rs1_release.160715-1616

FileDescription: Windows PowerShell

Product: Microsoft Windows Operating System

ProductVersion: 10.0.14393.0

Debug: False

Patched: False

PreRelease: False

PrivateBuild: False

SpecialBuild: False

Language: English (United States)

Notes
If you make a function into an advanced function by using either the
CmdletBinding or
Parameter attributes, the $args automatic variable
is no longer available in the function.
Advanced functions require explicit
parameter definition.

PowerShell Desired State Configuration (DSC) was not designed to use splatting.
You
cannot use splatting to pass values into a DSC resource. For more
information, see Gael
Colas' article Pseudo-Splatting DSC Resources .

See also
about_Arrays
about_Automatic_Variables
about_Hash_Tables
about_Parameters
about_Split
Article • 09/19/2022 • 7 minutes to read

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. The Split
operator in PowerShell
uses a regular expression in the delimiter,
rather than a simple character.
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>

-Split (<String[]>)

<String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]]

<String> -Split {<ScriptBlock>} [,<Max-substrings>]

You can substitute -iSplit or -cSplit for -split in any binary Split
statement (a Split
statement that includes a delimiter or script block). 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> or <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:

PowerShell

"Lastname:FirstName:Address" -split ":"

Lastname

FirstName

Address

By default, the delimiter is omitted from the results. To preserve all or part
of the
delimiter, enclose in parentheses the part that you want to preserve.
If the <Max-
substrings> parameter is added, this takes precedence when your
command splits up
the collection. If you opt to include a delimiter as part of
the output, the command
returns the delimiter as part of the output; however,
splitting the string to return the
delimiter as part of output does not count
as a split.

Examples:

PowerShell

"Lastname:FirstName:Address" -split "(:)"

Lastname

FirstName

Address

"Lastname/:/FirstName/:/Address" -split "/(:)/"

Lastname

FirstName

Address

<Max-substrings>

Specifies the maximum number of substrings returned by the split operation. The
default is all substrings split by the delimiter. If there are more
substrings, they are
concatenated to the final substring. If there are fewer
substrings, all substrings are
returned. A value of 0 returns all the
substrings.

Example:

PowerShell

$c = "Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune"

$c -split ",", 5

Output

Mercury

Venus

Earth

Mars

Jupiter,Saturn,Uranus,Neptune

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.

PowerShell

$c = 'a,b,c','1,2,3,4,5'

$c -split ',', 3

3,4,5

<Max-substrings> does not specify the maximum number of objects that are
returned.

In the following example, <Max-substrings> is set to 3.


This results in three substring
values, but a total of five strings
in the resulting output. The delimiter is included after
the splits until the
maximum of three substrings is reached. Additional delimiters in the
final
substring become part of the substring.

PowerShell

'Chocolate-Vanilla-Strawberry-Blueberry' -split '(-)', 3

Output

Chocolate

Vanilla

Strawberry-Blueberry

Negative values are ignored.

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

PowerShell

$c = "Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune"

$c -split {$_ -eq "e" -or $_ -eq "p"}

Output

rcury,V

nus,

arth,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 forces ^ and $ to match the beginning
end of every line
instead of the beginning and end of the input string.
Singleline: Singleline mode treats the input string as a SingleLine.
It forces the .
character to match every character (including newlines),
instead of matching every
character EXCEPT the newline \n .
ExplicitCapture: Ignores non-named match groups so that only
explicit capture
groups are returned in the result list. Valid
only with RegexMatch.

7 Note
SingleLine is the default behavior. Singleline and Multiline
cannot be used together
with the options parameter. This was resolved in
PowerShell 6.0.
The work around is
by using Mode-Modifiers in your regular expression.
You can read more about
mode modifiers in Regular Expression Options

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.

Use one of the following patterns to split more than one string:

Use the binary split operator (<string[]> -split <delimiter>)


Enclose all the strings in parentheses
Store the strings in a variable then submit the variable to the split
operator

Consider the following example:

PS> -split "1 2", "a b"

a b

PS> "1 2", "a b" -split " "

PS> -split ("1 2", "a b")

PS> $a = "1 2", "a b"

PS> -split $a

Examples
The following statement splits the string at whitespace.

PowerShell

-split "Windows PowerShell 2.0`nWindows PowerShell with remoting"

Output

Windows

PowerShell

2.0

Windows

PowerShell

with

remoting

The following statement splits the string at any comma.

PowerShell

"Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune" -split ','

Output

Mercury

Venus

Earth

Mars

Jupiter

Saturn

Uranus

Neptune

The following statement splits the string at the pattern "er".


PowerShell

"Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune" -split 'er'

Output

cury,Venus,Earth,Mars,Jupit

,Saturn,Uranus,Neptune

The following statement performs a case-sensitive split at the letter "N".

PowerShell

"Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune" -cSplit 'N'

Output

Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,

eptune

The following statement splits the string at "e" and "t".

PowerShell

"Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune" -split '[et]'

Output

rcury,V

nus,

ar

h,Mars,Jupi

r,Sa

urn,Uranus,N

un

The following statement splits the string at "e" and "r", but limits the
resulting substrings
to six substrings.

PowerShell
"Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune" -split '[er]', 6

Output

cu

y,V

nus,

arth,Mars,Jupiter,Saturn,Uranus,Neptune

The following statement splits a string into three substrings.

PowerShell

"a,b,c,d,e,f,g,h" -split ",", 3

Output

c,d,e,f,g,h

The following statement splits two strings into three substrings.


(The limit is applied to
each string independently.)

PowerShell

"a,b,c,d", "e,f,g,h" -split ",", 3

Output

c,d

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

$a = @'

1The first line.

2The second line.

3The third of three lines.

'@

$a -split "^\d", 0, "multiline"

Output

The first line.

The second line.

The third of three lines.

The following statement uses the backslash character to escape the dot (.)
delimiter.

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.

PowerShell

"This.is.a.test" -split "\."

Output

This

is

test

The following statement uses the SimpleMatch option to direct the -split
operator to
interpret the dot (.) delimiter literally.

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.

PowerShell

"This.is.a.test" -split ".", 0, "simplematch"

Output

This

is

test

The following statement splits the string at one of two delimiters, depending
on the
value of a variable.

PowerShell

$i = 1

$c = "LastName, FirstName; Address, City, State, Zip"

$c -split $(if ($i -lt 1) {","} else {";"})

Output

LastName, FirstName

Address, City, State, Zip

See also
Split-Path
about_Operators
about_Comparison_Operators
about_Join
about_Switch
Article • 09/19/2022 • 7 minutes to read

Short description
Explains how to use a switch to handle multiple if statements.

Long description
To check a condition in a script or function, use an if statement. The if
statement can
check many types of conditions, including the value of variables
and the properties of
objects.

To check multiple conditions, use a switch statement. The switch statement


is
equivalent to a series of if statements, but it is simpler. The switch
statement lists each
condition and an optional action. If a condition obtains,
the action is performed.

The switch statement can use the $_ and $switch automatic variables. For
more
information, see
about_Automatic_Variables.

Syntax
A basic switch statement has the following format:

Syntax

Switch (<test-expression>)

<result1-to-be-matched> {<action>}

<result2-to-be-matched> {<action>}

The equivalent if statements are:

Syntax

if (<result1-to-be-matched> -eq (<test-expression>)) {<action>}

if (<result2-to-be-matched> -eq (<test-expression>)) {<action>}

The <test-expression> is single expression that is evaluated in expression


mode to
return a value.

The <result-to-be-matched> is an expression whose value is compared to the


input
value. Expressions include literal values (strings or numbers),
variables, and scriptblocks
that return a boolean value.

Any unquoted value that is not recognized as a number is treated as a string.


To avoid
confusion or unintended string conversion, you should always quote
string values.
Enclose any expressions in parentheses () , creating
subexpressions, to ensure that the
expression is evaluated correctly.

It is important to understand that the <result-to-be-matched> value is on the


left-hand
side of the comparison expression. That means the result of the
<test-expression> is on
the right-hand side, which can be converted to the
type of the left-hand side value for
comparison. For more information, see
about_Comparison_Operators

The value default is reserved for the action used when there are no other
matches.

The $_ automatic variable contains the value of the expression passed to the
switch
statement and is available for evaluation and use within the scope of
the <result-to-be-
matched> statements.

The complete switch statement syntax is as follows:

Syntax

switch [-regex | -wildcard | -exact] [-casesensitive] (<test-expression>)

"string" | number | variable | { <value-scriptblock> } { <action-


scriptblock> }

default { <action-scriptblock> } # optional

or

Syntax

switch [-regex | -wildcard | -exact] [-casesensitive] -file filename

"string" | number | variable | { <value-scriptblock> } { <action-


scriptblock> }

default { <action-scriptblock> } # optional

If no parameters are used, switch behaves the same as using the Exact
parameter. It
performs a case-insensitive match for the value. If the value is
a collection, each element
is evaluated in the order in which it appears.

The switch statement must include at least one condition statement.

The default clause is triggered when the value does not match any of the
conditions. It
is equivalent to an else clause in an if statement. Only one
default clause is
permitted in each switch statement.

switch has the following parameters:

Wildcard - Indicates that the condition is a wildcard string. If the


match clause is
not a string, the parameter is ignored. The comparison is
case-insensitive.
Exact - Indicates that the match clause, if it is a string, must match
exactly. If the
match clause is not a string, this parameter is ignored. The
comparison is case-
insensitive.
CaseSensitive - Performs a case-sensitive match. If the match clause is
not a string,
this parameter is ignored.
File- Takes input from a file rather than a <test-expression> . If
multiple File
parameters are included, only the last one is used. Each
line of the file is read and
evaluated by the switch statement. The
comparison is case-insensitive.
Regex - Performs regular expression matching of the value to the
condition. If the
match clause is not a string, this parameter is ignored.
The comparison is case-
insensitive. The $matches automatic variable is
available for use within the
matching statement block.

7 Note

When specifying conflicting values, like Regex and Wildcard, the last
parameter
specified takes precedence, and all conflicting parameters are
ignored. Multiple
instances of parameters are also permitted. However, only
the last parameter listed
is used.

Examples
In the following example, the switch statement compares the test value, 3, to
each of
the conditions. When the test value matches the condition, the action
is performed.

PowerShell
switch (3)

1 {"It is one."}

2 {"It is two."}

3 {"It is three."}

4 {"It is four."}

Output

It is three.

In this simple example, the value is compared to each condition in the list,
even though
there is a match for the value 3. The following switch statement
has two conditions for
a value of 3. It demonstrates that, by default, all
conditions are tested.

PowerShell

switch (3)

1 {"It is one."}

2 {"It is two."}

3 {"It is three."}

4 {"It is four."}

3 {"Three again."}

Output

It is three.

Three again.

To direct the switch to stop comparing after a match, use the break
statement. The
break statement terminates the switch statement.

PowerShell

switch (3)

1 {"It is one."}

2 {"It is two."}

3 {"It is three."; Break}

4 {"It is four."}

3 {"Three again."}

Output

It is three.

If the test value is a collection, such as an array, each item in the


collection is evaluated
in the order in which it appears. The following
examples evaluates 4 and then 2.

PowerShell

switch (4, 2)

1 {"It is one." }

2 {"It is two." }

3 {"It is three." }
4 {"It is four." }

3 {"Three again."}

Output

It is four.

It is two.

Any break statements apply to the collection, not to each value, as shown
in the
following example. The switch statement is terminated by the break
statement in the
condition of value 4.

PowerShell

switch (4, 2)

1 {"It is one."; Break}

2 {"It is two." ; Break }

3 {"It is three." ; Break }

4 {"It is four." ; Break }

3 {"Three again."}

Output

It is four.

In this example, an object that's not a string or numerical data is passed to


the switch .
The switch performs a string coercion on the object and
evaluates the outcome.
PowerShell

$test = @{

Test = 'test'

Test2 = 'test2'

$test.ToString()

switch -Exact ($test)

'System.Collections.Hashtable'

'Hashtable string coercion'

'test'

'Hashtable value'

Output

System.Collections.Hashtable

Hashtable string coercion

In this example, there is no matching case so there is no output.

PowerShell

switch ("fourteen")

1 {"It is one."; Break}

2 {"It is two."; Break}

3 {"It is three."; Break}

4 {"It is four."; Break}

"fo*" {"That's too many."}

By adding the default clause, you can perform an action when no other
conditions
succeed.

PowerShell

switch ("fourteen")

1 {"It is one."; Break}

2 {"It is two."; Break}

3 {"It is three."; Break}

4 {"It is four."; Break}

"fo*" {"That's too many."}

Default {

"No matches"

Output

No matches

For the word "fourteen" to match a case you must use the -Wildcard or
-Regex
parameter.

PowerShell

PS> switch -Wildcard ("fourteen")

1 {"It is one."; Break}

2 {"It is two."; Break}

3 {"It is three."; Break}

4 {"It is four."; Break}

"fo*" {"That's too many."}

Output

That's too many.

The following example uses the -Regex parameter.

PowerShell

$target = 'https://bing.com'

switch -Regex ($target)


{

'^ftp\://.*$' { "$_ is an ftp address"; Break }

'^\w+@\w+\.com|edu|org$' { "$_ is an email address"; Break }

'^(http[s]?)\://.*$' { "$_ is a web address that uses $($matches[1])";


Break }

Output

https://bing.com is a web address that uses https

The following example demonstrates the use of script blocks as switch


statement
conditions.

PowerShell

switch ("Test")

{$_ -is [String]} {

"Found a string"

"Test" {

"This $_ executes as well"

Output

Found a string

This Test executes as well

The following example processes an array containing two date values. The
<value-
scriptblock> compares the Year property of each date. The
<action-scriptblock>
displays a welcome message or the number of days until
the beginning of the year
2022.

PowerShell

switch ((Get-Date 1-Jan-2022), (Get-Date 25-Dec-2021)) {

{ $_.Year -eq 2021 } {

$days = ((Get-Date 1/1/2022) - $_).days

"There are $days days until 2022."

{ $_.Year -eq 2022 } { 'Welcome to 2022!' }

If the value matches multiple conditions, the action for each condition is
executed. To
change this behavior, use the break or continue keywords.

The break keyword stops processing and exits the switch statement.

The continue keyword stops processing the current value, but continues
processing any
subsequent values.

The following example processes an array of numbers and displays if they are
odd or
even. Negative numbers are skipped with the continue keyword. If a
non-number is
encountered, execution is terminated with the break keyword.
PowerShell

switch (1,4,-1,3,"Hello",2,1)

{$_ -lt 0} { continue }

{$_ -isnot [Int32]} { break }

{$_ % 2} {

"$_ is Odd"

{-not ($_ % 2)} {

"$_ is Even"

Output

1 is Odd

4 is Even

3 is Odd

See also
about_Break
about_Continue
about_If
about_Script_Blocks
about_Tab_Expansion
Article • 02/08/2023 • 2 minutes to read

Short description
PowerShell provides completions on input to provide hints, enable discovery, and
speed
up input entry. Command names, parameter names, argument values and file
paths can
all be completed by pressing the Tab key.

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

The Tab key is the default key binding on Windows. This keybinding
can be changed by
the PSReadLine module or the application that is hosting
PowerShell. The keybinding is
different on non-Windows platforms. For more
information, see
about_PSReadLine.

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

File and cmdlet name completion


To fill in a filename or path from the available choices automatically, type
part of the
name and press the Tab key. 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,
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, PowerShell replaces this with the only other matching
cmdlet name, Get-Content .

Tab completion also works to resolve PowerShell alias and native executables.

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:

Examples

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

PSReadLine also has a menu completion feature. The default key binding on
Windows is
Ctrl + Space .

PS> fore<Ctrl-Space>

When you press Ctrl + Space , PowerShell presents the full


list of matching values as a
menu:
PS> foreach

foreach ForEach-Object foreach.cmd

In this example the string 'fore' is matched to foreach (PowerShell alias),


ForEach-
Object (cmdlet), and foreach.cmd (native command). Use the arrow
keys to select the

value you want.

Parameter argument completion


Tab completion can also work to complete parameter arguments. This allows you
to use
the Tab key to cycle through a list of possible values that
are valid for some parameter.

For more information see,


about_Functions_Argument_Completion.

See also
about_Comment_Based_Help
about_Functions_Argument_Completion
about_Requires
about_Throw
Article • 09/19/2022 • 2 minutes to read

Short description
Describes the throw keyword that 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.

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:

PowerShell

throw [<expression>]

The expression in the throw syntax is optional. When the throw statement
doesn't
appear in a catch block, and it doesn't include an expression, it
generates a
ScriptHalted error.

PowerShell

throw

Output

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:

PowerShell

throw "This is an error."

Output

This is an error.

At line:1 char:6

+ throw <<<< "This is an error."


+ CategoryInfo : OperationStopped: (This is an error.:String) [], R

untimeException

+ 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:

PowerShell

throw (Get-Process pwsh)

Output

At line:1 char:6

+ throw <<<< (get-process PowerShell)

+ CategoryInfo : OperationStopped: (System.Diagnostics.Process (Pow

erShell):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.

PowerShell

$Error[0].TargetObject

Output

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 .NET exception. The


following example
uses the throw keyword to throw a
System.FormatException object.

PowerShell

$formatError = New-Object System.FormatException

throw $formatError

Output

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.

The 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
varies depending on the object
thrown.

The throw 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


Unlike past versions of PowerShell, don't use the throw keyword for parameter
validation. See
about_Functions_Advanced_Parameters
for the correct way.

See also
about_Break
about_Continue
about_Scopes
about_Trap
about_Try_Catch_Finally
about_Transactions
Article • 09/19/2022 • 15 minutes to read

Short description
Describes how to manage transacted operations in PowerShell.

Long description
Transactions are supported in PowerShell beginning in 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 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
PowerShell includes several cmdlets designed for managing transactions.

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:

PowerShell

get-command *transaction

For detailed information about the cmdlets, type:

PowerShell

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 PowerShell Registry provider supports transactions in Windows Vista. The


TransactedString object
(Microsoft.PowerShell.Commands.Management.TransactedString) works with any
operating system that runs PowerShell.

Other PowerShell providers can support transactions. To find the PowerShell


providers in
your session that support transactions, use the following command
to find the
"Transactions" value in the Capabilities property of providers:

PowerShell

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:


PowerShell

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:

PowerShell

get-help * -parameter UseTransaction

In PowerShell core, all of the cmdlets designed to work with PowerShell


providers
support transactions. As a result, you can use the provider cmdlets
to manage
transactions.

For more information about PowerShell providers, see about_Providers.

THE TRANSACTION OBJECT


Transactions are represented in 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 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, 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:

PowerShell

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

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

PowerShell

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.

PowerShell

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.

PowerShell

complete-transaction

As a result, the MyCompany key is added to the registry.

PowerShell

dir m*

Output

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.

PowerShell

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.

PowerShell

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.

PowerShell

Undo-transaction

The result is that the MyOtherCompany key is not added to the registry.

PowerShell

dir m*

Output

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.

PowerShell

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.

PowerShell

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

PowerShell

dir m*

The result shows that no entries have yet been added to the MyCompany key.

Output

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.

PowerShell

dir m* -useTransaction

The result shows that, if the transaction is committed, the MyKey entry will
be added to
the MyCompany key.

Output

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.

PowerShell

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.

PowerShell

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

PowerShell

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.

Output

Hive: HKEY_CURRENT_USER\Software

SKC VC Name Property

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

83 1 Microsoft {(default)}

0 0 MyCompany2 {}

The following command commits the transaction.

PowerShell
complete-transaction

Now, the keys that were added as part of the transaction appear in the
registry.

PowerShell

dir m*

Output

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.

PowerShell

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.

PowerShell

New-Item MyCompany -UseTX

Because the MyCompany key already exists in the registry, the command fails,
and the
transaction is rolled back.

Output

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.

Output

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

PowerShell

start-transaction -rollbackpreference Never

In this case, when the command fails, the transaction is not automatically
rolled back.

PowerShell

New-Item MyCompany -UseTX

Output

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

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.

PowerShell

start-transaction

The following New-Object command creates an instance of the TransactedString


class
and saves it in the $t variable.

PowerShell

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

PowerShell

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

PowerShell

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.

PowerShell

$t.tostring()

The output shows that only the non-transacted changes are effective.

Output

Windows

To see the current content of the transacted string in $t from within the
transaction,
embed the expression in a Use-Transaction command.

PowerShell

use-transaction {$s.tostring()} -usetx

The output shows the transaction view.

Output

PowerShell

The following command commits the transaction.

PowerShell

complete-transaction

To see the final string:

$t.tostring()

PowerShell

EXAMPLE 8: MANAGING MULTI-SUBSCRIBER


TRANSACTIONS
When you start a transaction while another transaction is in progress,
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.

PowerShell

start-transaction

The following command uses the Get-Transaction command to get the active
transaction.

PowerShell

get-transaction

The result shows the object that represents the active transaction.

Output

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.

PowerShell

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.

PowerShell

start-transaction

A Get-Transaction command shows that the subscriber count on the transaction


object
is incremented. The value is now 2.
Output

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.

PowerShell

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.

PowerShell

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

Output

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.

PowerShell

complete-transaction

Another Get-Transaction command shows that the transaction has been committed.

Output
RollbackPreference SubscriberCount Status

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

Error 0 Committed

EXAMPLE 9: 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.

PowerShell

start-transaction

The following command uses the Get-Transaction command to get the active
transaction.

PowerShell

get-transaction

The result shows the object that represents the active transaction.

Output

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.

PowerShell

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.

PowerShell

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.

PowerShell

get-transaction

Note that the SubscriberCount of the transaction is 1, indicating that there


are no other
subscribers and that the transaction is new.

Output

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.

PowerShell

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.

PowerShell

undo-transaction

A Get-Transaction command confirms that the original transaction is still


active in the
session.

PowerShell

get-transaction

Output

RollbackPreference SubscriberCount Status

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

Error 1 Active

The following command commits the active transaction.

PowerShell

complete-transaction

A Get-ChildItem command shows that the registry has been changed.

PowerShell

dir m*

Output

Hive: HKEY_CURRENT_USER\Software

SKC VC Name Property

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

83 1 Microsoft {(default)}

0 0 MyCompany {}

See also
about_Providers
Get-ChildItem
Get-PSProvider
Complete-Transaction
Get-Transaction
Start-Transaction
Undo-Transaction
Use-Transaction
about_Trap
Article • 09/19/2022 • 9 minutes to read

Short description
Describes a keyword that handles a terminating error.

Long description
A terminating error stops a statement from running. If PowerShell does not
handle a
terminating error in some way, PowerShell also stops running the
function or script in
the current pipeline. In other languages, such as C#,
terminating errors are known as
exceptions.

The trap keyword specifies a list of statements to run when a terminating


error occurs.
trap statements can handle the terminating errors in the
following ways:

Display the error after processing the trap statement block and continuing
execution of the script or function containing the trap . This is the
default
behavior.

7 Note

When the terminating error occurs in a subordinate script block, such as


an
if statement or foreach loop, the statements in the trap block are
run and
execution continues at the next statement outside the subordinate
script
block.

Display the error and abort execution of the script or function containing
the trap
using break in the trap statement.

Silence the error, but continue execution of the script or function


containing the
trap by using continue in the trap statement.

The statement list of the trap can include multiple conditions or function
calls. A trap
can write logs, test conditions, or even run another program.

Syntax
The trap statement has the following syntax:

PowerShell

trap [[<error type>]] {<statement list>}

The trap statement includes a list of statements to run when a terminating


error occurs.
A trap statement consists of the trap keyword, optionally
followed by a type
expression, and the statement block containing the list of
statements to run when an
error is trapped. The type expression refines the
types of errors the trap catches.

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, PowerShell checks for a trap statement that handles the error. If
a trap
statement is present, PowerShell continues running the script or
command in the trap
statement.

The following example is a very simple trap statement:

PowerShell

trap {"Error found."}

This trap statement traps any terminating error.

In the following example, the function includes a nonsense string that causes
a runtime
error.

PowerShell

function TrapTest {

trap {"Error found."}

nonsenseString

TrapTest

Running this function returns the following:

Output
Error found.

nonsenseString : 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 try again.

At line:3 char:5

+ nonsenseString

+ ~~~~~~~~~~~~~~

+ CategoryInfo : ObjectNotFound: (nonsenseString:String) [],


CommandNotFoundException

+ FullyQualifiedErrorId : CommandNotFoundException

The following example includes a trap statement that displays the error by
using the $_
automatic variable:

PowerShell

function TrapTest {

trap {"Error found: $_"}

nonsenseString

TrapTest

Running this version of the function returns the following:

Output

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

nonsenseString : 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 try again.

At line:3 char:5

+ nonsenseString

+ ~~~~~~~~~~~~~~

+ CategoryInfo : ObjectNotFound: (nonsenseString:String) [],


CommandNotFoundException

+ FullyQualifiedErrorId : CommandNotFoundException

) Important

trap statements may be defined anywhere within a given script block, but
always

apply to all statements in that script block. At runtime, trap


statements in a block
are defined before any other statements are executed.
In JavaScript, this is known
as
hoisting . This means
that trap statements apply to all statements in that
block even if
execution has not advanced past the point at which they are defined.
For
example, defining a trap at the end of a script and throwing an error in
the first
statement still triggers that trap .

Trapping specific errors


A script or command can have multiple trap statements. A trap can be
defined to
handle specific errors.

The following example is a trap statement that traps the specific error
CommandNotFoundException:

PowerShell

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 the
trap statement list, PowerShell writes the error object to
the error stream and then

continues the script.

PowerShell uses .NET exception types. The following example specifies the
System.Exception error type:

PowerShell

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 type can be
trapped
by only one trap statement. When a terminating error occurs,
PowerShell searches for
the trap with the most specific match, starting in
the current script block of execution.

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.

PowerShell

trap {"Other terminating error trapped" }

trap [System.Management.Automation.CommandNotFoundException] {

"Command error trapped"

nonsenseString

Running this script produces the following result:

Output

Command error trapped

nonsenseString : 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 try again.

At C:\Temp\traptest.ps1:5 char:1

+ nonsenseString

+ ~~~~~~~~~~~~~~

+ CategoryInfo : ObjectNotFound: (nonsenseString:String) [],


CommandNotFoundException

+ FullyQualifiedErrorId : CommandNotFoundException

Because 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:

PowerShell

trap {"Other terminating error trapped" }

trap [System.Management.Automation.CommandNotFoundException]

{"Command error trapped"}

1/$null

Running this script produces the following result:

Output

Attempted to divide by zero.

At C:\temp\traptest.ps1:4 char:1

+ 1/$null

+ ~~~~~~~

+ CategoryInfo : NotSpecified: (:) [], RuntimeException

+ FullyQualifiedErrorId : RuntimeException

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 in a script block


By default, when a terminating error is thrown, execution transfers to the trap
statement.
After the trap block is run, control returns to the next statement
block after the location
of the error.

For example, when a terminating error occurs in an foreach statement, the trap
statement is run and execution continues at the next statement after the foreach block,
not within the foreach block.

PowerShell

trap { 'An error occurred!'}

foreach ($x in 3..0) {

1/$x

'after division'

'after loop'

Output

0.333333333333333

after division

0.5

after division

after division

An error occurred!

Attempted to divide by zero.

At line:3 char:4

+ 1/$x

+ ~~~~

+ CategoryInfo : NotSpecified: (:) [], RuntimeException

+ FullyQualifiedErrorId : RuntimeException

after loop

In the output above, you can see the loops continue until the last iteration.
When the
script tries to divide 1 by 0 a terminating error is thrown. The rest
of the foreach
scriptblock is skipped, the try statement is run, and the
script continues after the
foreach scriptblock.

Trapping errors and scope


If a terminating error occurs in the same script block as the trap statement,
PowerShell
runs the list of statements defined by the trap . Execution
continues at the statement
after the error. If the trap statement is in a
different script block from the error,
execution continues at the next
statement that is in the same script block as the trap
statement.

For example, if an error occurs in a function, and the trap statement is in


the function,
the script continues at the next statement. The following script
contains an error and a
trap statement:

PowerShell

function function1 {

trap { "An error: " }

NonsenseString

"function1 was completed"

function1

Running this script produces the following result:

Output

An error:

NonsenseString : 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 try again.

At line:3 char:5

+ NonsenseString

+ ~~~~~~~~~~~~~~

+ CategoryInfo : ObjectNotFound: (NonsenseString:String) [],


CommandNotFoundException

+ FullyQualifiedErrorId : CommandNotFoundException

function1 was completed

The trap statement in the function traps the error. After displaying the
message,
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:

PowerShell

function function2 {

NonsenseString

"function2 was completed"

trap { "An error: " }

function2

Running the Function2 function produces the following result:

Output

An error:

NonsenseString : 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 try again.

At C:\temp\traptest.ps1:2 char:5

+ NonsenseString

+ ~~~~~~~~~~~~~~

+ CategoryInfo : ObjectNotFound: (NonsenseString:String) [],


CommandNotFoundException

+ FullyQualifiedErrorId : CommandNotFoundException

In this example, the "function2 was completed" command was not run. In both
examples, the terminating error occurs within the function. In this example,
however, the
trap statement is outside the function. PowerShell does not go
back into the function
after the trap statement runs.

U Caution

When multiple traps are defined for the same error condition, the first trap
defined
lexically (highest in the script block) is used.

In the following example, only the trap with "whoops 1" is run.

PowerShell

Remove-Item -ErrorAction Stop ThisFileDoesNotExist

trap { "whoops 1"; continue }

trap { "whoops 2"; continue }

) Important

A Trap statement is scoped to where it compiles. If you have a


trap statement
inside a function or dot sourced script, when the function
or dot sourced script
exits, all trap statements inside are removed.

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, PowerShell stops


the function
or script. The following sample function uses the break keyword
in a trap statement:

PowerShell

function break_example {

trap {

"Error trapped"

break

1/$null

"Function completed."

break_example

Output

Error trapped

Attempted to divide by zero.

At line:6 char:5

+ 1/$null

+ ~~~~~~~

+ CategoryInfo : NotSpecified: (:) [],


ParentContainsErrorRecordException

+ FullyQualifiedErrorId : RuntimeException

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 keyword in a trap statement, PowerShell resumes
after the
statement that caused the error, just as it would without break or
continue . With the
continue keyword, however, PowerShell does not write an
error to the error stream.

The following sample function uses the continue keyword in a trap


statement:

PowerShell

function continue_example {

trap {

"Error trapped"

continue

1/$null

"Function completed."

continue_example

Output

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.

Notes
trap statements provide a way to ensure all terminating errors within a
script block are
handled. For more finer-grained error handling, use
try / catch blocks where traps are
defined using catch statements. The
catch statements only apply to the code inside the
associated try
statement. For more information, see
about_Try_Catch_Finally.

See also
about_Break
about_Continue
about_Scopes
about_Throw
about_Try_Catch_Finally
about_Try_Catch_Finally
Article • 09/19/2022 • 6 minutes to read

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 PowerShell does not


handle a
terminating error in some way, 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.

Use the try block to define a section of a script in which you want
PowerShell to
monitor for errors. When an error occurs within the try block,
the error is first saved to
the $Error automatic variable. PowerShell then
searches for a catch block to handle the
error. If the try statement does
not have a matching catch block, 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 error 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:

PowerShell

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:

PowerShell

catch [[<error type>][',' <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, 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:

PowerShell

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:

PowerShell

try { NonsenseString }

catch { "An error occurred." }

The catch keyword must immediately follow the try block or another catch
block.

PowerShell does not recognize "NonsenseString" as a cmdlet or other item.


Running this
script returns the following result:

PowerShell

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 MyDoc.doc , and it contains
two catch blocks:

PowerShell

try {

$wc = new-object System.Net.WebClient

$wc.DownloadFile("http://www.contoso.com/MyDoc.doc","c:\temp\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.

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:

PowerShell

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:

PowerShell

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.

7 Note

PowerShell wraps all exceptions in a RuntimeException type. Therefore,


specifying
the error type System.Management.Automation.RuntimeException
behaves the
same as an unqualified catch block.

Using Traps in a Try Catch


When a terminating error occurs in a try block with a Trap defined within
the try
block, even if there is a matching catch block, the Trap statement
takes control.

If a Trap exists at a higher block than the try , and there is no matching
catch block
within the current scope, the Trap will take control, even if
any parent scope has a
matching catch block.

Accessing exception information


Within a catch block, the current error can be accessed using $_ , which
is also known
as $PSItem . The object is of type ErrorRecord.

PowerShell

try { NonsenseString }

catch {

Write-Host "An error occurred:"

Write-Host $_

Running this script returns the following result:

Output

An Error occurred:

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

There are additional properties that can be accessed, such as ScriptStackTrace,


Exception, and ErrorDetails. For example, if we change the script to the
following:

PowerShell

try { NonsenseString }

catch {

Write-Host "An error occurred:"

Write-Host $_.ScriptStackTrace

The result will be similar to:


An Error occurred:

at <ScriptBlock>, <No file>: line 2

Freeing resources 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. 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_Break
about_Continue
about_Scopes
about_Throw
about_Trap
about_Types.ps1xml
Article • 09/19/2022 • 10 minutes to read

Short description
Explains how to use Types.ps1xml files to extend the types of objects that
are used in
PowerShell.

Long description
Extended type data defines additional properties and methods ("members") of
object
types in PowerShell. There are two techniques for adding extended type
data to a
PowerShell session.

Types.ps1xml file: An XML file that defines extended type data.


Update-TypeData : A cmdlet that reloads Types.ps1xml files and defines
extended

data for types in the current session.

This topic describes Types.ps1xml files. For more information about using the
Update-
TypeData cmdlet to add dynamic extended type data to the current
session see
Update-

TypeData.

About extended type data


Extended type data defines additional properties and methods ("members") of
object
types in PowerShell. You can extend any type that is supported by
PowerShell and use
the added properties and methods in the same way that you
use the properties that are
defined on the object types.

For example, PowerShell adds a DateTime property to all System.DateTime


objects, such
as the ones that the Get-Date cmdlet returns.

PowerShell

(Get-Date).DateTime

Output

Sunday, January 29, 2012 9:43:57 AM

You won't find the DateTime property in the description of the


System.DateTime
structure, because PowerShell
adds the property and it is visible only in PowerShell.

PowerShell internally defines a default set of extended types. This type


information is
loaded in every PowerShell session at startup. The DateTime
property is part of this
default set. Prior to PowerShell 6, the type
definitions were stored the Types.ps1xml file
in the PowerShell installation
directory ( $PSHOME ).

Adding extended type data to PowerShell


There are three sources of extended type data in PowerShell sessions.

Extended type data is defined by PowerShell and loaded automatically into


every
PowerShell session.

The Types.ps1xml files that modules export are loaded when the module
is
imported into the current session.

Extended type data that is defined by using the Update-TypeData cmdlet


is added
only to the current session. It is not saved in a file.

In the session, the extended type data from the three sources is applied
to objects in the
same way and is available on all objects of the specified
types.

The TypeData cmdlets


The following cmdlets are included in the Microsoft.PowerShell.Utility
module in
PowerShell 3.0 and later.

Get-TypeData : Gets extended type data in the current session.

Update-TypeData : Reloads Types.ps1xml files. Adds extended type data to


the
current session.
Remove-TypeData : Removes extended type data from the current session.

For more information about these cmdlets, see the help topic for each cmdlet.

Built-in Types.ps1xml files


The Types.ps1xml files in the $PSHOME directory are added automatically to
every
session.
The Types.ps1xml file in the PowerShell installation directory ( $PSHOME ) is
an XML-based
text file that lets you add properties and methods to the objects
that are used in
PowerShell. PowerShell has built-in Types.ps1xml files that
add several elements to the
.NET 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, PowerShell adds an alias
property named Count that displays the
same value. The following XML adds
the Count property to the System.Array type.

XML

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

PowerShell

Get-Member -InputObject (1,2,3,4)

The command returns the following results.

Output

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
PowerShell. For example:

PowerShell

(1, 2, 3, 4).count

PowerShell

(1, 2, 3, 4).length

Creating new Types.ps1xml files


The .ps1xml files that are installed with PowerShell are
digitally signed to prevent
tampering because the formatting can include
script blocks. Therefore, to add a
property or method to a .NET
type, create your own Types.ps1xml files, and then add
them to your
PowerShell session.

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 PowerShell, but
it is useful to place the files in the
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 PowerShell session. If you want your types to take precedence
over the built-in
types that are defined, use the PrependData parameter of
the Update-TypeData cmdlet.
Update-TypeData affects only the current
session. To make the change to all future
sessions, export the console, or add
the Update-TypeData command to your 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 type in the affected PowerShell session. 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 System.IO.FileInfo
objects. The age
of a file is the difference between its creation time and the
current time in days.

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.

Save the follow XML code to the file $PSHOME\MyTypes.ps1xml .

XML

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

Run Update-TypeData to add the new Types.ps1xml file to the current


session. The
command uses the PrependData parameter to place the new file
in a precedence order
higher than the original definitions.

For more information about Update-TypeData , see


Update-TypeData.

PowerShell

Update-Typedata -PrependPath $PSHOME\MyTypes.ps1xml

To test the change, run 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.

PowerShell

Get-ChildItem $PSHOME\pwsh.exe | Select-Object Age

Output

142

The XML in Types.ps1xml files


The full schema definition can be found in
Types.xsd
in the PowerShell source code
repository on GitHub.

The <Types> tag encloses all of the types that are defined in the file. There
should be
only one <Types> tag.

Each .NET type mentioned in the file should be represented by a <Type> tag.

The type tags must contain the following tags:

<Name> : Encloses the name of the affected .NET


type.

<Members> : Encloses the tags for the new properties and methods that are
defined for
the .NET type.

Any of the following member tags can be inside the <Members> tag.

AliasProperty
Defines a new name for an existing property.

The <AliasProperty> tag must have a <Name> tag that specifies the name of
the new
property and a <ReferencedMemberName> tag that specifies the existing
property.

For example, the Count alias property is an alias for the Length
property of array
objects.

XML

<Type>

<Name>System.Array</Name>

<Members>

<AliasProperty>

<Name>Count</Name>

<ReferencedMemberName>Length</ReferencedMemberName>

</AliasProperty>

</Members>

</Type>

CodeMethod
References a static method of a .NET class.

The <CodeMethod> tag must have a <Name> tag that specifies the name of the
new
method and a <CodeReference> tag that specifies the code in which the
method is
defined.

For example, the ToString method is the name of the


Microsoft.PowerShell.ToStringCodeMethods code definition.

XML

<Type>

<Name>System.Xml.XmlNode</Name>

<Members>

<CodeMethod>

<Name>ToString</Name>

<CodeReference>

<TypeName>Microsoft.PowerShell.ToStringCodeMethods</TypeName>

<MethodName>XmlNode</MethodName>

</CodeReference>

</CodeMethod>

</Members>

</Type>

CodeProperty
References a static method of a .NET class.

The <CodeProperty> tag must have a <Name> tag that specifies the name of
the new
property and a <GetCodeReference> tag that specifies the code in
which the property is
defined.

For example, the Mode property of System.IO.DirectoryInfo objects is a


code property
defined in the PowerShell FileSystem provider.

XML

<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 <Name> tag surrounding the name of the member set and
a secondary <Members> tag
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
objects in 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.

XML

<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 <Name> tag that specifies the name of
the new
property and a <Value> tag that specifies the value of the property.

For example, the following XML creates a Status property for


System.IO.DirectoryInfo
objects. The value of the Status property is
always Success.

XML

<Type>

<Name>System.IO.DirectoryInfo</Name>

<Members>

<NoteProperty>

<Name>Status</Name>

<Value>Success</Value>

</NoteProperty>

</Members>

</Type>

PropertySet
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 <Name> tag that specifies the name
of the property
set and a <ReferencedProperty> tag that specifies the
properties. The names of the
properties are enclosed in <Name> tag.

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 PropertySet named


DefaultDisplayPropertySet with three ReferencedProperties.

XML

<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 <Name> tag that specifies the
name of the new
method and a <Script> tag that encloses 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.

XML
<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 <Name> tag that specifies the
name of the new
property and a <GetScriptBlock> tag that encloses the
script block that returns the
property value.

For example, the VersionInfo property of the System.IO.FileInfo object


is a script
property that results from using the FullName property of the
GetVersionInfo static
method of System.Diagnostics.FileVersionInfo
objects.

XML

<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).
Update-TypeData
To load your Types.ps1xml files into a PowerShell session, run the
Update-TypeData
cmdlet. If you want the types in your file to take precedence
over types in the built-in
Types.ps1xml file, add the PrependData
parameter of Update-TypeData . Update-
TypeData affects only the current
session. To make the change to all future sessions,

export the session, or add


the Update-TypeData command to your PowerShell profile.

Exceptions that occur in properties, or from adding properties to an


Update-TypeData
command, do not report errors to StdErr . This is to
suppress exceptions that would
occur in many common types during formatting and
outputting. If you are getting .NET
properties, you can work around the
suppression of exceptions by using method syntax
instead, as shown in the
following example:

PowerShell

"hello".get_Length()

Note that method syntax can only be used with .NET properties. Properties that
are
added by running the Update-TypeData cmdlet cannot use method syntax.

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
Copy-ItemProperty
Get-Member
Get-TypeData
Remove-TypeData
Update-TypeData
about_Type_Accelerators
Article • 09/19/2022 • 2 minutes to read

SHORT DESRIPTION
Describes the Type accelerators available for .NET framework classes

Long description
Type accelerators are aliases for .NET framework classes. They allow you to
access specific
.NET framework classes without having to explicitly type the
entire class name. For
example, you can shorten the AliasAttribute
class from
[System.Management.Automation.AliasAttribute] to [Alias] .

7 Note

All type accelerators still need to be wrapped in square brackets( [] ).

Available Type Accelerators


Accelerator Full Class Name

adsi System.DirectoryServices.DirectoryEntry

adsisearcher System.DirectoryServices.DirectorySearcher

Alias System.Management.Automation.AliasAttribute

AllowEmptyCollection System.Management.Automation.AllowEmptyCollectionAttribute

AllowEmptyString System.Management.Automation.AllowEmptyStringAttribute

AllowNull System.Management.Automation.AllowNullAttribute

ArgumentCompleter System.Management.Automation.ArgumentCompleterAttribute

array System.Array

bigint System.Numerics.BigInteger

bool System.Boolean

byte System.Byte
Accelerator Full Class Name

char System.Char

cimclass Microsoft.Management.Infrastructure.CimClass

cimconverter Microsoft.Management.Infrastructure.CimConverter

ciminstance Microsoft.Management.Infrastructure.CimInstance

CimSession Microsoft.Management.Infrastructure.CimSession

cimtype Microsoft.Management.Infrastructure.CimType

CmdletBinding System.Management.Automation.CmdletBindingAttribute

cultureinfo System.Globalization.CultureInfo

datetime System.DateTime

decimal System.Decimal

double System.Double

DscLocalConfigurationManager System.Management.Automation.DscLocalConfigurationManagerAttribute

DscProperty System.Management.Automation.DscPropertyAttribute

DscResource System.Management.Automation.DscResourceAttribute

float System.Single

guid System.Guid

hashtable System.Collections.Hashtable

initialsessionstate System.Management.Automation.Runspaces.InitialSessionState

int System.Int32

int16 System.Int16

int32 System.Int32

int64 System.Int64

ipaddress System.Net.IPAddress

IPEndpoint System.Net.IPEndPoint

long System.Int64

mailaddress System.Net.Mail.MailAddress

NullString System.Management.Automation.Language.NullString
Accelerator Full Class Name

ObjectSecurity System.Security.AccessControl.ObjectSecurity

OutputType System.Management.Automation.OutputTypeAttribute

Parameter System.Management.Automation.ParameterAttribute

PhysicalAddress System.Net.NetworkInformation.PhysicalAddress

powershell System.Management.Automation.PowerShell

psaliasproperty System.Management.Automation.PSAliasProperty

pscredential System.Management.Automation.PSCredential

pscustomobject System.Management.Automation.PSObject

PSDefaultValue System.Management.Automation.PSDefaultValueAttribute

pslistmodifier System.Management.Automation.PSListModifier

psmoduleinfo System.Management.Automation.PSModuleInfo

psnoteproperty System.Management.Automation.PSNoteProperty

psobject System.Management.Automation.PSObject

psprimitivedictionary System.Management.Automation.PSPrimitiveDictionary

psscriptmethod System.Management.Automation.PSScriptMethod

psscriptproperty System.Management.Automation.PSScriptProperty

PSTypeNameAttribute System.Management.Automation.PSTypeNameAttribute

psvariable System.Management.Automation.PSVariable

psvariableproperty System.Management.Automation.PSVariableProperty

ref System.Management.Automation.PSReference

regex System.Text.RegularExpressions.Regex

runspace System.Management.Automation.Runspaces.Runspace

runspacefactory System.Management.Automation.Runspaces.RunspaceFactory

sbyte System.SByte

scriptblock System.Management.Automation.ScriptBlock

securestring System.Security.SecureString

single System.Single
Accelerator Full Class Name

string System.String

SupportsWildcards System.Management.Automation.SupportsWildcardsAttribute

switch System.Management.Automation.SwitchParameter

timespan System.TimeSpan

type System.Type

uint16 System.UInt16

uint32 System.UInt32

uint64 System.UInt64

uri System.Uri

ValidateCount System.Management.Automation.ValidateCountAttribute

ValidateDrive System.Management.Automation.ValidateDriveAttribute

ValidateLength System.Management.Automation.ValidateLengthAttribute

ValidateNotNull System.Management.Automation.ValidateNotNullAttribute

ValidateNotNullOrEmpty System.Management.Automation.ValidateNotNullOrEmptyAttribute

ValidatePattern System.Management.Automation.ValidatePatternAttribute

ValidateRange System.Management.Automation.ValidateRangeAttribute

ValidateScript System.Management.Automation.ValidateScriptAttribute

ValidateSet System.Management.Automation.ValidateSetAttribute

ValidateTrustedData System.Management.Automation.ValidateTrustedDataAttribute

ValidateUserDrive System.Management.Automation.ValidateUserDriveAttribute

version System.Version

void System.Void

WildcardPattern System.Management.Automation.WildcardPattern

wmi System.Management.ManagementObject

wmiclass System.Management.ManagementClass

wmisearcher System.Management.ManagementObjectSearcher

X500DistinguishedName System.Security.Cryptography.X509Certificates.X500DistinguishedName
Accelerator Full Class Name

X509Certificate System.Security.Cryptography.X509Certificates.X509Certificate

xml System.Xml.XmlDocument
about_Type_Operators
Article • 10/11/2022 • 4 minutes to read

Short description
Describes the operators that work with Microsoft .NET types.

Long description
The Boolean type operators ( -is and -isnot ) tell whether an object is an
instance of a
specified .NET 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
type. If it
succeeds, it returns the converted object. If it fails, it returns
$null . It does not return an
error.

PowerShell has the following type operators:

-is |Returns TRUE when the input is an instance of the specified .NET type.

PowerShell

(get-date) -is [DateTime] # Result is True

-isnot |Returns TRUE when the input not an instance of the specified.NET type.

PowerShell

(get-date) -isnot [DateTime] # Result is False

-as |Converts the input to the specified .NET type.

PowerShell

"5/7/07" -as [DateTime] # Result is Monday, May 7, 2007 12:00:00


AM

The syntax of the type operators is as follows:


PowerShell

<input> <operator> [.NET type]

You can also use the following syntax:

PowerShell

<input> <operator> ".NET type"

The .NET type can be written as a type name in brackets or 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 operate on the input object as a whole. That is, if
the input
object is a collection, it is the collection type that is tested,
not the types of the
collection's elements.

-is/isnot operators
The Boolean type operators ( -is and -isnot ) always return a Boolean
value, even if the
input is a collection of objects.

If <input> is a type that is the same as or is derived from the .NET Type,
the -is
operator returns $True .

For example, the DirectoryInfo type is derived from the FileSystemInfo


type. Therefore,
both of these examples return True.

PowerShell

PS> (Get-Item /) -is [System.IO.DirectoryInfo]

True

PS> (Get-Item /) -is [System.IO.FileSystemInfo]

True

The -is operator can also match interfaces if the <input> implements the
interface in
the comparison. In this example, the input is an array. Arrays
implement the
System.Collections.IList interface.

PowerShell
PS> 1, 2 -is [System.Collections.IList]

True

-as operator
The -as operator tries to convert the input object to the specified .NET
type. If it
succeeds, it returns the converted object. It if fails, it returns
$null . It does not return an
error.

If the <input> is a type that is derived from the .NET Type -as passes
through returns
input object unchanged. For example, the DirectoryInfo
type is derived from the
FileSystemInfo type. Therefore, the object type is
unchanged in the following example:

PowerShell

PS> $fsroot = (Get-Item /) -as [System.IO.FileSystemInfo]

PS> $fsroot.GetType().FullName

System.IO.DirectoryInfo

Converting the DateTime type is culture-sensitive

Unlike type casting, converting to [DateTime] type using the -as operator
only works
with strings that are formatted according to the rules of the
current culture.

PowerShell

PS> [cultureinfo]::CurrentCulture = 'fr-FR'

PS> '13/5/20' -as [datetime]

mercredi 13 mai 2020 00:00:00

PS> '05/13/20' -as [datetime]

PS> [datetime]'05/13/20'

mercredi 13 mai 2020 00:00:00

PS> [datetime]'13/05/20'

InvalidArgument: Cannot convert value "13/05/20" to type "System.DateTime".

Error: "String '13/05/20' was not recognized as a valid DateTime."

To find the .NET 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:
PowerShell

PS> (Get-Culture).GetType().FullName

System.Globalization.CultureInfo

Examples
The following examples show some uses of the Type operators:

PowerShell

PS> 32 -is [Float]

False

PS> 32 -is "int"

True

PS> (get-date) -is [DateTime]

True

PS> "12/31/2007" -is [DateTime]

False

PS> "12/31/2007" -is [String]

True

PS> (get-process PowerShell)[0] -is [System.Diagnostics.Process]

True

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

PowerShell

PS> (get-culture) -is [System.Globalization.CultureInfo]


True

PS> (get-uiculture) -is [System.Globalization.CultureInfo]

True

PS> (get-culture), (get-uiculture) -is [System.Globalization.CultureInfo]

False

PS> (get-culture), (get-uiculture) -is [Array]

True

PS> (get-culture), (get-uiculture) | foreach {

$_ -is [System.Globalization.CultureInfo])

True

True

PS> (get-culture), (get-uiculture) -is [Object]

True

The following examples show how to use the -as operator.

PowerShell

PS> "12/31/07" -is [DateTime]

False

PS> "12/31/07" -as [DateTime]

Monday, December 31, 2007 12:00:00 AM

PS> $date = "12/31/07" -as [DateTime]

C:\PS>$a -is [DateTime]


True

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 type, it returns $null .

PowerShell

PS> 1031 -as [System.Diagnostics.Process]

PS>

See also
about_Operators
about_Updatable_Help
Article • 11/15/2022 • 12 minutes to read

Short description
Describes the updatable help system in PowerShell.

Long description
PowerShell provides several different ways to access the most up-to-date help
topics for
PowerShell cmdlets and concepts.

The Updatable Help system, introduced in PowerShell 3.0, is designed to assure


that you
always have the newest help topics on your local computer so that you
can read them at
the command line. It makes it easy to download and install
help files and to update
them whenever newer help files become available.

To provide updated help for multiple computers in an enterprise and for


computers that
do not have access to the internet, Updatable Help lets you
download help files to a
filesystem directory or file share, and then install
the help files from the file share.

In PowerShell 4.0, the HelpInfoUri property is preserved over Windows


PowerShell
remoting, which allows Save-Help to work for modules that are
installed on a remote
computer, but are not necessarily installed on the local
computer. You can save a
PSModuleInfo object to disk or removable media
(such as a USB drive) by running
Export-Clixml on a computer that does not
have internet access, importing the

PSModuleInfo object on a computer that


does have internet access, and then running
Save-Help on the PSModuleInfo
object. The saved help can be copied to the remote,

disconnected computer by
using removable media, and then installed by running
Update-Help . These
improvements in Save-Help functionality let you install help on

computers
that are without any kind of network access. For an example of how to use
the
new Save-Help functionality, see
How to update help from a file share
in this topic.

Updatable Help also supports online access to the newest help topics and basic
help for
cmdlets, even when there are no help files on the computer.

PowerShell 3.0 does not come with Help files. You can use the Updatable Help
feature to
install the help files for all of the commands that are included by
default in PowerShell
and for all Windows modules.
Updatable help cmdlets
Update-Help : Downloads the newest help files from the internet or a file
share, and

installs them on the local computer.

Save-Help : Downloads the newest help files from the internet and saves them
in a
filesystem directory or file share. To install the help files on
computers, use Update-
Help .

Get-Help : Displays help topics at the command line. Gets help from the help
files

on the computer. Displays auto-generated help for cmdlets and functions


that do
not have help files. Opens online help topics for cmdlets, functions,
scripts, and
workflows in your default internet browser.

Update help in the PowerShell ISE


You can also update help by using the Update PowerShell Help item in the
Help menu
in PowerShell Integrated Scripting Environment (ISE).

The Update PowerShell Help item runs an Update-Help command without


parameters.

Auto-generated help: help without help files


If you do not have the help file for a cmdlet, function, or workflow on the
computer, the
Get-Help cmdlet displays auto-generated help and prompts you to
download the help

files or read them online.

Auto-generated help includes syntax and aliases, and remarks that explain how
to use
the Updatable Help cmdlets and to access the online help topics.

For example, the following command gets basic help for the Get-Culture
cmdlet. The
output shows the Get-Help display when there are no help files on
the computer.

PowerShell

Get-Help Get-Culture

Output

NAME

Get-Culture

SYNTAX

Get-Culture [<CommonParameters>]

ALIASES

None

REMARKS

To get the latest Help content including descriptions and examples

type: Update-Help.

Help files for modules


The smallest unit of Updatable Help is help for a module. Module help includes
help for
all of the cmdlets, functions, workflows, providers, scripts, and
concepts in a module. You
can update help for all modules that are installed on
the computer, even if they are not
imported into the current session.

You can update help for the entire module, but you cannot update help for
individual
cmdlets.

To find the module that contains a particular cmdlet, use the following command
format:

PowerShell

(Get-Command <cmdlet-name>).ModuleName

For example, to find the module that contains the Set-ExecutionPolicy


cmdlet, type:

PowerShell

(Get-Command Set-ExecutionPolicy).ModuleName

To update help for a particular module, type:

PowerShell

Update-Help -Module <ModuleName>

For example, to update help for the module that contains the
Set-ExecutionPolicy
cmdlet, type:

PowerShell
Update-Help -Module Microsoft.PowerShell.Security

Permissions for updatable help


To update help for the modules in the directory $pshome/Modules , you must be
member
of the Administrators group on the computer.

If you are not a member of the Administrators group, you cannot update help for
these
modules; but if you have internet access, you can view help online.

Updating help for modules in the directory $HOME/Documents/PowerShell/Modules


or
modules in other subdirectories of the $HOME directory does not require
special
permissions.

The Update-Help and Save-Help cmdlets have a UseDefaultCredentials


parameter that
provides the explicit credentials of the current user. This
parameter is designed for
accessing secure internet locations.

The Update-Help and Save-Help cmdlets also have a Credential parameter


that allows
you to run the command on a remote computer and access a file share
on a third
computer. The Credential parameter is valid only when you use
the SourcePath or
LiteralPath parameters of Update-Help and the
DestinationPath or LiteralPath
parameters of Save-Help .

How to install and update help files


To download and install help files for the first time, or to update the help
files on your
computer, use the Update-Help cmdlet.

The Update-Help cmdlet does all of the hard work for you, including the
following tasks.

Determines which modules support Updatable Help.


Finds the internet location where each module stores its Updatable Help
files.
Compares the help files for each module on your computer to the newest help
files
that are available for each module.
Downloads the new files from the internet.
Unwraps the help file package.
Verifies that the files are valid help files.
Installs the help files in the language-specific subdirectory of the module
directory.
To access the new help topics, use the Get-Help cmdlet. You do not need to
restart
PowerShell.

To install or update help for all modules on the computer that supports
Updatable Help,
type:

PowerShell

Update-Help

To update help for particular modules, add the Module parameter of


Update-Help .
Wildcard characters are permitted in the module name.

For example, to update help for the ServerManager module, type:

PowerShell

Update-Help -Module ServerManager

Without parameters, Update-Help updates help for all modules in the session
and for all
installed modules that support Updatable Help. To be included,
modules must be
installed in directories that are listed in the value of the
PSModulePath environment
variable. These are also modules that are returned by
a "Get-Help -ListAvailable"
command.

If the value of the Module parameter is * (all), Update-Help attempts


to update help for
all installed modules, including modules that do not support
Updatable Help. This
command typically generates many errors as the cmdlet
encounters modules that do
not support Updatable Help.

How to update help from a file share


To support computers that are not connected to the internet, or to control or
streamline
help updating in an enterprise, use the Save-Help cmdlet. The
Save-Help cmdlet
downloads help files from the internet and saves them in a
filesystem directory that you
specify.

Save-Help compares the help files in the specified directory to the newest
help files that

are available for each module. If the directory has no help


files or newer help files are
available for the module, the Save-Help cmdlet
downloads the new files from the
internet. However, it does not unwrap or
install the help files.
To install or update the help files on a computer from help files that were
saved to a
filesystem directory, use the SourcePath parameter of the
Update-Help cmdlet. The
Update-Help cmdlet identifies the newest help
files, unwraps and validates them, and

installs them in the language-specific


subdirectories of the module directories.

For example, to save help for all installed modules to the \\Server\Share
directory, type:

PowerShell

Save-Help -DestinationPath \\Server\Share

Then, to update help from the \\Server\Share directory, type:

PowerShell

Update-Help -SourcePath \\Server\Share

The following examples show the use of Save-Help to save help for modules
that are
not installed on the local computer. In this example, the
administrator runs Save-Help to
save the help for the DhcpServer module from
an internet-connected client computer,
without installing the DhcpServer module
or DHCP Server role on the local computer.

Option 1: Run Invoke-Command to get the PSModuleInfo object for the


remote module,
save it in a variable, $m , and then run Save-Help on the
PSModuleInfo object by
specifying the variable $m as the module name.

PowerShell

$m = Invoke-Command -ComputerName RemoteServer -ScriptBlock

{ Get-Module -Name DhcpServer -ListAvailable }

Save-Help -Module $m -DestinationPath C:\SavedHelp

Option 2: Open a PSSession targeted at the computer that is running the DHCP
Server
module, to get the PSModuleInfo object for the module, save it in a
variable $m , and
then run Save-Help on the object that is saved in the $m
variable.

PowerShell

$s = New-PSSession -ComputerName RemoteServer

$m = Get-Module -PSSession $s -Name DhcpServer -ListAvailable

Save-Help -Module $m -DestinationPath C:\SavedHelp

Option 3: Open a CIM session, targeted at the computer that is running the DHCP
Server module, to get the PSModuleInfo object for the module, save it in a
variable $m ,
and then run Save-Help on the object that is saved in the $m
variable.

PowerShell

$c = New-CimSession -ComputerName RemoteServer

$m = Get-Module -CimSession $c -Name DhcpServer -ListAvailable

Save-Help -Module $m -DestinationPath C:\SavedHelp

In the following example, the administrator installs help for the DHCP Server
module on
a computer that does not have network access.

First, run Export-Clixml to export the PSModuleInfo object to a shared


folder or to
removable media.

PowerShell

$m = Get-Module -Name DhcpServer -ListAvailable

Export-Clixml -Path E:\UsbFlashDrive\DhcpModule.xml -InputObject $m

Next, transport the removable media to a computer that has internet access, and
then
import the PSModuleInfo object with Import-Clixml . Run Save-Help
to save the Help
for the imported DhcpServer module PSModuleInfo object.

PowerShell

$deserialized_m = Import-Clixml E:\UsbFlashDrive\DhcpModule.xml

Save-Help -Module $deserialized_m -DestinationPath


E:\UsbFlashDrive\SavedHelp

Finally, transport the removable media back to the computer that does not have
network access, and then install the help by running Update-Help .

PowerShell

Update-Help -Module DhcpServer -SourcePath E:\UsbFlashDrive\SavedHelp

Without parameters, Save-Help downloads help for all modules in the session
and for all
installed modules that support Updatable Help. To be included,
modules must be
installed in directories that are listed in the value of the
$env:PSModulePath environment
variable, on either the local computer or on a remote
computer for which you want to
save help. These are also modules that are
returned by running a Get-Help -
ListAvailable command.

How to update help files in different languages


By default, the Update-Help and Save-Help cmdlets download help in the UI
culture and
language that is set for Windows on the local computer. If help
files for the specified
modules are not available in the local UI culture,
Update-Help and Save-Help use the
Windows language fallback rules to find
the best supported language.

However, you can use the UICulture parameters of the Update-Help and
Save-Help
cmdlets to download and install help files in any UI cultures in
which they are available.

For example, to save the newest help files for all modules on the session in
Japanese (Ja-
jp) and French (fr-FR), type:

PowerShell

Save-Help -Path \Server\Share -UICulture ja-jp, fr-fr

If help files for the modules are not available in the languages that you
specified, the
Update-Help and Save-Help cmdlets return an error message
that lists the languages in

which help for each module is available so you can


choose the alternative that best
meets your needs.

7 Note

Currently, Updateable Help content is only published in English (en-US).

How to use online help


If you cannot or choose not to update the help files on your local computer,
you can still
get the newest help files online.

To open the online help topic for any cmdlet or function, use the Online
parameter of
the Get-Help cmdlet.

For example, the following command opens the online help topic for the
Get-Job
cmdlet in your default internet browser:

PowerShell
Get-Help Get-Job -Online

To get online help for a script, use the Online parameter and the full path
to the script.

The Online parameter does not work with About topics. To see the about
topics for
PowerShell, including help topics about the PowerShell language, see
PowerShell About
Topics.

How to minimize or prevent internet


downloads
To minimize internet downloads and provide Updatable Help to users who are not
connected to the internet, use the Save-Help cmdlet. Download help from the
internet
and save it to a network share. Then, create a Group Policy setting or
scheduled job that
runs an Update-Help command on all computers. Set the
value of the SourcePath
parameter of the Update-Help cmdlet to the
network share.

To prevent users who have internet access from downloading Updatable Help from
the
internet, use the Set the default source path for Update-Help Group
Policy setting.

This Group Policy setting implicitly adds the SourcePath parameter, with
the filesystem
location that you specify, to every Update-Help command on
every affected computer.
Users can use the SourcePath parameter explicitly
to specify a different filesystem
location, but they cannot exclude the
SourcePath parameter and download help from
the internet.

7 Note

The Set the default source path for Update-Help group policy setting
appears
under Computer Configuration and User Configuration. However,
only the policy
setting under Computer Configuration is effective. The
policy setting under User
Configuration is ignored.

For more information, see


about_Group_Policy_Settings.

How to update help for non-standard modules


To update or save help for a module that is not returned by the
ListAvailable parameter
of the Get-Module cmdlet, import the module into
the current session before running an
Update-Help or Save-Help command. On
a remote computer, before running the Save-

Help command, import the module


into the current Session, or Invoke-Command script
block, that is connected
to the remote computer.

When the module is in the current session, run the Update-Help or Save-Help
cmdlets
without parameters, or use the Module parameter to specify the
module name.

The Module parameters of the Update-Help and Save-Help cmdlets accept


only a
module name. They do not accept the path to a module file.

Use this technique to update or save help for any module that is not returned
by the
ListAvailable parameter of the Get-Module cmdlet, such as a module
that is installed in a
location that is not listed in the $env:PSModulePath
environment variable, or a module
that is not well-formed (the module directory
does not contain at least one file whose
basename is the same as the directory
name).

How to support updatable help


If you author a module, you can support online help and Updatable Help for your
modules. For more information, see
Supporting Updatable Help
and Supporting Online
Help.

Updatable help not available for PowerShell snap-ins or comment-based help.

Remarks
The Update-Help and Save-Help cmdlets are not supported on Windows
Preinstallation
Environment (Windows PE).

See also
Get-Help
Save-Help
Update-Help
about_Using
Article • 01/25/2023 • 3 minutes to read

Short description
Allows you to indicate which namespaces are used in the session.

Long description
The using statement allows you to specify which namespaces are used in the
session.
Adding namespaces simplifies usage of .NET classes and member and
allows you to
import classes from script modules and assemblies.

The using statements must come before any other statements in a script or
module. No
uncommented statement can precede it, including parameters.

The using statement must not contain any variables.

The using statement should not be confused with the using: scope modifier
for
variables. For more information, see
about_Remote_Variables.

Namespace syntax
To specify .NET namespaces from which to resolve types:

using namespace <.NET-namespace>

Specifying a namespace makes it easier to reference types by their short names.

Module syntax
To load classes from a PowerShell module:

using module <module-name>

The value of <module-name> can be a module name, a full module specification,


or a path
to a module file.

When <module-name> is a path, the path can be fully qualified or relative. A


relative path
is resolved relative to the script that contains the using
statement.

When <module-name> is a name or module specification, PowerShell searches the


PSModulePath for the specified module.

A module specification is a hashtable that has the following keys.

ModuleName - Required Specifies the module name.

GUID - Optional Specifies the GUID of the module.


It's also Required to specify at least one of the three below keys.
ModuleVersion - Specifies a minimum acceptable version of the module.

MaximumVersion - Specifies the maximum acceptable version of the module.


RequiredVersion - Specifies an exact, required version of the module.
This can't

be used with the other Version keys.

The using module statement imports classes from the root module
( ModuleToProcess ) of
a script module or binary module. It does not
consistently import classes defined in
nested modules or classes defined in
scripts that are dot-sourced into the module.
Classes that you want to be
available to users outside of the module should be defined
in the root module.

During development of a script module, it is common to make changes to the code


then
load the new version of the module using Import-Module with the
Force parameter. This
works for changes to functions in the root module
only. Import-Module does not reload
any nested modules. Also, there is no way
to load any updated classes.

To ensure that you are running the latest version, you must unload the module
using the
Remove-Module cmdlet. Remove-Module removes the root module, all
nested modules,

and any classes defined in the modules. Then you can reload the
module and the classes
using Import-Module and the using module statement.

Assembly syntax
To preload types from a .NET assembly:

using assembly <.NET-assembly-path>

using assembly <.NET-namespace>

Loading an assembly preloads .NET types from that assembly into a script at
parse time.
This allows you to create new PowerShell classes that use types
from the preloaded
assembly.

In Windows PowerShell 5.1 you can load the assembly by path name or by
name. When
you use the name, PowerShell searches the .NET Global Assembly
Cache (GAC) for the
associated assembly.

If you are not creating new PowerShell classes, use the Add-Type cmdlet
instead. For
more information, see
Add-Type.

Examples

Example 1 - Add namespaces for typename resolution


The following script gets the cryptographic hash for the "Hello World" string.

Note how the using namespace System.Text and using namespace System.IO
simplify the
references to [UnicodeEncoding] in System.Text and [Stream]
and to [MemoryStream] in
System.IO .

PowerShell

using namespace System.Text

using namespace System.IO

[string]$string = "Hello World"

## Valid values are "SHA1", "SHA256", "SHA384", "SHA512", "MD5"

[string]$algorithm = "SHA256"

[byte[]]$stringbytes = [UnicodeEncoding]::Unicode.GetBytes($string)

[Stream]$memorystream = [MemoryStream]::new($stringbytes)

$hashfromstream = Get-FileHash -InputStream $memorystream `

-Algorithm $algorithm
$hashfromstream.Hash.ToString()

Example 2 - Load classes from a script module


In this example, we have a PowerShell script module named CardGames that
defines the
following classes:

Deck
Card

Import-Module and the #requires statement only import the module functions,
aliases,
and variables, as defined by the module. Classes are not imported. The
using module
command imports the module and also loads the class definitions.

PowerShell

using module CardGames

[Deck]$deck = [Deck]::new()

$deck.Shuffle()

[Card[]]$hand1 = $deck.Deal(5)

[Card[]]$hand2 = $deck.Deal(5)

[Card[]]$hand3 = $deck.Deal(5)

Example 3 - Load classes from an assembly


This example loads an assembly so that its classes can be used when processing
data.
The following script converts data into a YAML format.

PowerShell

using assembly './YamlDotNet.dll'


using namespace YamlDotNet

$yamlSerializer = [Serialization.Serializer]::new()

$info = [ordered]@{

Inventory = @(

@{ Name = 'Apples' ; Count = 1234 }

@{ Name = 'Bagels' ; Count = 5678 }

CheckedAt = [datetime]'2023-01-01T01:01:01'

$yamlSerializer.Serialize($info)

Output

Inventory:

- Name: Apples

Count: 1234

- Name: Bagels

Count: 5678

CheckedAt: 2023-01-01T01:01:01.0000000

about_Variables
Article • 09/19/2022 • 9 minutes to read

Short description
Describes how variables store values that can be used in PowerShell.

Long description
You can store all types of values in PowerShell variables. For example, store
the results of
commands, and store elements that are used in commands and
expressions, such as
names, paths, settings, and values.

A variable is a unit of memory in which values are stored. In PowerShell,


variables are
represented by text strings that begin with a dollar sign ( $ ),
such as $a , $process , or
$my_var .

Variable names aren't case-sensitive, and can include spaces and special
characters. But,
variable names that include special characters and spaces are
difficult to use and should
be avoided. For more information, see
Variable names that include special characters.

There are several different types of variables in PowerShell.

User-created variables: User-created variables are created and maintained by


the
user. By default, the variables that you create at the PowerShell command
line exist
only while the PowerShell window is open. When the PowerShell
windows is
closed, the variables are deleted. To save a variable, add it to
your PowerShell
profile. You can also create variables in scripts with
global, script, or local scope.

Automatic variables: Automatic variables store the state of PowerShell. These


variables are created by PowerShell, and PowerShell changes their values as
required to maintain their accuracy. Users can't change the value of these
variables. For example, the $PSHOME variable stores the path to the
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


PowerShell.
These variables are created by PowerShell and are populated with
default values.
Users can change the values of these variables. For example,
the
$MaximumHistoryCount variable 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 create a new variable, use an assignment statement to assign a value to the
variable.
You don't have to declare the variable before using it. The default
value of all variables is
$null .

To get a list of all the variables in your PowerShell session, type


Get-Variable . The
variable names are displayed without the preceding dollar
( $ ) sign that is used to
reference variables.

For example:

PowerShell

$MyVariable = 1, 2, 3

$Path = "C:\Windows\System32"

Variables are useful for storing the results of commands.

For example:

PowerShell

$Processes = Get-Process

$Today = (Get-Date).DateTime

To display the value of a variable, type the variable name, preceded by a


dollar sign ( $ ).

For example:

PowerShell

$MyVariable

Output
1

PowerShell

$Today

Output

Tuesday, September 3, 2019 09:46:46

To change the value of a variable, assign a new value to the variable.

The following examples display the value of the $MyVariable variable, changes
the value
of the variable, and then displays the new value.

PowerShell

$MyVariable = 1, 2, 3

$MyVariable

Output

PowerShell

$MyVariable = "The green cat."

$MyVariable

Output

The green cat.

To delete the value of a variable, use the Clear-Variable cmdlet or change


the value to
$null .

PowerShell

Clear-Variable -Name MyVariable

PowerShell

$MyVariable = $null

To delete the variable, use Remove-Variable


or Remove-Item.

PowerShell

Remove-Variable -Name MyVariable

PowerShell

Remove-Item -Path Variable:\MyVariable

It is also possible to assign values to multiple variables with one statement.


The
following examples assigns the same value to multiple variables:

PowerShell

$a = $b = $c = 0

The next example assigns multiple values to multiple variables.

PowerShell

$i,$j,$k = 10, "red", $true # $i is 10, $j is "red", $k is True

$i,$j = 10, "red", $true # $i is 10, $j is [object[]], Length 2

For more detailed information, see the Assigning multiple variables section
of
about_Assignment_Operators.

Types of variables
You can store any type of object in a variable, including integers, strings,
arrays, and
hash tables. And, objects that represent processes, services, event
logs, and computers.

PowerShell variables are loosely typed, which means that they aren't limited to
a
particular type of object. A single variable can even contain a collection,
or array, of
different types of objects at the same time.
The data type of a variable is determined by the .NET types of the values of
the variable.
To view a variable's object type, use
Get-Member.

For example:

PowerShell

$a = 12 # System.Int32

$a = "Word" # System.String

$a = 12, "Word" # array of System.Int32, System.String

$a = Get-ChildItem C:\Windows # FileInfo and DirectoryInfo types

You can use a type attribute and cast notation to ensure that a variable can
contain only
specific object types or objects that can be converted to that
type. If you try to assign a
value of another type, PowerShell tries to convert
the value to its type. If the type can't
be converted, the assignment statement
fails.

To use cast notation, enter a type name, enclosed in brackets, before the
variable name
(on the left side of the assignment statement). The following
example creates a $number
variable that can contain only integers, a $words
variable that can contain only strings,
and a $dates variable that can
contain only DateTime objects.

PowerShell

[int]$number = 8

$number = "12345" # The string is converted to an integer.

$number = "Hello"

Output

Cannot convert value "Hello" to type "System.Int32". Error: "Input string


was

not in a correct format."

At line:1 char:1

+ $number = "Hello"

+ ~~~~~~~~~~~~~~~~~

+ CategoryInfo : MetadataError: (:) [],

ArgumentTransformationMetadataException

+ FullyQualifiedErrorId : RuntimeException

PowerShell

[string]$words = "Hello"

$words = 2 # The integer is converted to a string.


$words += 10 # The plus (+) sign concatenates the strings.

$words

Output

210

PowerShell

[datetime] $dates = "09/12/91" # The string is converted to a DateTime


object.

$dates

Output

Thursday, September 12, 1991 00:00:00

PowerShell

$dates = 10 # The integer is converted to a DateTime object.

$dates

Output

Monday, January 1, 0001 00:00:00

Using variables in commands and expressions


To use a variable in a command or expression, type the variable name, preceded
by the
dollar ( $ ) sign.

If the variable name and dollar sign aren't enclosed in quotation marks, or if
they're
enclosed in double quotation ( " ) marks, the value of the variable is
used in the
command or expression.

If the variable name and dollar sign are enclosed in single quotation ( ' )
marks, the
variable name is used in the expression.

For more information about using quotation marks in PowerShell, see


about_Quoting_Rules.

This example gets the value of the $PROFILE variable, which is the path to
the
PowerShell user profile file in the PowerShell console.

PowerShell
$PROFILE

Output

C:\Users\User01\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

In this example, two commands are shown that can open the PowerShell profile in
notepad.exe. The example with double-quote ( " ) marks uses the variable's
value.

PowerShell

notepad $PROFILE

notepad "$PROFILE"

The following examples use single-quote ( ' ) marks that treat the variable as
literal text.

PowerShell

'$PROFILE'

Output

$PROFILE

PowerShell

'Use the $PROFILE variable.'

Output

Use the $PROFILE variable.

Variable names that include special characters


Variable names begin with a dollar ( $ ) sign and can include alphanumeric
characters
and special characters. The variable name length is limited only by
available memory.

The best practice is that variable names include only alphanumeric characters
and the
underscore ( _ ) character. Variable names that include spaces and
other special
characters, are difficult to use and should be avoided.
Alphanumeric variable names can contain these characters:

Unicode characters from these categories: Lu, Ll, Lt, Lm,


Lo, or Nd.
Underscore ( _ ) character.
Question mark ( ? ) character.

The following list contains the Unicode category descriptions. For more
information, see
UnicodeCategory.

Lu - UppercaseLetter
Ll - LowercaseLetter
Lt - TitlecaseLetter
Lm - ModifierLetter
Lo - OtherLetter
Nd - DecimalDigitNumber

To create or display a variable name that includes spaces or special


characters, enclose
the variable name with the curly braces ( {} ) characters.
The curly braces direct
PowerShell to interpret the variable name's characters
as literals.

Special character variable names can contain these characters:

Any Unicode character, with the following exceptions:


The closing curly brace ( } ) character (U+007D).
The backtick ( ` ) character (U+0060). The backtick is used to escape
Unicode
characters so they're treated as literals.

PowerShell has reserved variables such as $$ , $? , $^ , and $_ that


contain alphanumeric
and special characters. For more information, see
about_Automatic_Variables.

For example, the following command creates the variable named save-items . The
curly
braces ( {} ) are needed because variable name includes a hyphen ( - )
special character.

PowerShell

${save-items} = "a", "b", "c"

${save-items}

Output

The following command gets the child items in the directory that is represented
by the
ProgramFiles(x86) environment variable.

PowerShell

Get-ChildItem ${env:ProgramFiles(x86)}

To reference a variable name that includes braces, enclose the variable name in
braces,
and use the backtick character to escape the braces. For example, to
create a variable
named this{value}is type:

PowerShell

${this`{value`}is} = "This variable name uses braces and backticks."

${this`{value`}is}

Output

This variable name uses braces and backticks.

Variables and scope


By default, variables are only available in the scope in which they're created.

For example, a variable that you create in a function is available only within
the function.
A variable that you create in a script is available only within
the script. If you dot-source
the script, the variable is added to the current
scope. For more information, see
about_Scopes.

You can use a scope modifier to change the default scope of the variable. The
following
expression creates a variable named Computers . The variable has a
global scope, even
when it's created in a script or function.

PowerShell

$Global:Computers = "Server01"

For any script or command that executes out of session, you need the Using
scope
modifier to embed variable values from the calling session scope, so that
out of session
code can access them.

For more information, see about_Remote_Variables.


Saving variables
Variables that you create are available only in the session in which you create
them.
They're lost when you close your session.

To create the variable in every PowerShell session that you start, add the
variable to your
PowerShell profile.

For example, to change the value of the $VerbosePreference variable in every


PowerShell session, add the following command to your PowerShell profile.

PowerShell

$VerbosePreference = "Continue"

You can add this command to your PowerShell profile by opening the $PROFILE
file in a
text editor, such as notepad.exe. For more information about
PowerShell profiles, see
about_Profiles.

The Variable: drive


The PowerShell Variable provider creates a Variable: drive that looks and
acts like a file
system drive, but it contains the variables in your session
and their values.

To change to the Variable: drive, use the following command:

PowerShell

Set-Location Variable:

To list the items and variables in the Variable: drive, use the Get-Item or
Get-ChildItem
cmdlets.

PowerShell

Get-ChildItem Variable:

To get the value of a particular variable, use file system notation to specify
the name of
the drive and the name of the variable. For example, to get the
$PSCulture automatic
variable, use the following command.

PowerShell
Get-Item Variable:\PSCulture

Output

Name Value

---- -----

PSCulture en-US

To display more information about the Variable: drive and the PowerShell
Variable
provider, type:

PowerShell

Get-Help Variable

Variable syntax with provider paths


You can prefix a provider path with the dollar ( $ ) sign, and access the
content of any
provider that implements the
IContentCmdletProvider
interface.

The following built-in PowerShell providers support this notation:

about_Environment_Provider
about_Variable_Provider
about_Function_Provider
about_Alias_Provider

The variable cmdlets


PowerShell includes a set of cmdlets that are designed to manage variables.

To list the cmdlets, type:

PowerShell

Get-Command -Noun Variable

To get help for a specific cmdlet, type:

PowerShell

Get-Help <cmdlet-name>

Cmdlet Name Description

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 Changes the value of a variable.

See also
about_Automatic_Variables
about_Environment_Variables
about_Preference_Variables
about_Profiles
about_Quoting_Rules
about_Remote_Variables
about_Scopes
about_Variable_Provider
Article • 09/19/2022 • 5 minutes to read

Provider name
Variable

Drives
Variable:

Capabilities
ShouldProcess

Short description
Provides access to the PowerShell variables and to their values.

Detailed description
The PowerShell Variable provider lets you get, add, change, clear, and
delete PowerShell
variables in the current console.

The PowerShell Variable provider supports the variables that PowerShell


creates,
including the automatic variables, the preference variables, and the
variables that you
create.

The Variable drive is a flat namespace that contains only the variable
objects. The
variables have no child items.

The Variable provider supports the following cmdlets, which are covered
in this article.

Get-Location
Set-Location
Get-Item
New-Item
Remove-Item
Clear-Item
PowerShell also includes a set of cmdlets designed especially to view and to
change
variables. When you use Variable cmdlets, you do not need to specify
the Variable:
drive in the name. This article does not cover working with
Variable cmdlets.

Get-Variable
New-Variable
Set-Variable
Remove-Variable
Clear-Variable

7 Note

You can also use the 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.

Types exposed by this provider


Variables can be one of several different types. Most variables will be
instances of the
PSVariable class. Other variables and their types are
listed below.

The ? variable is an instance of the QuestionMarkVariable class.


The null variable is an instance of the NullVariable class.
The maximum count variables are instances of the
SessionStateCapacityVariable
class.
LocalVariable instances contain information about current execution,
such as:

MyInvocation

PSCommandPath
PSScriptRoot

PSBoundParameters
args

input

Navigating the Variable drives


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 PowerShell drive. To
reference a variable

from another location, use the drive name ( Variable: ) in


the path.

PowerShell

Set-Location Variable:

To return to a file system drive, type the drive name. For example, type:

PowerShell

Set-Location C:

You can also work with the Variable provider from any other PowerShell
drive. To
reference an variable from another location, use the drive name
Variable: in the path.

7 Note

PowerShell uses aliases to allow you a familiar way to work with provider
paths.
Commands such as dir and ls are now aliases for
Get-ChildItem,
cd is an alias for
Set-Location. and pwd is
an alias for Get-Location.

Displaying the value of variables

Get all variables in the current session


This command gets the list of all the variables and their values in the current
session.
You can use this command from any PowerShell drive.

PowerShell

Get-ChildItem -Path Variable:

Get a variable using its provider path


This command retrieves a variables value using its provider path prefixed by the
dollar
sign ( $ ). This has the same effect as prefixing the variables name with
the dollar sign
( $ ).

PowerShell
$variable:home

Get variables using wildcards


This command gets the variables with names that begin with "max". You can use
this
command from any PowerShell drive.

PowerShell

Get-ChildItem -Path Variable:max*

Get the value of the ? variable


This command uses the -LiteralPath parameter of
Get-ChildItem to get
the value of
the ? variable from within the Variable: drive. The ? is
a wildcard in paths, but Get-
ChildItem does not attempt to resolve any
wildcards in the values of the -LiteralPath
parameter.

PowerShell

Get-ChildItem -Literalpath ?

Get ReadOnly and Constant variables


This command gets the variables that have the values of ReadOnly or
Constant for their
Options property.

PowerShell

Get-ChildItem -Path Variable: | Where-Object {

$_.options -Match "Constant" `

-or $_.options -Match "ReadOnly"

} | Format-List -Property name, value, options

Creating variables

Create a new variable


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.

PowerShell

New-Item -Path . -Name services -Value (Get-Service)

Create a variable using an absolute path


This command creates a services variable and stores the result of a
Get-Service
command in it.

PowerShell

New-Item -Path Variable:services -Value Get-Service

To create a variable without a value, omit the assignment operator.

Changing variables

Rename a variable
This command uses the Rename-Item cmdlet to change the name of the a
variable to
processes .

PowerShell

Rename-Item -Path Variable:a -NewName processes

Change the value of a variable


This command uses the Set-Item cmdlet to change the value of the
ErrorActionPreference variable to "Stop".

PowerShell
Set-Item -Path Variable:ErrorActionPreference -Value Stop

Copy a variable
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.

PowerShell

Copy-Item -Path Variable:processes -Destination Variable:old_processes

Delete a variable
This command deletes the serv variable from the current session. You can use
this
command in any PowerShell drive.

PowerShell

Remove-Variable -Path Variable:serv

Delete variables using the -Force parameter


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 .

PowerShell

Remove-Item Variable:* -Force

Setting the value of a variable to NULL


This command uses the Clear-Item cmdlet to change the value of the
processes
variable to NULL.

PowerShell

Clear-Item -Path Variable:processes

Using the pipeline


Provider cmdlets accept pipeline input. You can use the pipeline to simplify
task by
sending provider data from one cmdlet to another provider cmdlet.
To read more about
how to use the pipeline with provider cmdlets, see the
cmdlet references provided
throughout this article.

Getting help
Beginning in Windows PowerShell 3.0, you can get customized help topics for
provider
cmdlets that explain how those cmdlets behave in a file system drive.

To get the help topics that are customized for the file system drive, run a
Get-Help
command in a file system drive or use the -Path
parameter of Get-Help to specify a file
system drive.

PowerShell

Get-Help Get-ChildItem

PowerShell

Get-Help Get-ChildItem -Path variable:

See also
about_Automatic_Variables
about_Providers
about_Variables
about_While
Article • 09/19/2022 • 2 minutes to read

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:

PowerShell

while (<condition>){<statement list>}

When you run a while statement, 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,
PowerShell reruns the <statement list> section. For
more information about how
booleans are evaluated, see
about_Booleans.

The <statement list> section of the statement contains one or more commands
that
are run each time the loop is entered or repeated. The <statement list>
can contain
any valid PowerShell statements, including the break and
continue keywords.

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.

PowerShell
while($val -ne 3)

$val++

Write-Host $val

In this example, the condition ( $val is not equal to 3) is true while $val
is equal to 0, 1,
and 2. Each time through the loop, $val is incremented by 1
using the ++ unary
increment operator. The last time through the loop $val
is set to 3, the condition
statement evaluates to false, and the loop exits.

To conveniently write this command at the PowerShell command prompt, you


can enter
it in the following way:

PowerShell

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_Booleans
about_Break
about_Comparison_Operators
about_Continue
about_Do
about_For
about_Foreach
about_Language_Keywords
about_Wildcards
Article • 01/24/2023 • 2 minutes to read

Short description
Describes how to use wildcard characters in PowerShell.

Long description
Wildcard characters represent one or many characters. You can use them to
create word
patterns in commands. Wildcard expressions are used with the
-like operator or with
any parameter that accepts wildcards.

For example, to match all the files in the C:\Techdocs directory with a
.ppt file name
extension, type:

PowerShell

Get-ChildItem C:\Techdocs\*.ppt

In this case, the asterisk ( * ) wildcard character represents any characters


that appear
before the .ppt file name extension.

Wildcard expressions are simpler than regular expressions. For more


information, see
about_Regular_Expressions.

PowerShell supports the following wildcard characters:

* - Match zero or more characters

a* matches aA , ag , and Apple


a* doesn't match banana

? - Match one character in that position

?n matches an , in , and on
?n doesn't match ran

[ ] - Match a range of characters


[a-l]ook matches book , cook , and look

[a-l]ook doesn't match took

[ ] - Match specific characters


[bc]ook matches book and cook
[bc]ook doesn't match hook

`* - Match any character as a literal (not a wildcard character)


12`*4 matches 12*4

12`*4 doesn't match 1234

You can include multiple wildcard characters in the same word pattern. For
example, to
find text files with names that begin with the letters a
through l, type:

PowerShell

Get-ChildItem C:\Techdocs\[a-l]*.txt

There may be cases where you want to match the literal character rather than
treat it as
a wildcard character. In those cases you can use the backtick
( ` ) character to escape the
wildcard character so that it is compared
using the literal character value. For example,
'*hello`?*' matches strings
containing "hello?".

Many cmdlets accept wildcard characters in parameter values. The Help topic for
each
cmdlet describes which parameters accept wildcard characters. For
parameters that
accept wildcard characters, their use is case-insensitive.

You can use wildcard characters in commands and script blocks, such as to
create a
word pattern that represents property values. For example, the
following command gets
services in which the ServiceType property value
includes Interactive.

PowerShell

Get-Service | Where-Object {$_.ServiceType -Like "*Interactive*"}

In the following example, the If statement includes a condition that uses


wildcard
characters to find property values. If the restore point's
Description includes PowerShell,
the command adds the value of the
restore point's CreationTime property to a log file.

PowerShell

$p = Get-ComputerRestorePoint

foreach ($point in $p) {

if ($point.description -like "*PowerShell*") {

Add-Content -Path C:\TechDocs\RestoreLog.txt "$($point.CreationTime)"

See also
about_If
about_Language_Keywords
about_Script_Blocks
about_Windows_Powershell_5.1
Article • 09/19/2022 • 4 minutes to read

Short description
Describes new features that are included in Windows PowerShell 5.1.

Long description
Windows PowerShell 5.1 includes significant new features that extend its use,
improve
its usability, and allow you to control and manage Windows-based
environments more
easily and comprehensively.

Windows PowerShell 5.1 is backward-compatible. Cmdlets, providers, modules,


snap-ins,
scripts, functions, and profiles that were designed for Windows
PowerShell 4.0, Windows
PowerShell 3.0, and Windows PowerShell 2.0 generally
work in Windows PowerShell 5.1
without changes.

New cmdlets: local users and groups; Get-ComputerInfo


PowerShellGet improvements include enforcing signed modules, and installing
JEA
modules
PackageManagement added support for Containers, CBS Setup, EXE-based setup,
CAB packages
Debugging improvements for DSC and PowerShell classes
Security enhancements including enforcement of catalog-signed modules coming
from the Pull Server and when using PowerShellGet cmdlets
Responses to a number of user requests and issues

Windows PowerShell 5.1 is installed by default on Windows Server version 2016 and
higher and Windows
client version 10 and higher.

To install Windows PowerShell 5.1 on Windows Server 2012 R2, Windows 8.1 Enterprise,
or Windows 8.1
Pro, see Install and Configure WMF 5.1. Be sure
to read the download
details, and meet all system requirements, before you install Windows
Management
Framework 5.1.

You can also read about changes to Windows PowerShell 5.1 in


What's New in Windows
PowerShell.

New Scenarios and Features in WMF 5.1


Note: This information is preliminary and subject to change.

PowerShell Editions
Starting with version 5.1, PowerShell is available in different editions which denote
varying feature sets and platform compatibility.

Desktop Edition: Built on .NET Framework and provides compatibility with


scripts
and modules targeting versions of PowerShell running on full footprint
editions of
Windows such as Server Core and Windows Desktop.
Core Edition: Built on .NET Core and provides compatibility with scripts
and
modules targeting versions of PowerShell running on reduced footprint
editions of
Windows such as Nano Server and Windows IoT.

Learn more about using PowerShell Editions

Determine running edition of PowerShell using $PSVersionTable


Filter Get-Module results by CompatiblePSEditions using PSEdition parameter
Prevent script execution unless run on a compatible edition of PowerShell
Declare a module's compatibility to specific PowerShell versions

Catalog Cmdlets
Two new cmdlets have been added in the
Microsoft.PowerShell.Security
module; these
generate and validate Windows catalog files.

New-FileCatalog

New-FileCatalog creates a Windows catalog file for set of folders and files.
This catalog
file contains hashes for all files in specified paths. Users can
distribute the set of folders
along with corresponding catalog file
representing those folders. This information is
useful to validate whether any
changes have been made to the folders since catalog
creation time.

New-FileCatalog [-CatalogFilePath] <string> [[-Path] <string[]>]

[-CatalogVersion <int>] [-WhatIf] [-Confirm] [<CommonParameters>]

Catalog versions 1 and 2 are supported. Version 1 uses the SHA1 hashing
algorithm to
create file hashes; version 2 uses SHA256. Catalog version 2 is
not supported on
Windows Server 2008 R2 or Windows 7. You should use
catalog version 2 on Windows 8,
Windows Server 2012, and later operating
systems.

To verify the integrity of catalog file (Pester.cat in above example), sign it


using
Set-
AuthenticodeSignature
cmdlet.

Test-FileCatalog

Test-FileCatalog validates the catalog representing a set of folders.

Test-FileCatalog [-Detailed] [-FilesToSkip <String[]>]

[-CatalogFilePath] <String> [[-Path] <String[]>]

[-WhatIf] [-Confirm] [<CommonParameters>]

This cmdlet compares all the files hashes and their relative paths found in
catalog with
ones on disk. If it detects any mismatch between file hashes
and paths it returns the
status as ValidationFailed. Users can retrieve all
this information by using the -Detailed
parameter. It also displays signing
status of catalog in Signature property which is
equivalent to calling
Get-AuthenticodeSignature
cmdlet on the catalog file. Users can
also skip any file during validation by
using the -FilesToSkip parameter.

Module Analysis Cache


Starting with WMF 5.1, PowerShell provides control over the file that is used
to cache
data about a module, such as the commands it exports.

By default, this cache is stored in the file


${env:LOCALAPPDATA}\Microsoft\Windows\PowerShell\ModuleAnalysisCache . The
cache is
typically read at startup while searching for a command and is
written on a background
thread sometime after a module is imported.

To change the default location of the cache, set the


$env:PSModuleAnalysisCachePath
environment variable before starting
PowerShell. Changes to this environment variable
will only affect children
processes. The value should name a full path (including
filename) that
PowerShell has permission to create and write files. To disable the file
cache, set this value to an invalid location, for example:

PowerShell

$env:PSModuleAnalysisCachePath = 'nul'

This sets the path to an invalid device. If PowerShell can't write to the
path, no error is
returned, but you can see error reporting by using a tracer:

PowerShell

Trace-Command -PSHost -Name Modules -Expression {

Import-Module Microsoft.PowerShell.Management -Force

When writing out the cache, PowerShell will check for modules that no longer
exist to
avoid an unnecessarily large cache. Sometimes these checks are not
desirable, in which
case you can turn them off by setting:

PowerShell

$env:PSDisableModuleAnalysisCacheCleanup = 1

Setting this environment variable will take effect immediately in the current
process.

Specifying module version


In WMF 5.1, using module behaves the same way as other module-related
constructions
in PowerShell. Previously, you had no way to specify a
particular module version; if there
were multiple versions present, this
resulted in an error.

In WMF 5.1:

You can use ModuleSpecification Constructor (Hashtable).


This hash table has the
same format as Get-Module -FullyQualifiedName .

Example: using module @{ModuleName = 'PSReadLine'; RequiredVersion = '1.1'}

If there are multiple versions of the module, PowerShell uses the same
resolution
logic as Import-Module and doesn't return an error--the same
behavior as Import-
Module and Import-DscResource .

Improvements to Pester
In WMF 5.1, the version of Pester that ships with PowerShell has been updated
from
3.3.5 to 3.4.0, with the addition of GitHub PR# 484 ,
which enables better behavior for
Pester on Nano Server.
You can review the changes in versions 3.3.5 to 3.4.0 by inspecting the
CHANGELOG in
the GitHub repository.

KEYWORDS
What's New in Windows PowerShell 5.1
about_Windows_PowerShell_ISE
Article • 09/19/2022 • 7 minutes to read

Short description
Describes the features and system requirements of Windows PowerShell
Integrated
Scripting Environment (ISE).

Long description
Windows PowerShell ISE is a graphical 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 Intellisense, multiline
editing, tab completion, auto-save, syntax
coloring, selective execution, context-sensitive
help, Show Command (compose
commands in a window) and support for double-byte
character sets and
right-to-left languages.

Windows PowerShell ISE is an excellent tool for beginners. The Show Command
window
and New Remote PowerShell Tab guide you through tasks so that you can
be successful
on the first try. Snippets and error indicators help you learn
the Windows PowerShell
language as you work.

Advanced users can take advantage of the sophisticated debugging features,


add-ons,
and the Windows PowerShell ISE object model.

What's New in Windows PowerShell ISE in Windows PowerShell 4.0

Windows PowerShell ISE introduces two new features in Windows PowerShell 4.0.

Windows PowerShell ISE now supports both Windows PowerShell Workflow


debugging and remote script debugging. For more Information, see
about_Debuggers.

IntelliSense support has been added for Windows PowerShell Desired State
Configuration providers and configurations.

Starting Windows PowerShell ISE


Windows PowerShell ISE is installed, enabled, and ready to use in all
supported versions
of Windows.
In Windows 8.1, Windows 8, Windows Server 2012 R2, and Windows Server 2012,
on the Start screen, type PowerShell_ISE, and then click PowerShell_ISE or
Windows
PowerShell ISE.

In Windows Server 2012 R2 and Windows Server 2012, in Server Manager, on the
Tools menu, click Windows PowerShell ISE.

In earlier versions of Windows, click Start, All Programs, Accessories,


Windows
PowerShell, and then click Windows PowerShell ISE.

In a Windows PowerShell console, Cmd.exe, or the Run or Search box in


Windows,
type "PowerShell_ise.exe". You can also use the command-line
parameters,
including the NoProfile switch. For more information, see
PowerShell_ISE.exe
Console Help.

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 Console 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
Console 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 Console pane. You can
move
or copy the results from the Console pane by using keyboard shortcuts or
the Copy
button on the toolbar, and you can paste the results in the Script
pane or Console panes
or other programs. To clear the Console pane, click the
"Clear Output Pane" button or
type 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 Console 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
Selection button or press F8. By
default, F8 runs the current line.

Advanced editing features include brace-matching, expand-collapse, line


numbers, error
indicators, block editing and indenting, rich copy, and case
conversion.

Getting Help
Windows PowerShell ISE includes help topics that describe its use. In
addition, all
installed help files are accessible from the Script and Command
panes.

Windows PowerShell ISE also supports context-sensitive help. To get help about
a
particular cmdlet, provider, or keyword, place the cursor in the name of the
item and
press F1. To search the help topics, press F1 and type the search
term.

To update the help topics on the computer, use the Update Windows PowerShell
Help
item in the Help menu. This item updates help for the modules in the
current session in
the current UI culture. It is equivalent to running the
Update-Help cmdlet without
parameters. To update help for the cmdlets that
come with Windows PowerShell, start
Windows PowerShell ISE with the "Run as
administrator" option.

You can also use the Get-Help, Save-Help, and Update-Help cmdlets in Windows
PowerShell ISE, just as you use it in the Windows PowerShell console. However,
in
Windows PowerShell ISE, the Help function displays the entire help topic,
not one page
at a time.

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.
As you step through a script while debugging, the debugging highlighter shows
precisely which part of the command is running and automatically opens files
that
include called functions and scripts.

By default, the Toggle Breakpoint menu item sets a breakpoint on an entire


line in a
script, but you can set a breakpoint on a variable or command name.
You can also set a
breakpoint on a command by line and column number, making
it easier to debug long
pipeline commands.

Often, you can debug syntax errors in a script just by opening the script file
in Windows
PowerShell ISE. The error indicators identify syntax errors and the
outlining features let
you collapse parts of the script to focus on trouble
spots.

You can also use the Windows PowerShell debugger cmdlets in the Command pane
just
as you would use them in the console.

Running Remote Commands


The New Remote PowerShell Tab feature makes it easy to establish a persistent
user-
managed Windows PowerShell session ("PSSession") to the local computer or
a remote
computer. The command opens a pop-up window that prompts you for a
computer
name and for the user account that has permission to run commands on
the remote
computer.

Customizing the View


You can use Windows PowerShell ISE features to move and to resize the Console
pane
and the Script pane. You can show and hide either pane, and you can
change the text
size in all the panes.

You can also use the Options window to customize the appearance and operation
of
Windows PowerShell ISE. In addition, Windows PowerShell ISE has a custom
host
variable, $psISE, that you can use 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.

Notes
Windows PowerShell ISE is an optional Windows Feature that is turned on by
default on
client and server versions of Windows. To enable and disable
Windows PowerShell ISE in
client versions of Windows, use Turn Windows
Features On or Off in Control Panel. To
enable and disable Windows PowerShell
ISE in server versions of Windows, use the Add
Roles and Features Wizard in
Server Manager.

Because Windows PowerShell ISE requires a user interface, it does not work on
Server
Core installations of Windows Server. However, if you add the Windows
PowerShell ISE
feature, the installation automatically converts to Server with
a GUI.

Windows 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 "Disable
WPF Hardware
acceleration" graphics rendering settings on your system. For more
information, see
Graphics Rendering Registry Settings.

See also
about_Debuggers
about_Profiles
about_Updatable_Help
Show-Command
Get-Help
Save-Help
Update-Help
Get-IseSnippet
Import-IseSnippet
New-IseSnippet
about_Windows_RT
Article • 09/19/2022 • 2 minutes to read

Short description
Explains limitations of Windows PowerShell 4.0 on Windows RT 8.1.

Long description
The Windows RT 8.1 operating system is installed on computers and devices
(such as
Microsoft Surface 2, on which it is the operating system that ships
with the computer)
that use Advanced RISC Machine (ARM) processors.

Windows PowerShell 4.0 is included in Windows RT 8.1. All cmdlets, providers,


and
modules, and most scripts designed for Windows PowerShell 2.0 and later
releases run
on Windows RT 8.1 without changes.

Because Windows RT 8.1 does not include all Windows features, some Windows
PowerShell features work differently or do not work on Windows RT-based
devices. The
following list explains the differences.

Windows PowerShell ISE is not included in and cannot run on Windows RT 8.1.
Windows PowerShell ISE requires Windows Presentation Foundation, which is not
included in Windows RT 8.1.

Windows PowerShell remoting and the WinRM service are disabled by default.
To
enable remoting, run the Enable-PSRemoting cmdlet. Also, run the
Set-Service
cmdlet to set the startup type of the WinRM service to Automatic,
or Automatic
(Delayed Start).

While remoting is disabled, you can use Windows PowerShell remoting to run
commands on other computers, but other computers cannot run commands on
the
Windows RT device. Also, implicit remoting - that is, remoting that is built
in to
a cmdlet or script, and not explicitly requested with added parameters
does not work in Windows PowerShell running on Windows RT 8.1.

Domain-joined computing and Kerberos authentication are not supported on


Windows RT 8.1. You cannot use Windows PowerShell to add or manage these
features.
Microsoft .NET Framework classes that are not supported on Windows RT 8.1
are
also not supported by Windows PowerShell on Windows RT 8.1.

Transactions are not enabled on Windows RT 8.1. Transaction cmdlets, such


as
Start-Transaction, and transaction parameters, such as UseTransaction, do
not work
properly.

All Windows PowerShell sessions on Windows RT 8.1 devices use the


ConstrainedLanguage language mode. ConstrainedLanguage language mode is a
companion to User Mode Code Integrity (UMCI). It permits all Windows cmdlets
and Windows PowerShell language elements, but restricts types to ensure that
users cannot use Windows PowerShell to circumvent or violate the UMCI
protections.

For more information about ConstrainedLanguage language mode, see


about_Language_Modes.

See also
about_Language_Modes
about_Remote
about_Windows_PowerShell_ISE
about_WMI
Article • 09/19/2022 • 2 minutes to read

Short description
Windows Management Instrumentation (WMI) uses the Common Information Model
(CIM) to represent systems, applications, networks, devices, and other
manageable
components of the modern enterprise.

Long description
Windows Management Instrumentation (WMI) is Microsoft's implementation of
Web-
Based Enterprise Management (WBEM), the industry standard.

Classic WMI uses DCOM to communicate with networked devices to manage remote
systems. Windows PowerShell 3.0 introduces a CIM provider model that uses
WinRM to
remove the dependency on DCOM. This CIM provider model also uses new
WMI
provider APIs that enable developers to write Windows PowerShell cmdlets
in native
code (C++).

Do not confuse WMI providers with Windows PowerShell providers. Many Windows
features have an associated WMI provider that exposes their management
capabilities.
To get WMI providers, run a WMI query that gets instances of the
__Provider WMI class,
such as the following query.

PowerShell

Get-WmiObject -Class __Provider

THREE COMPONENTS OF WMI


The following three components of WMI interact with Windows PowerShell:
Namespaces, Providers, and Classes.

WMI Namespaces organize WMI providers and WMI classes into groups of related
components. In this way, they are similar to .NET Framework namespaces.
Namespaces
are not physical locations, but are more like logical databases.
All WMI namespaces are
instances of the __Namespace system class. The default
WMI namespace is Root/CIMV2
(since Microsoft Windows 2000). To use Windows
PowerShell to get WMI namespaces in
the current session, use a command with
the following format.

PowerShell

Get-WmiObject -Class __Namespace

To get WMI namespaces in other namespaces, use the Namespace parameter to


change
the location of the search. The following command finds WMI namespaces
that reside in
the Root/Cimv2/Applications namespace.

PowerShell

Get-WmiObject -Class __Namespace -Namespace root/CIMv2/applications

WMI namespaces are hierarchical. Therefore, obtaining a list of all namespaces


on a
particular system requires performing a recursive query starting at the
root namespace.

WMI Providers expose information about Windows manageable objects. A provider


retrieves data from a component, and passes that data through WMI to a
management
application, such as Windows PowerShell. Most WMI providers are
dynamic providers,
which means that they obtain the data dynamically when it
is requested through the
management application.

FINDING WMI CLASSES


In a default installation of Windows 8, there are more than 1,100 WMI classes
in
Root/Cimv2. With this many WMI classes, the challenge becomes identifying
the
appropriate WMI class to use to perform a specific task. Windows
PowerShell 3.0
provides two ways to find WMI classes that are related to a
specific topic.

For example,to find WMI classes in the root\CIMV2 WMI namespace that are
related to
disks, you can use a query such as the one shown here.

PowerShell

Get-WmiObject -List *disk*

To find WMI classes that are related to memory, you might use a query such as
the one
shown here.

PowerShell
Get-WmiObject -List *memory*

The CIM cmdlets also provide the ability to discover WMI classes. To do this,
use the
Get-CIMClass cmdlet. The command shown here lists WMI classes related
to video.

PowerShell

Get-CimClass *video*

Tab expansion works when changing WMI namespaces, and therefore use of tab
expansion makes sub-WMI namespaces easily discoverable. In the following
example,
the Get-CimClass cmdlet lists WMI classes related to power settings.
To find it, type the
root/CIMV2/ namespace and then press the Tab key
several times until the power

namespace appears. Here is the command:

PowerShell

Get-CimClass *power* -Namespace root/cimv2/power

about_WMI_Cmdlets
Article • 09/19/2022 • 4 minutes to read

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

PowerShell

C:\PS> get-wmiobject win32_bios | format-list *

The following command displays information about the WinRM service for three
remote
computers.

PowerShell

$wql = "select * from win32_service where name='WinRM'"

get-wmiobject -query $wql -computername server01, server01, server03

The following more complex command exits all instances of a program.

PowerShell

C:\PS> notepad.exe

C:\PS> $wql = "select * from win32_process where name='notepad.exe'"

C:\PS> $np = get-wmiobject -query $wql

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:

PowerShell

PS> $s = [WmiSearcher]'Select * from Win32_Process where Handlecount > 1000'

PS> $s.Get() |sort handlecount |ft handlecount,__path,name -auto

count __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:

PowerShell

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:

PowerShell

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:

1. Click Start, right-click My Computer, and then click Manage.


2. In Computer Management, expand Services and Applications, right-click WMI
Control, and then click Properties.
3. 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

See also
Register-WmiEvent
Set-WmiInstance
Invoke-WmiMethod
Get-WmiObject
Remove-WmiObject
About WMI
WMI Troubleshooting
about_WQL
Article • 09/19/2022 • 14 minutes to read

Short description
Describes WMI Query Language (WQL), which can be used to get WMI objects in
Windows PowerShell.

Long description
WQL is the Windows Management Instrumentation (WMI) query language, which is
the
language used to get information from WMI.

You are not required to use WQL to perform a WMI query in Windows PowerShell.
Instead, you can use the parameters of the Get-WmiObject or Get-CimInstance
cmdlets.
WQL queries are somewhat faster than standard Get-WmiObject commands
and the
improved performance is evident when the commands run on hundreds of
systems.
However, be sure that the time you spend to write a successful WQL
query doesn't
outweigh the performance improvement.

The basic WQL statements you need to use WQL are Select, Where, and From.

WHEN TO USE WQL


When working with WMI, and especially with WQL, do not forget that you are
also using
Windows PowerShell. Often, if a WQL query does not work as
expected, it's easier to use
a standard Windows PowerShell command than to
debug the WQL query.

Unless you are returning massive amounts of data from across


bandwidth-constrained
remote systems, it is rarely productive to spend hours
trying to perfect a complicated
and convoluted WQL query when there is a
perfectly acceptable Windows cmdlet that
does the same thing, if a bit more
slowly.

USING THE SELECT STATEMENT


A typical WMI query begins with a Select statement that gets all properties or
particular
properties of a WMI class. To select all properties of a WMI class,
use an asterisk ( * ). The
From keyword specifies the WMI class.
A Select statement has the following format:

Select <property> from <WMI-class>

For example, the following Select statement selects all properties (*) from
the instances
of the Win32_Bios WMI class.

Select * from Win32_Bios

To select a particular property of a WMI class, place the property name


between the
Select and From keywords.

The following query selects only the name of the BIOS from the Win32_Bios WMI
class.
The command saves the query in the $queryName variable.

Select Name from Win32_Bios

To select more than one property, use commas to separate the property names.
The
following WMI query selects the name and the version of the Win32_Bios WMI
class. The
command saves the query in the $queryNameVersion variable.

Select name, version from Win32_Bios

USING THE WQL QUERY


There are three ways to use WQL query in Windows PowerShell command.

Use the Get-WmiObject cmdlet


Use the Get-CimInstance cmdlet
Use the [wmisearcher] type accelerator.

USING THE GET-WMIOBJECT CMDLET


The most basic way to use the WQL query is to enclose it in quotation marks
(as a
string) and then use the query string as the value of the Query
parameter of the Get-
WmiObject cmdlet, as shown in the following example.

PowerShell

Get-WmiObject -Query "Select * from Win32_Bios"

Output

SMBIOSBIOSVersion : 8BET56WW (1.36 )

Manufacturer : LENOVO

Name : Default System BIOS

SerialNumber : R9FPY3P

Version : LENOVO - 1360

You can also save the WQL statement in a variable and then use the variable as
the value
of the Query parameter, as shown in the following command.

PowerShell

$query = "Select * from Win32_Bios"

Get-WmiObject -Query $query

You can use either format with any WQL statement. The following command uses
the
query in the $queryName variable to get only the name and version
properties of the
system BIOS.

PowerShell

$queryNameVersion = "Select Name, Version from Win32_Bios"

Get-WmiObject -Query $queryNameVersion

Output

__GENUS : 2

__CLASS : Win32_BIOS

__SUPERCLASS :

__DYNASTY :

__RELPATH :

__PROPERTY_COUNT : 1

__DERIVATION : {}

__SERVER :

__NAMESPACE :

__PATH :

Name : Default System BIOS

Version : LENOVO - 1360

Remember that you can use the parameters of the Get-WmiObject cmdlet to get
the
same result. For example, the following command also gets the values of
the Name and
Version properties of instances of the Win32_Bios WMI class.

PowerShell

Get-WmiObject -Class Win32_Bios -Property Name, Version

Output

__GENUS : 2

__CLASS : Win32_BIOS

__SUPERCLASS :

__DYNASTY :

__RELPATH :

__PROPERTY_COUNT : 1

__DERIVATION : {}

__SERVER :

__NAMESPACE :

__PATH :

Name : Default System BIOS

Version : LENOVO - 1360

USING THE GET-CIMINSTANCE CMDLET


Beginning in Windows PowerShell 3.0, you can use the Get-CimInstance cmdlet to
run
WQL queries.

Get-CimInstance gets instances of CIM-compliant classes, including WMI


classes. The
CIM cmdlets, introduced Windows PowerShell 3.0, perform the same
tasks as the WMI
cmdlets. The CIM cmdlets comply with WS-Management (WSMan)
standards and with
the Common Information Model (CIM) standard, which enables
the cmdlets to use the
same techniques to manage Windows computers and
computers that are running other
operating systems.

The following command uses the Get-CimInstance cmdlet to run a WQL query.

Any WQL query that can be used with Get-WmiObject can also be used with
Get-
CimInstance.

PowerShell
Get-CimInstance -Query "Select * from Win32_Bios"

Output

SMBIOSBIOSVersion : 8BET56WW (1.36 )

Manufacturer : LENOVO

Name : Default System BIOS

SerialNumber : R9FPY3P

Version : LENOVO - 1360

Get-CimInstance returns a CimInstance object, instead of the ManagementObject


that
Get-WmiObject returns, but the objects are quite similar.

(Get-CimInstance -Query "Select * from Win32_Bios").GetType().FullName

Microsoft.Management.Infrastructure.CimInstance

(Get-WmiObject -Query "Select * from Win32_Bios").GetType().FullName

System.Management.ManagementObject

USING THE [wmisearcher] TYPE ACCELERATOR


The [wmisearcher] type accelerator creates a ManagementObjectSearcher object
from a
WQL statement string. The ManagementObjectSearcher object has many
properties and
methods, but the most basic method is the Get method, which
invokes the specified
WMI query and returns the resulting objects.

By using the [wmisearcher], you gain easy access to the


ManagementObjectSearcher
.NET Framework class. This lets you query WMI and to
configure the way the query is
conducted.

To use the [wmisearcher] type accelerator:

1. Cast the WQL string into a ManagementObjectSearcher object.


2. Call the Get method of the ManagementObjectSearcher object.

For example, the following command casts the "select all" query, saves the
result in the
$bios variable, and then calls the Get method of the
ManagementObjectSearcher object
in the $bios variable.

PowerShell

$bios = [wmisearcher]"Select * from Win32_Bios"

$bios.Get()

Output

SMBIOSBIOSVersion : 8BET56WW (1.36 )

Manufacturer : LENOVO

Name : Default System BIOS

SerialNumber : R9FPY3P

Version : LENOVO - 1360

NOTE: Only selected object properties are displayed by default. These


properties are
defined in the Types.ps1xml file.

You can use the [wmisearcher] type accelerator to cast the query or the
variable. In the
following example, the [wmisearcher] type accelerator is used
to cast the variable. The
result is the same.

PowerShell

[wmisearcher]$bios = "Select * from Win32_Bios"

$bios.Get()

Output

SMBIOSBIOSVersion : 8BET56WW (1.36 )

Manufacturer : LENOVO

Name : Default System BIOS

SerialNumber : R9FPY3P

Version : LENOVO - 1360

When you use the [wmisearcher] type accelerator, it changes the query string
into a
ManagementObjectSearcher object, as shown in the following commands.

$a = "Select * from Win32_Bios"

$a.GetType().FullName

System.String

$a = [wmisearcher]"Select * from Win32_Bios"

$a.GetType().FullName

System.Management.ManagementObjectSearcher

This command format works on any query. The following command gets the value
of
the Name property of the Win32_Bios WMI class.

PowerShell
$biosname = [wmisearcher]"Select Name from Win32_Bios"

$biosname.Get()

Output

__GENUS : 2

__CLASS : Win32_BIOS

__SUPERCLASS :

__DYNASTY :

__RELPATH :

__PROPERTY_COUNT : 1

__DERIVATION : {}

__SERVER :

__NAMESPACE :

__PATH :

Name : Default System BIOS

You can perform this operation in a single command, although the command is a
bit
more difficult to interpret.

In this format, you use the [wmisearcher] type accelerator to cast the WQL
query string
to a ManagementObjectSearcher, and then call the Get method on
the object -- all in a
single command. The parentheses () that enclose the
casted string direct Windows
PowerShell to cast the string before calling the
method.

PowerShell

([wmisearcher]"Select name from Win32_Bios").Get()

Output

__GENUS : 2

__CLASS : Win32_BIOS

__SUPERCLASS :

__DYNASTY :

__RELPATH :

__PROPERTY_COUNT : 1

__DERIVATION : {}

__SERVER :

__NAMESPACE :

__PATH :

Name : Default System BIOS

USING THE BASIC WQL WHERE STATEMENT


A Where statement establishes conditions for the data that a Select statement
returns.

The Where statement has the following format:

where <property> <operator> <value>

For example:

where Name = 'Notepad.exe'

The Where statement is used with the Select statement, as shown in the
following
example.

Select * from Win32_Process where Name = 'Notepad.exe'

When using the Where statement, the property name and value must be accurate.

For example, the following command gets the Notepad processes on the local
computer.

PowerShell

Get-WmiObject -Query "Select * from Win32_Process where name='Notepad.exe'"

However, the following command fails, because the process name includes the
".exe" file
name extension.

PowerShell

Get-WmiObject -Query "Select * from Win32_Process where name='Notepad'"

WHERE STATEMENT COMPARISON OPERATORS


The following operators are valid in a WQL Where statement.
Operator Description

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

= Equal

!= Not equal

<> Not equal

< Less than

> Greater than

<= Less than or equal

>= Greater than or equal


LIKE Wildcard match

IS Evaluates null

ISNOT Evaluates not null

ISA Evaluates a member of a WMI class

There are other operators, but these are the ones used for making comparisons.

For example, the following query selects the Name and Priority properties from
processes in the Win32_Process class where the process priority is greater
than or equal
to 11. The Get-WmiObject cmdlet runs the query.

PowerShell

$highPriority = "Select Name, Priority from Win32_Process " +

"where Priority >= 11"

Get-WmiObject -Query $highPriority

USING THE WQL OPERATORS IN THE FILTER


PARAMETER
The WQL operators can also be used in the value of the Filter parameter of the
Get-
WmiObject or Get-CimInstance cmdlets, as well as in the value of the Query
parameters
of these cmdlets.

For example, the following command gets the Name and ProcessID properties of
the
last five processes that have ProcessID values greater than 1004. The
command uses the
Filter parameter to specify the ProcessID condition.

PowerShell

Get-WmiObject -Class Win32_Process `

-Property Name, ProcessID -Filter "ProcessID >= 1004" |

Sort ProcessID | Select Name, ProcessID -Last 5

Output
Name ProcessID

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

SROSVC.exe 4220

WINWORD.EXE 4664

TscHelp.exe 4744

SnagIt32.exe 4748

WmiPrvSE.exe 5056

USING THE LIKE OPERATOR


The Like operator lets you use wildcard characters to filter the results of a
WQL query.

Like Operator Description

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

[] Character in a range [a-f] or a set

of characters [abcdef]. The items in

a set do not need to be consecutive or

listed in alphabetical order.

^ Character not in a range [^a-f] or

not in a set [^abcdef]. The items in

a set do not need to be consecutive or

listed in alphabetical order.

% A string of zero or more characters

_ One character.

(underscore) NOTE: To use a literal underscore

in a query string, enclose it in

square brackets [_].

When the Like operator is used without any wildcard characters or range
operators, it
behaves like the equality operator (=) and returns objects only
when they are an exact
match for the pattern.

You can combine the range operation with the percent wildcard character to
create
simple, yet powerful filters.

LIKE OPERATOR EXAMPLES

EXAMPLE 1: [<range>]

The following commands start Notepad and then search for an instance of the
Win32_Process class that has a name that starts with a letter between "H" and
"N" (case-
insensitive).

The query should return any process from Hotpad.exe through Notepad.exe.

PowerShell

Notepad # Starts Notepad

$query = "Select * from win32_Process where Name LIKE '[H-N]otepad.exe'"

Get-WmiObject -Query $query | Select Name, ProcessID

Output

Name ProcessID

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

notepad.exe 1740

EXAMPLE 2: [<range>] and %

The following commands select all process that have a name that begins with a
letter
between A and P (case-insensitive) followed by zero or more letters in
any combination.

The Get-WmiObject cmdlet runs the query, the Select-Object cmdlet gets the
Name and
ProcessID properties, and the Sort-Object cmdlet sorts the results in
alphabetical order
by name.

PowerShell

$query = "Select * from win32_Process where name LIKE '[A-P]%'"

Get-WmiObject -Query $query |

Select-Object -Property Name, ProcessID |

Sort-Object -Property Name

EXAMPLE 3: Not in Range (^)

The following command gets processes whose names do not begin with any of the
following letters: A, S, W, P, R, C, U, N

and followed zero or more letters.

PowerShell

$query = "Select * from win32_Process where name LIKE '[^ASWPRCUN]%'"

Get-WmiObject -Query $query |

Select-Object -Property Name, ProcessID |

Sort-Object -Property Name

EXAMPLE 4: Any characters -- or none (%)


The following commands get processes that have names that begin with "calc".
The %
symbol in WQL is equivalent to the asterisk ( * ) symbol in regular
expressions.

PowerShell

$query = "Select * from win32_Process where Name LIKE 'calc%'"

Get-WmiObject -Query $query | Select-Object -Property Name, ProcessID

Output

Name ProcessID

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

calc.exe 4424

EXAMPLE 5: One character (_)

The following commands get processes that have names that have the following
pattern, "c_lc.exe" where the underscore character represents any one
character. This
pattern matches any name from calc.exe through czlc.exe, or
c9lc.exe, but does not
match names in which the "c" and "l" are separated by
more than one character.

PowerShell

$query = "Select * from Win32_Process where Name LIKE 'c_lc.exe'"

Get-WmiObject -Query $query | Select-Object -Property Name, ProcessID

Output

Name ProcessID

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

calc.exe 4424

EXAMPLE 6: Exact match


The following commands get processes named WLIDSVC.exe. Even though the query
uses the Like keyword, it requires an exact match, because the value does not
include
any wildcard characters.

PowerShell
$query = "Select * from win32_Process where name LIKE 'WLIDSVC.exe'"

Get-WmiObject -Query $query | Select-Object -Property Name, ProcessID

```powershell

```output

Name ProcessID

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

WLIDSVC.exe 84

USING THE OR OPERATOR


To specify multiple independent conditions, use the Or keyword. The Or keyword
appears in the Where clause. It performs an inclusive OR operation on two (or
more)
conditions and returns items that meet any of the conditions.

The Or operator has the following format:

Where <property> <operator> <value> or <property> <operator> <value> ...

For example, the following commands get all instances of the Win32_Process WMI
class
but returns them only if the process name is winword.exe or excel.exe.

PowerShell

$q = "Select * from Win32_Process where Name='winword.exe'" +

" or Name='excel.exe'"

Get-WmiObject -Query $q

The Or statement can be used with more than two conditions. In the following
query,
the Or statement gets Winword.exe, Excel.exe, or Powershell.exe.

PowerShell

$q = "Select * from Win32_Process where Name='winword.exe'" +

" or Name='excel.exe' or Name='powershell.exe'"

USING THE AND OPERATOR


To specify multiple related conditions, use the And keyword. The And keyword
appears
in the Where clause. It returns items that meet all of the conditions.
The And operator has the following format:

Where <property> <operator> <value> and <property> <operator> <value> ...

For example, the following commands get processes that have a name of
"Winword.exe"
and the process ID of 6512.

Note that the commands use the Get-CimInstance cmdlet.

PowerShell

$q = "Select * from Win32_Process where Name = 'winword.exe' " +

"and ProcessID =6512"

Get-CimInstance -Query $q

Output

ProcessId Name HandleCount WorkingSetSize VirtualSize

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

# 6512 WINWORD.EXE 768 117170176 633028608

All operators, including the Like operators are valid with the Or and And
operators. And,
you can combine the Or and And operators in a single query
with parentheses that tell
Windows PowerShell which clauses to process first.

This command uses the Windows PowerShell continuation character ( ` ) divide


the
command into two lines.

PowerShell

$q = "Select * from Win32_Process `

where (Name = 'winword.exe' or Name = 'excel.exe') and HandleCount > 700"

Get-CimInstance -Query $q

Output

ProcessId Name HandleCount WorkingSetSize VirtualSize

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

6512 WINWORD.EXE 797 117268480 634425344

9610 EXCEL.EXE 727 38858752 323227648

SEARCHING FOR NULL VALUES


Searching for null values in WMI is challenging, because it can lead to
unpredictable
results. Null is not zero and it is not equivalent or to an
empty string. Some WMI class
properties are initialized and others are not, so
a search for null might not work for all
properties.

To search for null values, use the Is operator with a value of "null".

For example, the following commands get processes that have a null value for
the
IntallDate property. The commands return many processes.

PowerShell

$q = "Select * from Win32_Process where InstallDate is null"

Get-WmiObject -Query $q

In contrast, the following command, gets user accounts that have a null value
for the
Description property. This command does not return any user accounts,
even though
most user accounts do not have any value for the Description
property.

PowerShell

$q = "Select * from Win32_UserAccount where Description is null"

Get-WmiObject -Query $q

To find the user accounts that have no value for the Description property, use
the
equality operator to get an empty string. To represent the empty string,
use two
consecutive single quotation marks.

PowerShell

$q = "Select * from Win32_UserAccount where Description = '' "

USING TRUE OR FALSE


To get Boolean values in the properties of WMI objects, use True and False.
They are not
case sensitive.

The following WQL query returns only local user accounts from a domain joined
computer.

PowerShell

$q = "Select * from Win32_UserAccount where LocalAccount = True"

Get-CimInstance -Query $q

To find domain accounts, use a value of False, as shown in the following


example.

PowerShell

$q = "Select * from Win32_UserAccount where LocalAccount = False"

Get-CimInstance -Query $q

USING THE ESCAPE CHARACTER


WQL uses the backslash ( \ ) as its escape character. This is different from
Windows
PowerShell, which uses the backtick character ( ` ).

Quotation marks, and the characters used for quotation marks, often need to be
escaped so that they are not misinterpreted.

To find a user whose name includes a single quotation mark, use a backslash to
escape
the single quotation mark, as shown in the following command.

PowerShell

$q = "Select * from Win32_UserAccount where Name = 'Tim O\'Brian'"


Get-CimInstance -Query $q

Output

Name Caption AccountType SID Domain

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

Tim O'Brian FABRIKAM\TimO 512 S-1-5-21-1457... FABRIKAM

In some case, the backslash also needs to be escaped. For example, the
following
commands generate an Invalid Query error due to the backslash in the
Caption value.

PowerShell

$q = "Select * from Win32_UserAccount where Caption = 'Fabrikam\TimO'"

Get-CimInstance -Query $q

Output

Get-CimInstance : Invalid query

At line:1 char:1

+ Get-CimInstance -Query $q

+ ~~~~~~~~~~~

+ CategoryInfo : InvalidArgument: (:) [Get-CimInstance], CimExcep

+ FullyQualifiedErrorId : HRESULT 0x80041017,Microsoft.Management.Infrastr

To escape the backslash, use a second backslash character, as shown in the


following
command.

PowerShell

$q = "Select * from Win32_UserAccount where Caption = 'Fabrikam\\TimO'"

Get-CimInstance -Query $q

See also
about_Special_Characters
about_Quoting_Rules
about_WMI
about_WMI_Cmdlets
Add-History
Reference
Module: Microsoft.PowerShell.Core

Appends entries to the session history.

Syntax
PowerShell

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.

The session history is a list of the commands entered during the session. The session
history
represents the order of execution, the status, and the start and end times of the
command. As you
enter each command, PowerShell adds it to the history so that you
can reuse it. For more information
about the session history, see about_History.

The session history is managed separately from the history maintained by the
PSReadLine module.
Both histories are available in sessions where PSReadLine is
loaded. This cmdlet only works with
the session history. For more information see,
about_PSReadLine.

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.

Examples
Example 1: Add commands to the history of a different
session
This example add the commands typed in one PowerShell session to the history of a
different
PowerShell session.

PowerShell

Get-History | Export-Csv c:\testing\history.csv -IncludeTypeInformation

Import-Csv c:\testing\history.csv | Add-History

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: Import and run commands


This example imports commands from the History.xml file, adds them to the current
session history,
and then runs the commands in the combined history.

PowerShell

Import-Clixml c:\temp\history.xml | Add-History -PassThru | ForEach-Object -


Process {Invoke-History}

The first command uses the Import-Clixml cmdlet to import a command history that
was exported to
the History.xml file. The pipeline operator passes the commands to
the Add-History cmdlet, 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,
enclosed in braces ( {} ), as required by the
Process parameter of the ForEach-Object cmdlet.
Example 3: Add commands in the history to the end of
the history
This example adds the first five commands in the history to the end of the history list.

PowerShell

Get-History -Id 5 -Count 5 | Add-History

The Get-History cmdlet gets 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 PowerShell
associates the objects passed through the
pipeline with the InputObject parameter of
Add-History .

Example 4: Add commands in a .csv file to the current


history
This example add the commands in the History.csv file to the current session history.

PowerShell

$a = Import-Csv c:\testing\history.csv

Add-History -InputObject $a -PassThru

The Import-Csv cmdlet imports 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, the Add-History cmdlet does not
generate any output.

Example 5: Add commands in an .xml file to the current


history
This example adds the commands in the history.xml file to the current session history.

PowerShell
Add-History -InputObject (Import-Clixml c:\temp\history.xml)

The InputObject parameter passes the results of the command in parentheses to the
Add-History
cmdlet. The command in parentheses, which is executed first, imports the
history.xml file into
PowerShell. The Add-History cmdlet then adds the commands in

the file to the session history.

Parameters
-InputObject

Specifies an array of entries to add to the history as HistoryInfo object to the session
history.
You can use this parameter to submit a HistoryInfo object, such as the ones
that are returned by
the Get-History , Import-Clixml , or Import-Csv cmdlets, to Add-
History .

Type: PSObject[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Passthru

Indicates that this cmdlet returns a HistoryInfo object for each history entry. By
default, this
cmdlet does not generate any output.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
HistoryInfo

You can pipe a HistoryInfo object to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

HistoryInfo

When you use the PassThru parameter, this cmdlet returns a HistoryInfo object.

Notes
The session history is a list of the commands entered during the session together 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, 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 returned for

each command by the


Get-History cmdlet. 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 the

Export-Csv or Export-Clixml cmdlet and then import the file by using the Import-Csv

or
Import-Clixml cmdlets. 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 the Add-History cmdlet 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
the Export-Csv cmdlet and do not delete the type
information, column headings, or any fields in
the file.

To modify the session history, export the session to a CSV or XML file, modify the file,
import the
file, and use Add-History to append it to the current session history.
Related Links
Clear-History
Get-History
Invoke-History
about_PSReadLine
Get-PSReadLineOption
Set-PSReadLineOption
Add-PSSnapin
Reference
Module: Microsoft.PowerShell.Core

Adds one or more Windows PowerShell snap-ins to the current session.

Syntax
PowerShell

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.

Beginning in Windows PowerShell 3.0, the core commands that are included in Windows
PowerShell are
packaged in modules. The exception is Microsoft.PowerShell.Core, which
is a snap-in (PSSnapin).
By default, only the Microsoft.PowerShell.Core snap-in is added
to the session. Modules are
imported automatically on first use and you can use the
Import-Module cmdlet to import them.

Examples

Example 1: Add snap-ins


PowerShell

PS C:\> Add-PSSnapIn -Name Microsoft.Exchange, Microsoft.Windows.AD


This command adds the Microsoft Exchange and Active Directory snap-ins to the current
session.

Example 2: Add all the registered snap-ins


PowerShell

PS C:\> 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: Register a snap-in and add it


The first command gets snap-ins that have been added to the current session that
include 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.

The second command gets snap-ins that have been registered on your system, which
includes those that
have already been added to the session. It does not include the
snap-ins that are installed with
Windows PowerShell. 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 of the InstallUtil tool in .NET
Framework.

The fourth command uses the InstallUtil tool to register the snap-in. The command
specifies the path
of ManagementCmdlets.dll, the filename or module name of the
snap-in.

The fifth command is the same as the second command. This time, you use it to verify
that the
ManagementCmdlets snap-in is 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.
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.

You can also use the PSSnapin property of the object that the Get-Command cmdlet
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
cmdlet.

PowerShell

PS C:\> Get-PSSnapin

PS C:\> Get-PSSnapin -Registered

PS C:\> Set-Alias installutil


$env:windir\Microsoft.NET\Framework\v2.0.50727\installutil.exe

PS C:\> installutil C:\Dev\Management\ManagementCmdlets.dll

PS C:\> Get-PSSnapin -Registered

PS C:\> add-pssnapin ManagementFeatures

PS C:\> Get-Command -Module ManagementFeatures

PS C:\> (Get-Command Set-Alias).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 that is named
ManagementCmdlets.dll.

Parameters
-Name

Specifies the name of the snap-in. This is the Name, not the AssemblyName or
ModuleName. Wildcards
are permitted.

To find the names of the registered snap-ins on your system, type Get-PSSnapin -
Registered .

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True


-PassThru

Indicates that this cmdlet returns an object that represents each added snap-in. By
default, this
cmdlet does not generate any output.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You cannot pipe objects to this cmdlet.

Outputs
None or System.Management.Automation.PSSnapInInfo

This cmdlet returns a PSSnapInInfo object that represents the snap-in if you specify the
PassThru parameter. Otherwise, this cmdlet does not generate any output.

Notes
Beginning in Windows PowerShell 3.0, the core commands that are installed with
Windows PowerShell
are packaged in modules. In Windows PowerShell 2.0, and in
host programs that create older-style
sessions in later versions of Windows
PowerShell, the core commands are packaged in snap-ins
(PSSnapins). The
exception is Microsoft.PowerShell.Core, which is always a snap-in. Also,
remote
sessions, such as those started by the New-PSSession cmdlet, are older-style
sessions that
include core snap-ins.

For information about the CreateDefault2 method that creates newer-style


sessions with core
modules, see
CreateDefault2 Method.

For more information about snap-ins, see about_PSSnapins and


How to Create a
Windows PowerShell Snap-in.
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 snap-in that has been registered using the Microsoft .NET
Framework install
utility. For more information, see
How to Register Cmdlets,
Providers, and Host Applications .

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.

Related Links
Get-PSSnapin
Remove-PSSnapin
Clear-History
Reference
Module: Microsoft.PowerShell.Core

Deletes entries from the PowerShell session command history.

Syntax
PowerShell

Clear-History

[[-Id] <int[]>]

[[-Count] <int>]

[-Newest]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Clear-History

[[-Count] <int>]

[-CommandLine <string[]>]

[-Newest]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
Clear-History deletes the command history from a PowerShell session. Each PowerShell
session has
its own command history. To display the command history, use the Get-
History cmdlet.

By default, Clear-History deletes the entire command history from a PowerShell


session. You can
use parameters with Clear-History to delete selected commands.

Clear-History does not clear the PSReadLine command history file. The PSReadLine
module stores
a history file that contains every PowerShell command from every
PowerShell session. From a
PowerShell prompt, use the up and down arrows on your
keyboard to scroll through the command
history. To display the PSReadLine
configuration for command history, use Get-PSReadLineOption .
PSReadLine shipped with
PowerShell 5.0 and above. For more information, see
about_PSReadLine.

Examples

Example 1: Delete the command history from a


PowerShell session
This command deletes all of the commands from a PowerShell session's history.

PowerShell

Get-History

Id CommandLine

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

1 Set-Location .\Test

2 Update-Help

3 Set-Location C:\Test\Logs

4 Get-Location

Clear-History

Get-History

Id CommandLine

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

5 Clear-History

The Get-History cmdlet displays the PowerShell session's history. Clear-History deletes
the
entire command history. Get-History displays the updated command history and
confirms the prior
history was deleted.

Example 2: Delete the newest commands


This command uses the Count and Newest parameters to delete the newest commands
from a
PowerShell session's history.

PowerShell

Get-History

Id CommandLine

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

1 Set-Location C:\Test\

2 Get-Command Clear-History

3 Get-Command Clear-History -Syntax

4 Get-Command Clear-History -ShowCommandInfo

5 Get-Help Get-Alias

6 Get-Command Get-ChildItem -Syntax

7 Get-Help Clear-History

8 Set-Location C:\Test\Logs

9 Get-Help Get-Variable

10 Get-Help Get-ChildItem

Clear-History -Count 5 -Newest

Get-History

Id CommandLine

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

1 Set-Location C:\Test\

2 Get-Command Clear-History

3 Get-Command Clear-History -Syntax

4 Get-Command Clear-History -ShowCommandInfo

5 Get-Help Get-Alias

11 Clear-History -Count 5 -Newest

The Get-History cmdlet displays the PowerShell session's history. Clear-History is used
to
delete the command history. The Count parameter specifies the number of
commands to delete,
inclusive of the specified Id. The Newest parameter specifies that
the newest commands are
cleared from the history. Get-History displays the updated
command history and confirms that the
five newest commands were deleted, Id 6 - Id
10.

Example 3: Delete commands that match specific criteria


This command deletes commands that match specific criteria defined by the
CommandLine parameter.

PowerShell

Get-History

Id CommandLine

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

1 Set-Location C:\Test\

2 Get-Command Clear-History

3 Get-Command Clear-History -Syntax

4 Get-Command Clear-History -ShowCommandInfo

5 Get-Help Get-Alias

6 Get-Command Get-ChildItem -Syntax

7 Get-Help Clear-History

Clear-History -CommandLine *Help*, *Syntax

Get-History

Id CommandLine

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

1 Set-Location C:\Test\

2 Get-Command Clear-History

4 Get-Command Clear-History -ShowCommandInfo

8 Clear-History -CommandLine *Help*, *Syntax

The Get-History cmdlet displays the PowerShell session's history. Clear-History deletes
the
command history. The CommandLine parameter specifies commands that contain
Help or end with
Syntax. Get-History displays the updated command history and
confirms that commands Id 3,
Id 5, Id 6, and Id 7 were deleted.

Example 4: Delete commands by Id number


This command deletes specific history items using the Id. To delete multiple commands,
submit a
comma-separated list of Id numbers.

PowerShell

Get-History

Id CommandLine

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

1 Set-Location C:\Test\

2 Get-History

3 Get-Help Get-Alias

4 Get-Command Clear-History

5 Get-Command Clear-History -Syntax

6 Get-Command Clear-History -ShowCommandInfo

Clear-History -Id 3, 5

Get-History

Id CommandLine

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

1 Set-Location C:\Test\

2 Get-History

4 Get-Command Clear-History

6 Get-Command Clear-History -ShowCommandInfo

7 Get-History

8 Clear-History -Id 3, 5

The Get-History cmdlet displays the PowerShell session's history. Clear-History deletes
the
command history. The Id parameter specifies which commands to delete. Get-
History displays the
updated command history and confirms that Id 3 and Id 5 were

deleted.
Example 5: Delete commands by Id number and count
This command uses the Id and Count parameters to delete command history.
Commands are
deleted from the specified Id in reverse order, newest to oldest.

PowerShell

Get-History

Id CommandLine

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

1 Set-Location C:\Test\

2 Get-Command Clear-History

3 Get-Command Clear-History -Syntax

4 Get-Command Clear-History -ShowCommandInfo

5 Get-Help Get-Alias

6 Get-Command Get-ChildItem -Syntax

7 Get-Help Clear-History

8 Set-Location C:\Test\Logs

9 Get-Help Get-Variable

10 Get-Help Get-ChildItem

Clear-History -Id 7 -Count 5

Get-History

Id CommandLine

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

1 Set-Location C:\Test\

2 Get-Command Clear-History

8 Set-Location C:\Test\Logs

9 Get-Help Get-Variable

10 Get-Help Get-ChildItem

11 Clear-History -Id 7 -Count 5

The Get-History cmdlet displays the PowerShell session's history. Clear-History deletes
the
command history. The Id parameter specifies to begin with Id 7. The Count
parameter
specifies to delete five commands, inclusive of the specified Id. Get-History
displays the
updated command history and confirms that five commands were deleted,
Id 3 - Id 7.

Parameters
-CommandLine

Deletes command history from a PowerShell session. The string must be an exact
match or use
wildcards to match commands in the PowerShell session history
displayed by Get-History . If you
enter more than one string, Clear-History deletes
commands that match any of the strings. The
CommandLine parameter can be used
with Count.

For strings with a space, use single quotations. For more information, see
about_Quoting_Rules.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Confirm

Prompts you for confirmation before running the Clear-History cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Count

Specifies the number of history entries that Clear-History deletes. Commands are
deleted in order,
beginning with the oldest entry in the history.

The Count and Id parameters can be used together. The Count parameter specifies
the
number of commands to delete, inclusive of the specified Id. Beginning at the
specified Id,
commands are deleted in reverse sequential order. For example, if the Id
is 30 and the Count
is 10, Clear-History deletes items 21 through 30.

The Count and CommandLine parameters can be used together. Count specifies the
number of
commands to delete that match CommandLine parameter value. The
commands are deleted in
sequential order.

Type: Int32
Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Id

Specifies the command history Id that Clear-History deletes. To display Id numbers,


use
the Get-History cmdlet. The Id numbers are sequential and commands keep
their Id number
throughout a PowerShell session. The Id parameter can be used with
Count and Newest.

Type: Int32[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Newest

When the Newest parameter is used, Clear-History deletes the newest entries in
the history. By
default, Clear-History deletes the oldest entries in the history.

The Newest parameter can be used with Id and Count. The Count parameter
specifies
the number of commands to delete, inclusive of the specified Id. Beginning
at the specified
Id, commands are deleted in sequential order. For example, if the Id
is 30 and the Count
is 10, Clear-History deletes items 30 through 39.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf
Shows what would happen if the Clear-History cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
Windows PowerShell includes the following aliases for Clear-History :

clhy

The PowerShell session history is a list of the commands entered during a PowerShell
session. You
can view the history, add and delete commands, and run commands from
the history. For more
information, see about_History.

The session history is managed separately from the history maintained by the
PSReadLine module.
Both histories are available in sessions where PSReadLine is
loaded. This cmdlet only works with
the session history. For more information see,
about_PSReadLine.

Related Links
about_History
about_PSReadLine
about_Quoting_Rules
Add-History
Get-History
Invoke-History
Get-PSReadLineOption
Set-PSReadLineOption
Clear-Host
Reference
Module: Microsoft.PowerShell.Core

Clears the display in the host program.

Syntax
PowerShell

Clear-Host

Description
The Clear-Host function removes all text from the current display, including commands
and output
that might have accumulated. When complete, it displays the command
prompt. You can use the function
name or its alias, cls .

Clear-Host affects only the current display. It does not delete saved results or remove
any items
from the session. Session-specific items, such as variables and functions, are
not affected by this
function.

Because the behavior of the Clear-Host function is determined by the host program,
Clear-Host
might work differently in different host programs.

Examples

Example 1
PowerShell

# Before

PS C:\> Get-Process

Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName

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

843 33 14428 22556 99 17.41 1688 CcmExec

44 6 2196 4964 52 0.23 692 conhost

646 12 2332 4896 49 1.12 388 csrss

189 11 2860 7084 114 0.66 2896 csrss

78 11 1876 4008 42 0.22 4000 csrss

76 7 1848 5064 54 0.08 1028 dwm

610 41 23952 44048 208 4.40 2080 explorer

0 0 0 24 0 0 Idle

182 32 7692 15980 91 0.23 3056 LogonUI

186 25 7832 16068 91 0.27 3996 LogonUI

1272 32 11512 20432 58 25.07 548 lsass

267 10 3536 6736 34 0.80 556 lsm

137 17 3520 7472 61 0.05 1220 msdtc

447 31 70316 84476 201 1,429.67 836 MsMpEng

265 18 7136 15628 134 2.20 3544 msseces

248 16 6476 4076 76 0.22 1592 NisSrv

368 25 61312 65508 614 1.78 848 powershell

101 8 2304 6624 70 0.64 3648 rdpclip

258 15 6804 12156 50 2.65 536 services

...

PS C:\> cls

#After

PS C:>

This command uses the cls alias of Clear-Host to clear the current display.

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
Windows PowerShell includes the following aliases for Clear-Host :

clear
cls

Clear-Host is a simple function, not an advanced function. There are no parameters.


Related Links
Get-Host
Out-Host
Read-Host
Write-Host
Connect-PSSession
Reference
Module: Microsoft.PowerShell.Core

Reconnects to disconnected sessions.

Syntax
PowerShell

Connect-PSSession

-Name <String[]>
[-ThrottleLimit <Int32>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Connect-PSSession

[-Session] <PSSession[]>

[-ThrottleLimit <Int32>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Connect-PSSession

[-ComputerName] <String[]>
[-ApplicationName <String>]

[-ConfigurationName <String>]

[-Name <String[]>]

[-Credential <PSCredential>]

[-Authentication <AuthenticationMechanism>]

[-CertificateThumbprint <String>]

[-Port <Int32>]

[-UseSSL]

[-SessionOption <PSSessionOption>]

[-ThrottleLimit <Int32>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell
Connect-PSSession

[-ComputerName] <String[]>
[-ApplicationName <String>]

[-ConfigurationName <String>]

-InstanceId <Guid[]>

[-Credential <PSCredential>]

[-Authentication <AuthenticationMechanism>]

[-CertificateThumbprint <String>]

[-Port <Int32>]

[-UseSSL]

[-SessionOption <PSSessionOption>]

[-ThrottleLimit <Int32>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Connect-PSSession

[-ConfigurationName <String>]

[-ConnectionUri] <Uri[]>

[-AllowRedirection]

[-Name <String[]>]

[-Credential <PSCredential>]

[-Authentication <AuthenticationMechanism>]

[-CertificateThumbprint <String>]

[-SessionOption <PSSessionOption>]

[-ThrottleLimit <Int32>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Connect-PSSession

[-ConfigurationName <String>]

[-ConnectionUri] <Uri[]>

[-AllowRedirection]

-InstanceId <Guid[]>

[-Credential <PSCredential>]

[-Authentication <AuthenticationMechanism>]

[-CertificateThumbprint <String>]

[-SessionOption <PSSessionOption>]

[-ThrottleLimit <Int32>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell
Connect-PSSession

-InstanceId <Guid[]>

[-ThrottleLimit <Int32>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Connect-PSSession

[-ThrottleLimit <Int32>]

[-Id] <Int32[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Connect-PSSession cmdlet reconnects to user-managed PowerShell sessions
(PSSessions) that
were disconnected. It works on sessions that are disconnected
intentionally, such as by using the
Disconnect-PSSession cmdlet or the
InDisconnectedSession parameter of the Invoke-Command
cmdlet, and those that were
disconnected unintentionally, such as by a temporary network outage.

Connect-PSSession can connect to any disconnected session that was started by the

same user. These


include those that were started by or disconnected from other
sessions on other computers.

However, Connect-PSSession cannot connect to broken or closed sessions, or interactive


sessions
started by using the Enter-PSSession cmdlet. Also you cannot connect sessions
to sessions started
by other users, unless you can provide the credentials of the user
who created the session.

For more information about the Disconnected Sessions feature, see


about_Remote_Disconnected_Sessions.

This cmdlet was introduced in Windows PowerShell 3.0.

Examples

Example 1: Reconnect to a session


PowerShell

Connect-PSSession -ComputerName Server01 -Name ITTask

Id Name ComputerName State ConfigurationName


Availability

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


-------

4 ITTask Server01 Opened ITTasks


Available

This command reconnects to the ITTask session on the Server01 computer.

The output shows that the command was successful. The State of the session is Opened
and the
Availability is Available , which indicates that you can run commands in the
session.

Example 2: Effect of disconnecting and reconnecting


PowerShell

Get-PSSession

Id Name ComputerName State ConfigurationName


Availability

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


-------

1 Backups Localhost Opened Microsoft.PowerShell


Available

Get-PSSession | Disconnect-PSSession

Id Name ComputerName State ConfigurationName


Availability

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


-------

1 Backups Localhost Disconnected Microsoft.PowerShell


None

Get-PSSession | Connect-PSSession

Id Name ComputerName State ConfigurationName


Availability

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


-------

1 Backups Localhost Opened Microsoft.PowerShell


Available

This example shows the effect of disconnecting and then reconnecting to a session.
The first command uses the Get-PSSession cmdlet. Without the ComputerName
parameter, the
command gets only sessions that were created in the current session.

The output shows that the command gets the Backups session on the local computer.
The State of
the session is Opened and the Availability is Available .

The second command uses the Get-PSSession cmdlet to get the PSSession objects that
were
created in the current session and the Disconnect-PSSession cmdlet to disconnect
the sessions. The
output shows that the Backups session was disconnected. The State of
the session is
Disconnected and the Availability is None .

The third command uses the Get-PSSession cmdlet to get the PSSession objects that
were created
in the current session and the Connect-PSSession cmdlet to reconnect the
sessions. The output
shows that the Backups session was reconnected. The State of the
session is Opened and the
Availability is Available .

If you use the Connect-PSSession cmdlet on a session that is not disconnected, the
command does
not affect the session and it does not generate any errors.

Example 3: Series of commands in an enterprise scenario


This series of commands shows how the Connect-PSSession cmdlet might be used in an
enterprise
scenario. In this case, a system administrator starts a long-running job in a
session on a remote
computer. After starting the job, the administrator disconnects
from the session and goes home.
Later that evening, the administrator logs on to her
home computer and verifies that the job ran
until it is completed.

The administrator starts by creating a sessions on a remote computer and running a


script in the
session.The first command uses the New-PSSession cmdlet to create the
ITTask session on the
Server01 remote computer. The command uses the

ConfigurationName parameter to specify the


ITTasks session configuration. The
command saves the sessions in the $s variable.

The second command Invoke-Command cmdlet to start a background job in the session in
the $s
variable. It uses the FilePath parameter to run the script in the background job.

The third command uses the Disconnect-PSSession cmdlet to disconnect from the
session in the $s
variable. The command uses the OutputBufferingMode parameter
with a value of Drop to prevent
the script from being blocked by having to deliver
output to the session. It uses the
IdleTimeoutSec parameter to extend the session time-
out to 15 hours. When the command is
completed, the administrator locks her
computer and goes home for the evening.

Later that evening, the administrator starts her home computer, logs on to the
corporate network,
and starts PowerShell. The fourth command uses the Get-PSSession
cmdlet to get the sessions on the
Server01 computer. The command finds the ITTask
session. The fifth command uses the
Connect-PSSession cmdlet to connect to the
ITTask session. The command saves the session in the
$s variable.

The sixth command uses the Invoke-Command cmdlet to run a Get-Job command in the
session in the
$s variable. The output shows that the job finished successfully.The
seventh command uses the
Invoke-Command cmdlet to run a Receive-Job command in
the session in the $s variable in the
session. The command saves the results in the
$BackupSpecs variable.The eighth command uses the
Invoke-Command cmdlet to runs
another script in the session. The command uses the value of the
$BackupSpecs variable
in the session as input to the script.

PowerShell

$s = New-PSSession -ComputerName Server01 -Name ITTask -ConfigurationName


ITTasks

Invoke-Command -Session $s {Start-Job -FilePath \\Server30\Scripts\Backup-


SQLDatabase.ps1}

Id Name State HasMoreData Location


Command

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


-----

2 Job2 Running True Server01


\\Server30\Scripts\Backup...

Disconnect-PSSession -Session $s -OutputBufferingMode Drop -IdleTimeoutSec


60*60*15

Id Name ComputerName State ConfigurationName


Availability

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


-------

1 ITTask Server01 Disconnected ITTasks None

Get-PSSession -ComputerName Server01 -Name ITTask

Id Name ComputerName State ConfigurationName


Availability

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


-------

1 ITTask Server01 Disconnected ITTasks None

$s = Connect-PSSession -ComputerName Server01 -Name ITTask

Id Name ComputerName State ConfigurationName


Availability

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


-------

1 ITTask Server01 Opened ITTasks


Available

Invoke-Command -Session $s {Get-Job}

Id Name State HasMoreData Location


Command

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


-----

2 Job2 Completed True Server01


\\Server30\Scripts\Backup...

Invoke-Command -Session $s {$BackupSpecs = Receive-Job -JobName Job2}

Invoke-Command -Session $s {\\Server30\Scripts\New-SQLDatabase.ps1 -InitData


$BackupSpecs.Initialization}

Disconnect-PSSession -Session $s -OutputBufferingMode Drop -IdleTimeoutSec


60*60*15

Id Name ComputerName State ConfigurationName


Availability

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


-------

1 ITTask Server01 Disconnected ITTasks None

The ninth command disconnects from the session in the $s variable.The administrator
closes
PowerShell and closes the computer. She can reconnect to the session on the
next day and check the
script status from her work computer.

Parameters
-AllowRedirection

Indicates that this cmdlet 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, PowerShell does not redirect
connections, but you can use
this parameter to allow it to redirect the connection.

You can also limit the number of times the connection is redirected by changing the
MaximumConnectionRedirectionCount session option value. Use the
MaximumRedirection parameter
of the New-PSSessionOption cmdlet or set the
MaximumConnectionRedirectionCount property of the
$PSSessionOption
preference variable. The default value is 5 .
Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ApplicationName

Specifies the name of an application. This cmdlet connects only to sessions that use
the specified
application.

Enter the application name segment of the connection URI. For example, in the
following connection
URI, the application name is WSMan:
http://localhost:5985/WSMAN . The application name of a session
is stored in the

Runspace.ConnectionInfo.AppName property of the session.

The value of this parameter is used to select and filter sessions. It does not change
the
application that the session uses.

Type: String

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Authentication

Specifies the mechanism that is used to authenticate user credentials in the


command to reconnect to
the disconnected session. The acceptable values for this
parameter are:

Default

Basic
Credssp

Digest

Kerberos
Negotiate
NegotiateWithImplicitCredential

The default value is Default .

For more information about the values of this parameter, see


AuthenticationMechanism Enumeration.

U Caution

Credential Security Support 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.

Type: AuthenticationMechanism

Accepted values: Default, Basic, Negotiate, NegotiateWithImplicitCredential,


Credssp, Digest, Kerberos

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-CertificateThumbprint

Specifies the digital public key certificate (X509) of a user account that has
permission to connect
to the disconnected session. 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 a Get-Item or Get-ChildItem command in the


PowerShell
Cert: drive.

Type: String

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-ComputerName

Specifies the computers on which the disconnected sessions are stored. Sessions are
stored on the
computer that is at the server-side or receiving end of a connection.
The default is the local
computer.

Type the NetBIOS name, an IP address, or a fully qualified domain name of one
computer. Wildcard
characters are not permitted. To specify the local computer, type
the computer name, localhost , or
a dot ( . )

Type: String[]

Aliases: Cn

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ConfigurationName

Connects only to sessions that use the specified session configuration.

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 configuration name of
a session is stored in the
ConfigurationName property of the session.

The value of this parameter is used to select and filter sessions. It does not change
the session
configuration that the session uses.

For more information about session configurations, see


about_Session_Configurations.

Type: String

Position: Named

Default value: None


Accept pipeline input: True

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-ConnectionUri

Specifies the URIs of the connection endpoints for the disconnected sessions.

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:5985/WSMAN

If you do not specify a connection URI, you can use the UseSSL and Port parameters
to
specify the connection URI values.

Valid values for the Transport segment of the URI are HTTP and HTTPS. If you specify
a
connection URI with a Transport segment, but do not specify a port, the session is
created with
standards ports: 80 for HTTP and 443 for HTTPS. To use the default
ports for PowerShell
remoting, specify port 5985 for HTTP or 5986 for HTTPS.

If the destination computer redirects the connection to a different URI, PowerShell


prevents the
redirection unless you use the AllowRedirection parameter in the
command.

Type: Uri[]

Aliases: URI, CU
Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Credential

Specifies a user account that has permission to connect to the disconnected session.
The default is
the current user.

Type a username, such as User01 or Domain01\User01 , or enter a PSCredential object


generated by the Get-Credential cmdlet. If you type a user name, you're prompted
to enter the
password.

Credentials are stored in a PSCredential


object and the password is stored as a
SecureString.

7 Note

For more information about SecureString data protection, see


How secure is
SecureString?.

Type: PSCredential

Position: Named

Default value: Current user

Accept pipeline input: False

Accept wildcard characters: False

-Id

Specifies the IDs of the disconnected sessions. The Id parameter works only when
the
disconnected session was previously connected to the current session.

This parameter is valid, but not effective, when the session is stored on the local
computer, but
was not connected to the current session.

Type: Int32[]

Position: 0
Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-InstanceId

Specifies the instance IDs of the disconnected sessions.

The instance ID is a GUID that uniquely identifies a PSSession on a local or remote


computer.

The instance ID is stored in the InstanceID property of the PSSession.

Type: Guid[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Name

Specifies the friendly names of the disconnected sessions.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Port

Specifies the network port on the remote computer that is used to reconnect to the
session. To
connect to a remote computer, the remote computer must be listening
on the port that the connection
uses. The default ports are 5985 , which is the WinRM
port for HTTP, and 5986 , which is the WinRM
port for HTTPS.
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 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 that is 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.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Session

Specifies the disconnected sessions. Enter a variable that contains the PSSession
objects or a
command that creates or gets the PSSession objects, such as a Get-
PSSession command.

Type: PSSession[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-SessionOption

Specifies advanced options for the session. Enter a SessionOption object, such as
one that you
create by using the New-PSSessionOption cmdlet, or a hash table in
which the keys are session
option names and the values are session option values.
The default values for the options are determined by the value of the
$PSSessionOption preference
variable, if it is set. Otherwise, the default values are
established by options set in the session
configuration.

The session option values take precedence over default values for sessions set in the
$PSSessionOption preference variable and in the session configuration. However,

they do not take


precedence over maximum values, quotas or limits set in the
session configuration.

For a description of the session options that includes the default values, see
New-
PSSessionOption . For information about the $PSSessionOption preference variable,
see
about_Preference_Variables. For more information about
session configurations,
see about_Session_Configurations.

Type: PSSessionOption

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ThrottleLimit

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.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-UseSSL
Indicates that this cmdlet uses the Secure Sockets Layer (SSL) protocol to connect to
the
disconnected session. By default, SSL is not used.

WS-Management encrypts all PowerShell content transmitted over the network. The
UseSSL parameter
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 that is used for the
command, the
command fails.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs.


The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSSession

You can pipe a session (PSSession) to this cmdlet.

Outputs
PSSession
This cmdlet returns an object that represents the session to which it reconnected.

Notes
Windows PowerShell includes the following aliases for Connect-PSSession :

cnsn

This cmdlet is only available on Windows platforms.

Connect-PSSession reconnects only to sessions that are disconnected, that is,


sessions that have
a value of Disconnected for the State property. Only sessions
that are connected to, or end
at, computers that run Windows PowerShell 3.0 or
later versions can be disconnected and
reconnected.

If you use Connect-PSSession on a session that is not disconnected, the command


does not affect
the session and it does not generate errors.

Disconnected loopback sessions with interactive tokens, which are created by


using the
EnableNetworkAccess parameter, can be reconnected only from the
computer on which the session
was created. This restriction protects the computer
from malicious access.

The value of the State property of a PSSession is relative to the current session.
Therefore, a value of Disconnected means that the PSSession is not connected to
the
current session. However, it does not mean that the PSSession is disconnected
from all
sessions. It might be connected to a different session. To determine
whether you can connect or
reconnect to the session, use the Availability property.

An Availability value of None indicates that you can connect to the session. A
value of Busy
indicates that you cannot connect to the PSSession because it is
connected to another session.

For more information about the values of the State property of sessions, see
RunspaceState Enumeration.

For more information about the values of the Availability property of sessions, see
RunspaceAvailability Enumeration.

You cannot change the idle time-out value of a PSSession when you connect to
the
PSSession. The SessionOption parameter of Connect-PSSession takes a
SessionOption
object that has an IdleTimeout value. However, the IdleTimeout
value of the
SessionOption object and the IdleTimeout value of the
$PSSessionOption variable are
ignored when connecting to a PSSession.

You can set and change the idle time-out of a PSSession when you create the
PSSession, by
using the New-PSSession or Invoke-Command cmdlets, and when you
disconnect from the
PSSession.

The IdleTimeout property of a PSSession is critical to disconnected sessions,


because it
determines how long a disconnected session is maintained on the
remote computer. Disconnected
sessions are considered to be idle from the
moment that they are disconnected, even if commands
are running in the
disconnected session.

Related Links
Disconnect-PSSession
Enter-PSSession
Exit-PSSession
Get-PSSession
Get-PSSessionConfiguration
New-PSSession
New-PSSessionOption
New-PSTransportOption
Receive-PSSession
Register-PSSessionConfiguration
Remove-PSSession
Debug-Job
Reference
Module: Microsoft.PowerShell.Core

Debugs a running background, remote, or Windows PowerShell Workflow job.

Syntax
PowerShell

Debug-Job

[-Job] <Job>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Debug-Job

[-Name] <String>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Debug-Job

[-Id] <Int32>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Debug-Job

[-InstanceId] <Guid>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Debug-Job cmdlet lets you debug scripts that are running within jobs. The cmdlet is
designed
to debug PowerShell Workflow jobs, background jobs, and jobs running in
remote sessions. Debug-Job
accepts a running job object, name, ID, or instance ID as
input, and starts a debugging session on
the script it is running. The debugger quit
command stops the job and running script. The exit
command detaches the debugger,
and allows the job to continue to run.

Examples

Example 1: Debug a job by job ID


This command breaks into a running job with an ID of 3.

PowerShell

Debug-Job -ID 3

Id Name PSJobTypeName State HasMoreData


Location Command

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


- -------

3 Job3 RemoteJob Running True


PowerShellIx TestWFDemo1.ps1

Entering debug mode. Use h or ? for help.

Hit Line breakpoint on 'C:\TestWFDemo1.ps1:8'

At C:\TestWFDemo1.ps1:8 char:5

+ Write-Output -InputObject "Now writing output:"

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

[DBG:PowerShellIx]: PS C:\> > list

3:

4: workflow SampleWorkflowTest

5: {

6: param ($MyOutput)

7:

8:* Write-Output -InputObject "Now writing output:"

9: Write-Output -Input $MyOutput

10:

11: Write-Output -InputObject "Get PowerShell process:"

12: Get-Process -Name powershell

13:

14: Write-Output -InputObject "Workflow function


complete."

15: }

16:

17: # Call workflow function

18: SampleWorkflowTest -MyOutput "Hello"


Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Id

Specifies the ID number of a running job. To get the ID number of a job, run the Get-
Job cmdlet.

Type: Int32

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InstanceId

Specifies the instance ID GUID of a running job.

Type: Guid

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-Job

Specifies a running job object. The simplest way to use this parameter is to save the
results of a
Get-Job command that returns the running job that you want to debug
in a variable, and then
specify the variable as the value of this parameter.

Type: Job

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies a job by the friendly name of the job. When you start a job, you can specify
a job name by
adding the JobName parameter, in cmdlets such as Invoke-Command
and Start-Job .

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


Inputs
System.Management.Automation.RemotingJob

Related Links
Get-Job
Receive-Job
Remove-Job
Resume-Job
Start-Job
Stop-Job
Suspend-Job
Wait-Job
Disable-PSRemoting
Reference
Module: Microsoft.PowerShell.Core

Prevents PowerShell endpoints from receiving remote connections.

Syntax
PowerShell

Disable-PSRemoting

[-Force]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Disable-PSRemoting cmdlet blocks remote access to all Windows PowerShell session
endpoint
configurations on the local computer. This includes any endpoints created by
PowerShell 6 or higher.

To re-enable remote access to all session configurations, use the Enable-PSRemoting


cmdlet. This
includes any endpoints created by PowerShell 6 or higher. To enable remote
access to selected
session configurations, use the AccessMode parameter of the Set-
PSSessionConfiguration cmdlet.
You can also use the Enable-PSSessionConfiguration

and Disable-PSSessionConfiguration cmdlets to


enable and disable session
configurations for all users. For more information about session
configurations, see
about_Session_Configurations.

7 Note

Even after running Disable-PSRemoting you can still make loopback connections on
the local
machine. A loopback connection is a PowerShell remote session that
originates from and connects to
the same local machine. Remote sessions from
external sources remain blocked. For loopback
connections you must use implicit
credentials along the EnableNetworkAccess parameter. For
more information
about loopback connections, see New-PSSession.
To run this cmdlet, start Windows PowerShell with the Run as administrator option.

Examples

Example 1: Prevent remote access to all session


configurations
This example prevents remote access to all PowerShell session endpoint configurations
on the computer.

PowerShell

Disable-PSRemoting

WARNING: Disabling the session configurations does not undo all the changes
made by the Enable-PSRemoting

or Enable-PSSessionConfiguration cmdlet. You might have to manually undo


the changes by following these

steps:

1. Stop and disable the WinRM service.

2. Delete the listener that accepts requests on any IP address.

3. Disable the firewall exceptions for WS-Management communications.

4. Restore the value of the LocalAccountTokenFilterPolicy to 0, which


restricts remote access to

members of the Administrators group on the computer.

Example 2: Prevent remote access to all session


configurations without confirmation prompt
This example prevents remote access all PowerShell session endpoint configurations on
the computer
without prompting.

PowerShell

Disable-PSRemoting -Force

WARNING: Disabling the session configurations does not undo all the changes
made by the Enable-PSRemoting

or Enable-PSSessionConfiguration cmdlet. You might have to manually undo


the changes by following these

steps:

1. Stop and disable the WinRM service.

2. Delete the listener that accepts requests on any IP address.

3. Disable the firewall exceptions for WS-Management communications.

4. Restore the value of the LocalAccountTokenFilterPolicy to 0, which


restricts remote access to

members of the Administrators group on the computer.

Example 3: Effects of running this cmdlet


This example shows the effect of using the Disable-PSRemoting cmdlet. To run this
command
sequence, start PowerShell with the Run as administrator option.

After disabling the sessions configurations, the New-PSSession cmdlet attempts to create
a remote
session to the local computer (also known as a "loopback"). Because remote
access is disabled on the
local machine, the command fails.

PowerShell

Disable-PSRemoting -Force

New-PSSession -ComputerName localhost

WARNING: Disabling the session configurations does not undo all the changes
made by the Enable-PSRemoting

or Enable-PSSessionConfiguration cmdlet. You might have to manually undo


the changes by following these steps:

1. Stop and disable the WinRM service.

2. Delete the listener that accepts requests on any IP address.

3. Disable the firewall exceptions for WS-Management communications.

4. Restore the value of the LocalAccountTokenFilterPolicy to 0, which


restricts remote access to

members of the Administrators group on the computer.

New-PSSession : [localhost] Connecting to remote server localhost failed


with the following error

message : Access is denied. For more information, see the


about_Remote_Troubleshooting Help topic.

At line:1 char:1

+ New-PSSession -ComputerName localhost -ConfigurationName PowerShell.6

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : OpenError:
(System.Management.A\u2026tion.RemoteRunspace:RemoteRunspace)

[New-PSSession], PSRemotingTransportException

+ FullyQualifiedErrorId : AccessDenied,PSSessionOpenFailed

Example 4: Effects of running this cmdlet and Enable-


PSRemoting
This example shows the effect on the session configurations of using the Disable-
PSRemoting and
Enable-PSRemoting cmdlets.
Disable-PSRemoting is used to disable remote access to all PowerShell session endpoint

configurations. The Force parameter suppresses all user prompts. The


Get-
PSSessionConfiguration and Format-Table cmdlets display the session configurations on

the
computer.

The output shows that all remote users with a network token are denied access to the
endpoint
configurations. Administrators group on the local computer are allowed access
to the endpoint
configurations as long as they are connecting locally (also known as
loopback) and using implicit
credentials.

PowerShell

Disable-PSRemoting -force

Get-PSSessionConfiguration | Format-Table -Property Name, Permission -Auto

Enable-PSRemoting -Force

Get-PSSessionConfiguration | Format-Table -Property Name, Permission -Auto

Name Permission

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

microsoft.powershell NT AUTHORITY\NETWORK AccessDenied,


BUILTIN\Administrators AccessAllowed

microsoft.powershell.workflow NT AUTHORITY\NETWORK AccessDenied,


BUILTIN\Administrators AccessAllowed

microsoft.powershell32 NT AUTHORITY\NETWORK AccessDenied,


BUILTIN\Administrators AccessAllowed

microsoft.ServerManager NT AUTHORITY\NETWORK AccessDenied,


BUILTIN\Administrators AccessAllowed

WithProfile NT AUTHORITY\NETWORK AccessDenied,


BUILTIN\Administrators AccessAllowed

Name Permission

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

microsoft.powershell BUILTIN\Administrators AccessAllowed

microsoft.powershell.workflow BUILTIN\Administrators AccessAllowed

microsoft.powershell32 BUILTIN\Administrators AccessAllowed

microsoft.ServerManager BUILTIN\Administrators AccessAllowed

WithProfile BUILTIN\Administrators AccessAllowed

The Enable-PSRemoting cmdlet re-enables remote access to all PowerShell session


endpoint
configurations on the computer. The Force parameter suppresses all user
prompts and restarts the
WinRM service without prompting. The new output shows that
the AccessDenied security descriptors
have been removed from all session
configurations.

Example 5: Loopback connections with disabled session


endpoint configurations
This example demonstrates how endpoint configurations are disabled, and shows how
to make a
successful loopback connection to a disabled endpoint. Disable-PSRemoting
disables all PowerShell
session endpoint configurations.

PowerShell

Disable-PSRemoting -Force

New-PSSession -ComputerName localhost

WARNING: Disabling the session configurations does not undo all the changes
made by the Enable-PSRemoting

or Enable-PSSessionConfiguration cmdlet. You might have to manually undo


the changes by following these steps:

1. Stop and disable the WinRM service.

2. Delete the listener that accepts requests on any IP address.

3. Disable the firewall exceptions for WS-Management communications.

4. Restore the value of the LocalAccountTokenFilterPolicy to 0, which


restricts remote access to

members of the Administrators group on the computer.

New-PSSession : [localhost] Connecting to remote server localhost failed


with the following error message : Access is

denied. For more information, see the about_Remote_Troubleshooting Help


topic.

At line:1 char:1

+ New-PSSession -ComputerName localhost

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : OpenError:
(System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession],
PSRemotin

gTransportException

+ FullyQualifiedErrorId : AccessDenied,PSSessionOpenFailed

New-PSSession -ComputerName localhost -EnableNetworkAccess

Id Name Transport ComputerName ComputerType State


ConfigurationName Availability

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


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

1 Runspace1 WSMan localhost RemoteMachine Opened powershell.6


Available

The first use of New-PSSession attempts to create a remote session to the local machine.
This type
of connection goes through the network stack and is not a loopback.
Consequently, the connection
attempt to the disabled endpoint fails with an Access is
denied error.

The second use of New-PSSession also attempts to create a remote session to the local
machine.
In this case, it succeeds because it is a loopback connection that bypasses the
network stack.
A loopback connection is created when the following conditions are met:

The computer name to connect to is 'localhost'.


No credentials are passed in. Current logged in user (implicit credentials) is used
for the
connection.
The EnableNetworkAccess switch parameter is used.

For more information on loopback connections, see New-PSSession document.

Example 6: Prevent remote access to session


configurations that have custom security descriptors
This example demonstrates that the Disable-PSRemoting cmdlet disables remote access
to all session
configurations that include session configurations with custom security
descriptors.

Register-PSSessionConfiguration creates the Test session configuration. The FilePath

parameter specifies a session configuration file that customizes the session. The
ShowSecurityDescriptorUI parameter displays a dialog box that sets permissions for the
session
configuration. In the Permissions dialog box, we create custom full-access
permissions for the
indicated user.

The Get-PSSessionConfiguration and Format-Table cmdlets display the session


configurations and
their properties. The output shows that the Test session
configuration allows interactive access
and special permissions for the indicated user.

Disable-PSRemoting disables remote access to all session configurations.

PowerShell

Register-PSSessionConfiguration -Name Test -FilePath .\TestEndpoint.pssc -


ShowSecurityDescriptorUI -Force

Get-PSSessionConfiguration | Format-Table -Property Name, Permission -Wrap

Disable-PSRemoting -Force

Get-PSSessionConfiguration | Format-Table -Property Name, Permission -Wrap

New-PSSession -ComputerName localhost -ConfigurationName Test

Name Permission

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

microsoft.powershell BUILTIN\Administrators AccessAllowed

Test NT AUTHORITY\INTERACTIVE AccessAllowed,


BUILTIN\Administrators AccessAllowed,

DOMAIN01\User01 AccessAllowed

WARNING: Disabling the session configurations does not undo all the changes
made by the Enable-PSRemoting

or Enable-PSSessionConfiguration cmdlet. You might have to manually undo


the changes by following these steps:

1. Stop and disable the WinRM service.

2. Delete the listener that accepts requests on any IP address.

3. Disable the firewall exceptions for WS-Management communications.

4. Restore the value of the LocalAccountTokenFilterPolicy to 0, which


restricts remote access to

members of the Administrators group on the computer.

Name Permission

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

microsoft.powershell NT AUTHORITY\NETWORK AccessDenied,


BUILTIN\Administrators AccessAllowed

Test NT AUTHORITY\NETWORK AccessDenied,


NTAUTHORITY\INTERACTIVE AccessAllowed,

BUILTIN\Administrators AccessAllowed, DOMAIN01\User01 AccessAllowed

[Server01] Connecting to remote server failed with the following error


message : Access is denied. For more information, see the about_Rem

ote_Troubleshooting Help topic.

+ CategoryInfo : OpenError:
(System.Manageme....RemoteRunspace:RemoteRunspace) [],
PSRemotingTransportException

+ FullyQualifiedErrorId : PSSessionOpenFailed

Now the Get-PSSessionConfiguration and Format-Table cmdlets shows that an


AccessDenied
security descriptor for all network users is added to all session
configurations, including the
Test session configuration. Although the other security
descriptors are not changed, the
"network_deny_all" security descriptor takes
precedence. This is illustrated by the attempt to use
New-PSSession to connect to the
Test session configuration.

Example 7: Re-enable remote access to selected session


configurations
This example shows how to re-enable remote access only to selected session
configurations. After
disabling all session configurations, we re-enable a specific session.

The Set-PSSessionConfiguration cmdlet is used to change the


microsoft.ServerManager session
configuration. The AccessMode parameter with a
value of Remote re-enables remote access to
the configuration.

PowerShell

Disable-PSRemoting -Force

Get-PSSessionConfiguration | Format-Table -Property Name, Permission -Auto

Set-PSSessionConfiguration -Name Microsoft.ServerManager -AccessMode Remote


-Force

Get-PSSessionConfiguration | Format-Table -Property Name, Permission -Auto

WARNING: Disabling the session configurations does not undo all the changes
made by the Enable-PSRemoting

or Enable-PSSessionConfiguration cmdlet. You might have to manually undo


the changes by following these steps:

1. Stop and disable the WinRM service.

2. Delete the listener that accepts requests on any IP address.

3. Disable the firewall exceptions for WS-Management communications.

4. Restore the value of the LocalAccountTokenFilterPolicy to 0, which


restricts remote access to

members of the Administrators group on the computer.

Name Permission

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

microsoft.powershell NT AUTHORITY\NETWORK AccessDenied,


BUILTIN\Administrators AccessAllowed

microsoft.powershell.workflow NT AUTHORITY\NETWORK AccessDenied,


BUILTIN\Administrators AccessAllowed

microsoft.powershell32 NT AUTHORITY\NETWORK AccessDenied,


BUILTIN\Administrators AccessAllowed

microsoft.ServerManager NT AUTHORITY\NETWORK AccessDenied,


BUILTIN\Administrators AccessAllowed

WithProfile NT AUTHORITY\NETWORK AccessDenied,


BUILTIN\Administrators AccessAllowed

Name Permission

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

microsoft.powershell NT AUTHORITY\NETWORK AccessDenied,


BUILTIN\Administrators AccessAllowed

microsoft.powershell.workflow NT AUTHORITY\NETWORK AccessDenied,


BUILTIN\Administrators AccessAllowed

microsoft.powershell32 NT AUTHORITY\NETWORK AccessDenied,


BUILTIN\Administrators AccessAllowed

microsoft.ServerManager BUILTIN\Administrators AccessAllowed

WithProfile NT AUTHORITY\NETWORK AccessDenied,


BUILTIN\Administrators AccessAllowed

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named
Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Force

Forces the command to run without asking for user confirmation.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None
This cmdlet returns no output.

Notes
Disabling the session configurations does not undo all the changes that were
made by the
Enable-PSRemoting or Enable-PSSessionConfiguration cmdlets. You
might have to undo the
following changes manually.

1. Stop and disable the WinRM service.


2. Delete the listener that accepts requests on any IP address.
3. Disable the firewall exceptions for WS-Management communications.
4. Restore the value of the LocalAccountTokenFilterPolicy to 0, which restricts
remote access to
members of the Administrators group on the computer.

A session configuration is a group of settings that define the environment for a


session. Every
session that connects to the computer must use one of the session
configurations that are
registered on the computer. By denying remote access to
all session configurations, you
effectively prevent remote users from establishing
sessions that connect to the computer.

In Windows PowerShell 2.0, Disable-PSRemoting adds a Deny_All entry to the


security descriptors
of all session configurations. This setting prevents all users
from creating user-managed sessions
to the local computer. In Windows
PowerShell 3.0, Disable-PSRemoting adds a Network_Deny_All
entry to the security
descriptors of all session configurations. This setting prevents users on
other
computers from creating user-managed sessions on the local computer, but allows
users of the
local computer to create user-managed loopback sessions.

In Windows PowerShell 2.0, Disable-PSRemoting is the equivalent of


Disable-
PSSessionConfiguration -Name * . In Windows PowerShell 3.0 and later releases,
Disable-PSRemoting is the equivalent of
Set-PSSessionConfiguration -Name \

<Configuration name\> -AccessMode Local

Related Links
Disable-PSSessionConfiguration
Enable-PSRemoting
Get-PSSessionConfiguration
New-PSSession
Register-PSSessionConfiguration
Set-PSSessionConfiguration
Unregister-PSSessionConfiguration
WSMan Provider
Disable-PSSessionConfiguration
Reference
Module: Microsoft.PowerShell.Core

Disables session configurations on the local computer.

Syntax
PowerShell

Disable-PSSessionConfiguration

[[-Name] <String[]>]

[-Force]

[-NoServiceRestart]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Disable-PSSessionConfiguration cmdlet disables session configurations on the local
computer,
which prevents all users from using the session configurations to create a
user-managed sessions
(PSSessions) 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.

Starting in PowerShell 3.0, the Disable-PSSessionConfiguration cmdlet sets the Enabled


setting
of the session configuration ( WSMan:\localhost\Plugins\
<SessionConfiguration>\Enabled ) to False.

In PowerShell 2.0, the Disable-PSSessionConfiguration cmdlet adds a Deny_All entry to


the
security descriptor of one or more registered session configurations.

Without parameters, Disable-PSSessionConfiguration disables the


Microsoft.PowerShell
configuration, the default configuration 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 .


Examples

Example 1: Disable the default configuration


This example disables the Microsoft.PowerShell session configuration.

PowerShell

Disable-PSSessionConfiguration

Example 2: Disable all registered session configurations


This example disables all registered session configurations on the computer.

PowerShell

Disable-PSSessionConfiguration -Name *

Example 3: Disable session configurations by name


This example disables all session configurations that have names that begin with
Microsoft . The
Force parameter suppresses all user prompts from the cmdlet.

PowerShell

Disable-PSSessionConfiguration -Name Microsoft* -Force

Example 4: Disable session configurations by using the


pipeline
This example disables the MaintenanceShell and AdminShell session configurations.
The
pipeline operator ( | ) sends the results of a Get-PSSessionConfiguration to
Disable-
PSSessionConfiguration .

PowerShell

Get-PSSessionConfiguration -Name MaintenanceShell, AdminShell | Disable-


PSSessionConfiguration
Example 5: Effects of disabling a session configuration
This example shows the permissions before and after running Disable-
PSSessionConfiguration and the
effect of disabling a session configuration.

PowerShell

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

PS> Disable-PSSessionConfiguration -Name MaintenanceShell -Force

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

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_Troubleshooting Help topic.

+ CategoryInfo : OpenError:
(System.Manageme....RemoteRunspace:RemoteRunspace) [],
PSRemotingTransportException

+ FullyQualifiedErrorId : PSSessionOpenFailed

7 Note

Disabling the configuration does not prevent you from changing the configuration
using the
Set-PSSessionConfiguration cmdlet. It only prevents use of the
configuration.

Parameters
-Confirm
Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Force

Forces the command to run without asking for user confirmation.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Name

Specifies an array of names of session configurations to disable. Enter one or more


configuration
names. Wildcard characters 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.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True


-NoServiceRestart

Used to prevent the restart of the WSMan service. It is not necessary to restart the
service to
disable the configuration.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
Microsoft.PowerShell.Commands.PSSessionConfigurationCommands

You can pipe a session configuration object to this cmdlet.

String

You can pipe a string that contains the name of a session configuration to this cmdlet.

Outputs
None

This cmdlet returns no output.


Notes
To run this cmdlet you must start PowerShell by using the Run as administrator option.

Related Links
Enable-PSSessionConfiguration
Get-PSSessionConfiguration
New-PSSessionConfigurationFile
Register-PSSessionConfiguration
Set-PSSessionConfiguration
Test-PSSessionConfigurationFile
Unregister-PSSessionConfiguration
WSMan Provider
about_Session_Configurations
about_Session_Configuration_Files
Disconnect-PSSession
Reference
Module: Microsoft.PowerShell.Core

Disconnects from a session.

Syntax
PowerShell

Disconnect-PSSession

[-Session] <PSSession[]>

[-IdleTimeoutSec <Int32>]

[-OutputBufferingMode <OutputBufferingMode>]

[-ThrottleLimit <Int32>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Disconnect-PSSession

[-IdleTimeoutSec <Int32>]

[-OutputBufferingMode <OutputBufferingMode>]

[-ThrottleLimit <Int32>]

-Name <String[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Disconnect-PSSession

[-IdleTimeoutSec <Int32>]

[-OutputBufferingMode <OutputBufferingMode>]

[-ThrottleLimit <Int32>]

-InstanceId <Guid[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Disconnect-PSSession

[-IdleTimeoutSec <Int32>]

[-OutputBufferingMode <OutputBufferingMode>]

[-ThrottleLimit <Int32>]

[-Id] <Int32[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Disconnect-PSSession cmdlet disconnects a PowerShell session (PSSession), such as
one
started by using the New-PSSession cmdlet, from the current session. As a result, the
PSSession is in a disconnected state. You can connect to the disconnected PSSession
from the
current session or from another session on the local computer or a different
computer.

The Disconnect-PSSession cmdlet disconnects only open PSSessions that are connected
to the
current session. Disconnect-PSSession cannot disconnect broken or closed
PSSessions, or
interactive PSSessions started by using the Enter-PSSession cmdlet, and
it cannot disconnect
PSSessions that are connected to other sessions.

To reconnect to a disconnected PSSession, use the Connect-PSSession or Receive-


PSSession
cmdlets.

When a PSSession is disconnected, the commands in the PSSession continue to run


until they
complete, unless the PSSession times out or the commands in the PSSession
are blocked by a
full output buffer. To change the idle timeout, use the IdleTimeoutSec
parameter. To change the
output buffering mode, use the OutputBufferingMode
parameter You can also use the
InDisconnectedSession parameter of the Invoke-
Command cmdlet to run a command in a
disconnected session.

For more information about the Disconnected Sessions feature, see


about_Remote_Disconnected_Sessions.

This cmdlet is introduced in Windows PowerShell 3.0.

Examples

Example 1 - Disconnect a session by name


This command disconnects the UpdateSession PSSession on the Server01 computer
from the current
session. The command uses the Name parameter to identify the
PSSession.

PowerShell

PS> Disconnect-PSSession -Name UpdateSession

Id Name ComputerName State ConfigurationName


Availability

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


-------

1 UpdateSession Server01 Disconnected Microsoft.PowerShell


None

The output shows that the attempt to disconnect was successful. The session state is
Disconnected
and the Availability is None , which indicates that the session is not busy

and can be
reconnected.

Example 2 - Disconnect a session from a specific


computer
This command disconnects the ITTask PSSession on the Server12 computer from the
current
session. The ITTask session was created in the current session and connects to
the Server12
computer. The command uses the Get-PSSession cmdlet to get the session
and the
Disconnect-PSSession cmdlet to disconnect it.

PowerShell

PS> Get-PSSession -ComputerName Server12 -Name ITTask |

Disconnect-PSSession -OutputBufferingMode Drop -IdleTimeoutSec 86400

Id Name ComputerName State ConfigurationName


Availability

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


-------

1 ITTask Server12 Disconnected ITTasks None

The Disconnect-PSSession command uses the OutputBufferingMode parameter to set


the output
mode to Drop . This setting ensures that the script that is running in the
session can continue
to run even if the session output buffer is full. Because the script
writes its output to a report
on a file share, other output can be lost without
consequence.

The command also uses the IdleTimeoutSec parameter to extend the idle timeout of
the session to
24 hours. This setting allows time for this administrator or other
administrators to reconnect to
the session to verify that the script ran and troubleshoot
if needed.
Example 3 - Using multiple PSSessions on multiple
computers
This series of commands shows how the Disconnect-PSSession cmdlet might be used in
an enterprise
scenario. In this case, a new technician starts a script in a session on a
remote computer and runs
into a problem. The technician disconnects from the session
so that a more experienced manager can
connect to the session and resolve the
problem.

PowerShell

PS> $s = New-PSSession -ComputerName Srv1, Srv2, Srv30 -Name ITTask

PS> Invoke-Command $s -FilePath \\Server01\Scripts\Get-PatchStatus.ps1

PS> Get-PSSession -Name ITTask -ComputerName Srv1 | Disconnect-PSSession

Id Name ComputerName State ConfigurationName


Availability

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


-------

1 ITTask Srv1 Disconnected Microsoft.PowerShell


None

PS> Get-PSSession -ComputerName Srv1, Srv2, Srv30 -Name ITTask

Id Name ComputerName State ConfigurationName


Availability

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


-------

1 ITTask Srv1 Disconnected Microsoft.PowerShell


None

2 ITTask Srv2 Opened Microsoft.PowerShell


Available

3 ITTask Srv30 Opened Microsoft.PowerShell


Available

PS> Get-PSSession -ComputerName Srv1 -Name ITTask -Credential


Domain01\User01

Id Name ComputerName State ConfigurationName


Availability

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


-------

1 ITTask Srv1 Disconnected Microsoft.PowerShell


None

PS> $s = Connect-PSSession -ComputerName Srv1 -Name ITTask -Credential


Domain01\User01

PS> Invoke-Command -Session $s {dir $HOME\Scripts\PatchStatusOutput.ps1}

PS> Invoke-Command -Session $s {mkdir $HOME\Scripts\PatchStatusOutput}

PS> Invoke-Command -Session $s -FilePath \\Server01\Scripts\Get-


PatchStatus.ps1

PS> Disconnect-PSSession -Session $s


The technician begins by creating sessions on several remote computers and running a
script in each
session. The first command uses the New-PSSession cmdlet to create the
ITTask session on three
remote computers. The command saves the sessions in the $s

variable. The second command uses the


FilePath parameter of the Invoke-Command
cmdlet to run a script in the sessions in the $s
variable.

The script running on the Srv1 computer generates unexpected errors. The technician
contacts his
manager and asks for assistance. The manager directs the technician to
disconnect from the session
so he can investigate.The second command uses the Get-
PSSession cmdlet to get the ITTask session
on the Srv1 computer and the Disconnect-
PSSession cmdlet to disconnect it. This command does not
affect the ITTask sessions

on the other computers.

The third command uses the Get-PSSession cmdlet to get the ITTask sessions. The
output shows
that the ITTask sessions on the Srv2 and Srv30 computers were not
affected by the command to
disconnect.

The manager logs on to his home computer, connects to his corporate network, starts
PowerShell, and
uses the Get-PSSession cmdlet to get the ITTask session on the Srv1
computer. He uses the
credentials of the technician to access the session.

Next, the manager uses the Connect-PSSession cmdlet to connect to the ITTask session
on the Srv1
computer. The command saves the session in the $s variable.

The manager uses the Invoke-Command cmdlet to run some diagnostic commands in the
session in the
$s variable. He recognizes that the script failed because it did not find a
required directory.
The manager uses the MkDir function to create the directory, and
then he restarts the
Get-PatchStatus.ps1 script and disconnects from the session.The
manager reports his findings to
the technician, suggests that he reconnect to the
session to complete the tasks, and asks him to
add a command to the Get-
PatchStatus.ps1 script that creates the required directory if it does
not exist.

Example 4 - Change the timeout value for a PSSession


This example shows how to correct the value of the IdleTimeout property of a session
so that it
can be disconnected.

The idle timeout property of a session is critical to disconnected sessions, because it


determines
how long a disconnected session is maintained before it is deleted. You can
set the idle timeout
option when you create a session and when you disconnect it. The
default values for the idle
timeout of a session are set in the $PSSessionOption
preference variable on the local computer
and in the session configuration on the
remote computer. Values set for the session take precedence
over values set in the
session configuration, but session values cannot exceed quotas set in the
session
configuration, such as the MaxIdleTimeoutMs value.

PowerShell

PS> $Timeout = New-PSSessionOption -IdleTimeout 172800000

PS> $s = New-PSSession -Computer Server01 -Name ITTask -SessionOption


$Timeout

PS> Disconnect-PSSession -Session $s

Disconnect-PSSession : The session ITTask cannot be disconnected because the


specified

idle timeout value 172800(seconds) is either greater than the server maximum
allowed

43200 (seconds) or less that the minimum allowed60(seconds). Choose an idle


time out

value that is within the allowed range and try again.

PS> Invoke-Command -ComputerName Server01 {Get-PSSessionConfiguration


Microsoft.PowerShell} |

Format-List -Property *

Architecture : 64

Filename : %windir%\system32\pwrshplugin.dll

ResourceUri :
http://schemas.microsoft.com/powershell/microsoft.powershell

MaxConcurrentCommandsPerShell : 1000

UseSharedProcess : false

ProcessIdleTimeoutSec : 0
xmlns :
http://schemas.microsoft.com/wbem/wsman/1/config/PluginConfiguration

MaxConcurrentUsers : 5
lang : en-US

SupportsOptions : true

ExactMatch : true

RunAsUser :

IdleTimeoutms : 7200000

PSVersion : 3.0

OutputBufferingMode : Block

AutoRestart : false

SecurityDescriptorSddl : O:NSG:BAD:P(A;;GA;;;BA)S:P(AU;FA;GA;;;WD)
(AU;SA;GXGW;;;WD)

MaxMemoryPerShellMB : 1024

MaxIdleTimeoutms : 2147483647

Uri :
http://schemas.microsoft.com/powershell/microsoft.powershell

SDKVersion : 2
Name : microsoft.powershell

XmlRenderingType : text

Capability : {Shell}

RunAsPassword :

MaxProcessesPerShell : 15

ParentResourceUri :
http://schemas.microsoft.com/powershell/microsoft.powershell

Enabled : true

MaxShells : 25

MaxShellsPerUser : 25

Permission : BUILTIN\Administrators AccessAllowed

PSComputerName : localhost

RunspaceId : aea84310-6dbf-4c21-90ac-13980039925a

PSShowComputerName : True

PS> $s.Runspace.ConnectionInfo

ConnectionUri : http://Server01/wsman

ComputerName : Server01

Scheme : http

Port : 80

AppName : /wsman

Credential :

ShellUri :
http://schemas.microsoft.com/powershell/Microsoft.PowerShell

AuthenticationMechanism : Default

CertificateThumbprint :

MaximumConnectionRedirectionCount : 5

MaximumReceivedDataSizePerCommand :

MaximumReceivedObjectSize : 209715200

UseCompression : True

NoMachineProfile : False

ProxyAccessType : None

ProxyAuthentication : Negotiate

ProxyCredential :

SkipCACheck : False

SkipCNCheck : False

SkipRevocationCheck : False

NoEncryption : False

UseUTF16 : False

OutputBufferingMode : Drop

IncludePortInSPN : False

Culture : en-US

UICulture : en-US

OpenTimeout : 180000

CancelTimeout : 60000

OperationTimeout : 180000

IdleTimeout : 172800000

PS> Disconnect-PSSession $s -IdleTimeoutSec 43200

Id Name ComputerName State ConfigurationName


Availability

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


-------

4 ITTask Server01 Disconnected Microsoft.PowerShell


None

PS> $s.Runspace.ConnectionInfo.IdleTimeout

43200000
The first command uses the New-PSSessionOption cmdlet to create a session option
object. It uses
the IdleTimeout parameter to set an idle timeout of 48 hours ( 172800000
milliseconds). The
command saves the session option object in the $Timeout variable.

The second command uses the New-PSSession cmdlet to create the ITTask session on
the Server01
computer. The command save the session in the $s variable. The value of
the SessionOption
parameter is the 48-hour idle timeout in the $Timeout variable.

The third command disconnects the ITTask session in the $s variable. The command
fails because
the idle timeout value of the session exceeds the MaxIdleTimeoutMs
quota in the session
configuration. Because the idle timeout is not used until the session
is disconnected, this
violation can go undetected while the session is in use.

The fourth command uses the Invoke-Command cmdlet to run a Get-


PSSessionConfiguration command
for the Microsoft.PowerShell session configuration
on the Server01 computer. The command uses the
Format-List cmdlet to display all
properties of the session configuration in a list.The output
shows that the
MaxIdleTimeoutMS property, which establishes the maximum permitted
IdleTimeout
value for sessions that use the session configuration, is 43200000 milliseconds
(12
hours).

The fifth command gets the session option values of the session in the $s variable. The
values of
many session options are properties of the ConnectionInfo property of the
Runspace property
of the session.The output shows that the value of the IdleTimeout
property of the session is
172800000 milliseconds (48 hours), which violates the
MaxIdleTimeoutMs quota of 12 hours in
the session configuration.To resolve this
conflict, you can use the ConfigurationName parameter
to select a different session
configuration or use the IdleTimeout parameter to reduce the idle
timeout of the
session.

The sixth command disconnects the session. It uses the IdleTimeoutSec parameter to
set the idle
timeout to the 12-hour maximum.

The seventh command gets the value of the IdleTimeout property of the disconnected
session,
which is measured in milliseconds. The output confirms that the command was
successful.

Parameters
-Confirm
Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Id

Disconnects from sessions with the specified session ID. Type one or more IDs
(separated by
commas), or use the range operator ( .. ) to specify a range of IDs.

To get the ID of a session, use the Get-PSSession cmdlet. The instance ID is stored in
the ID
property of the session.

Type: Int32[]

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-IdleTimeoutSec

Changes the idle timeout value of the disconnected PSSession. Enter a value in
seconds. The
minimum value is 60 (1 minute).

The idle timeout determines how long the disconnected PSSession is maintained on
the remote
computer. When the timeout expires, the PSSession is deleted.

Disconnected PSSessions are considered to be idle from the moment that they are
disconnected,
even if commands are running in the disconnected session.

The default value for the idle timeout of a session is set by the value of the
IdleTimeoutMs
property of the session configuration. The default value is 7200000
milliseconds (2 hours).
The value of this parameter takes precedence over the value of the IdleTimeout
property of the
$PSSessionOption preference variable and the default idle timeout
value in the session
configuration. However, this value cannot exceed the value of
the MaxIdleTimeoutMs property of
the session configuration. The default value of
MaxIdleTimeoutMs is 12 hours ( 43200000
milliseconds).

Type: Int32

Position: Named

Default value: 60

Accept pipeline input: False

Accept wildcard characters: False

-InstanceId

Disconnects from sessions with the specified instance IDs.

The instance ID is a GUID that uniquely identifies a session on a local or remote


computer. The
instance ID is unique, even across multiple sessions on multiple
computers.

To get the instance ID of a session, use the Get-PSSession cmdlet. The instance ID is
stored in
the InstanceID property of the session.

Type: Guid[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Disconnects from sessions with the specified friendly names. Wildcards are
permitted.

To get the friendly name of a session, use the Get-PSSession cmdlet. The friendly
name is stored
in the Name property of the session.

Type: String[]
Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-OutputBufferingMode

Determines how command output is managed in the disconnected session when the
output buffer is
full. The default value is Block .

If the command in the disconnected session is returning output and the output
buffer fills, the
value of this parameter effectively determines whether the command
continues to run while the
session is disconnected. A value of Block suspends the
command until the session is reconnected. A
value of Drop allows the command to
complete, although data might be lost. When using the Drop
value, redirect the
command output to a file on disk.

Valid values are:

Block : When the output buffer is full, execution is suspended until the buffer is
clear.
Drop : When the output buffer is full, execution continues. As new output is
saved, the oldest
output is discarded.
None : No output buffering mode is specified. The value of the

OutputBufferingMode property
of the session configuration is used for the
disconnected session.

Type: OutputBufferingMode

Position: Named

Default value: Block

Accept pipeline input: False

Accept wildcard characters: False

-Session

Disconnects from the specified PSSessions. Enter PSSession objects, such as those
that the
New-PSSession cmdlet returns. You can also pipe a PSSession object to
Disconnect-PSSession .
The Get-PSSession cmdlet can get all PSSessions that terminate at a remote
computer, including
PSSessions that are disconnected and PSSessions that are
connected to other sessions on
other computers. Disconnect-PSSession disconnects
only PSSession that are connected to the
current session. If you pipe other
PSSessions to Disconnect-PSSession , the
Disconnect-PSSession command fails.

Type: PSSession[]

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-ThrottleLimit

Sets the throttle limit for the Disconnect-PSSession command.

The throttle limit is 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.

Type: Int32

Position: Named

Default value: 32

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named
Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSSession

You can pipe a session to this cmdlet.

Outputs
PSSession

This cmdlet returns an object representing the session that it disconnected.

Notes
Windows PowerShell includes the following aliases for Disconnect-PSSession :

dnsn

The Disconnect-PSSession cmdlet works only when the local and remote
computers are running
PowerShell 3.0 or later.

If you use the Disconnect-PSSession cmdlet on a disconnected session, the


command has no effect
on the session and it does not generate errors.

Disconnected loopback sessions with interactive security tokens (those created


with the
EnableNetworkAccess parameter) can be reconnected only from the
computer on which the session
was created. This restriction protects the computer
from malicious access.

When you disconnect a PSSession, the session state is Disconnected and the
availability is
None.

The value of the State property is relative to the current session. Therefore, a value
of
Disconnected means that the PSSession is not connected to the current session.
However, it
does not mean that the PSSession is disconnected from all sessions. It
might be connected to a
different session. To determine whether you can connect
or reconnect to the session, use the
Availability property.
An Availability value of None indicates that you can connect to the session. A value
of
Busy indicates that you cannot connect to the PSSession because it is
connected to another
session.

For more information about the values of the State property of sessions, see
RunspaceState Enumeration.

For more information about the values of the Availability property of sessions, see
RunspaceAvailability Enumeration.

Related Links
Connect-PSSession
Enter-PSSession
Exit-PSSession
Get-PSSession
Get-PSSessionConfiguration
New-PSSession
New-PSSessionOption
New-PSTransportOption
Receive-PSSession
Register-PSSessionConfiguration
Remove-PSSession
about_PSSessions
about_Remote
about_Remote_Disconnected_Sessions
Enable-PSRemoting
Reference
Module: Microsoft.PowerShell.Core

Configures the computer to receive remote commands.

Syntax
PowerShell

Enable-PSRemoting

[-Force]

[-SkipNetworkProfileCheck]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Enable-PSRemoting cmdlet configures the computer to receive PowerShell remote
commands that
are sent by using the WS-Management technology.

PowerShell remoting is enabled by default on Windows Server 2012. You can use
Enable-PSRemoting
to enable PowerShell remoting on other supported versions of
Windows and to re-enable remoting on
Windows Server 2012 if it becomes disabled.

You have to run this command only one time on each computer that will receive
commands. You do not
have to run it on computers that only send commands. Because
the configuration starts listeners, it
is prudent to run it only where it is needed.

Beginning in PowerShell 3.0, the Enable-PSRemoting cmdlet can enable PowerShell


remoting
on client versions of Windows when the computer is on a public network. For
more information, see
the description of the SkipNetworkProfileCheck parameter.

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.
Registers the Microsoft.PowerShell and Microsoft.PowerShell.Workflow
session
configurations, if it they are not already registered.
Registers the Microsoft.PowerShell32 session configuration on 64-bit
computers, if it is
not already registered.
Enables all session configurations.
Changes the security descriptor of all session configurations to allow remote
access.
Restarts the WinRM service to make the preceding changes effective.

To run this cmdlet on the Windows platform, start PowerShell by using the Run as
administrator
option. This does not apply to Linux or MacOS versions of PowerShell.

U Caution

On systems that have both PowerShell 3.0 and PowerShell 2.0, do not use
PowerShell 2.0 to run the Enable-PSRemoting and Disable-PSRemoting cmdlets. The
commands
might appear to succeed, but the remoting is not configured correctly.
Remote commands and later
attempts to enable and disable remoting, are likely to
fail.

Examples

Example 1: Configure a computer to receive remote


commands
This command configures the computer to receive remote commands.

PowerShell

Enable-PSRemoting

Example 2: Configure a computer to receive remote


commands without a confirmation prompt
This command configures the computer to receive remote commands.
The Force
parameter suppresses the user prompts.

PowerShell

Enable-PSRemoting -Force
Example 3: Allow remote access on clients
This example shows how to allow remote access from public networks on client versions
of the Windows
operating system. The name of the firewall rule can be different for
different versions of Windows.
Use Get-NetFirewallRule to see a list of rules. Before
enabling the firewall rule, view the
security settings in the rule to verify that the
configuration is appropriate for your environment.

PowerShell

Get-NetFirewallRule -Name 'WINRM*' | Select-Object Name

Name

----

WINRM-HTTP-In-TCP-NoScope

WINRM-HTTP-In-TCP

WINRM-HTTP-Compat-In-TCP-NoScope

WINRM-HTTP-Compat-In-TCP

Enable-PSRemoting -SkipNetworkProfileCheck -Force

Set-NetFirewallRule -Name 'WINRM-HTTP-In-TCP' -RemoteAddress Any

By default, Enable-PSRemoting creates network rules that allow remote access from
private and
domain networks. The command uses the SkipNetworkProfileCheck
parameter to allow remote access
from public networks in the same local subnet. The
command specifies the Force parameter to
suppress confirmation messages.

The SkipNetworkProfileCheck parameter does not affect server versions of the


Windows operating
system, which allow remote access from public networks in the
same local subnet by default.

The Set-NetFirewallRule cmdlet in the NetSecurity module adds a firewall rule that
allows
remote access from public networks from any remote location. This includes
locations in different
subnets.

7 Note

The name of the firewall rule can be different depending on the version of
Windows. Use the
Get-NetFirewallRule cmdlet to list the names of the rules on
your system.
Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Force

Forces the command to run without asking for user confirmation.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SkipNetworkProfileCheck

Indicates that this cmdlet enables remoting on client versions of the Windows
operating system when
the computer is on a public network. This parameter enables
a firewall rule for public networks
that allows remote access only from computers in
the same local subnet.

This parameter does not affect server versions of the Windows operating system,
which, by default,
have a local subnet firewall rule for public networks. If the local
subnet firewall rule is
disabled on a server version, Enable-PSRemoting re-enables it,
regardless of the value of this
parameter.

To remove the local subnet restriction and enable remote access from all locations
on public
networks, use the Set-NetFirewallRule cmdlet in the NetSecurity module.
This parameter was introduced in PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs.


The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
String

This cmdlet returns strings that describe its results.

Notes
In PowerShell 3.0, Enable-PSRemoting creates the following firewall exceptions for
WS-
Management communications.
On server versions of the Windows operating system, Enable-PSRemoting creates firewall
rules
for private and domain networks that allow remote access, and creates a firewall
rule for public
networks that allows remote access only from computers in the same
local subnet.

On client versions of the Windows operating system, Enable-PSRemoting in PowerShell


3.0 creates
firewall rules for private and domain networks that allow unrestricted remote
access. To create a
firewall rule for public networks that allows remote access from the
same local subnet, use the
SkipNetworkProfileCheck parameter.

On client or server versions of the Windows operating system, to create a firewall rule
for public
networks that removes the local subnet restriction and allows remote access ,
use the
Set-NetFirewallRule cmdlet in the NetSecurity module to run the following
command:
Set-NetFirewallRule -Name "WINRM-HTTP-In-TCP-PUBLIC" -RemoteAddress Any

In PowerShell 2.0, Enable-PSRemoting creates the following firewall exceptions for WS-
Management
communications.

On server versions of the Windows operating system, it creates firewall rules for all
networks that
allow remote access.

On client versions of the Windows operating system, Enable-PSRemoting in PowerShell


2.0
creates a firewall exception only for domain and private network locations. To
minimize security
risks, Enable-PSRemoting does not create a firewall rule for public
networks on client versions
of Windows. When the current network location is public,
Enable-PSRemoting returns the following
message: Unable to check the status of the
firewall.

Starting in PowerShell 3.0, Enable-PSRemoting enables all session configurations by


setting the
value of the Enabled property of all session configurations to $True .

In PowerShell 2.0, Enable-PSRemoting removes the Deny_All setting from the security
descriptor of session configurations. In PowerShell 3.0, Enable-PSRemoting removes the
Deny_All and Network_Deny_All settings. This provides remote access to session
configurations that were reserved for local use.

Related Links
Disable-PSSessionConfiguration
Enable-PSSessionConfiguration
Get-PSSessionConfiguration
Register-PSSessionConfiguration
Set-PSSessionConfiguration
Disable-PSRemoting
WSMan Provider
about_Remote
about_Session_Configurations
Enable-PSSessionConfiguration
Reference
Module: Microsoft.PowerShell.Core

Enables the session configurations on the local computer.

Syntax
PowerShell

Enable-PSSessionConfiguration

[[-Name] <String[]>]

[-Force]

[-SecurityDescriptorSddl <String>]

[-SkipNetworkProfileCheck]

[-NoServiceRestart]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Enable-PSSessionConfiguration cmdlet enables registered session configurations
that have been
disabled, such as by using the Disable-PSSessionConfiguration or
Disable-PSRemoting cmdlets, or
the AccessMode parameter of Register-

PSSessionConfiguration . 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 enables the Microsoft.PowerShell


configuration, which is the default configuration that is used for sessions.

Enable-PSSessionConfiguration removes the Deny_All setting from the security


descriptor of the
affected session configurations, turns on the listener that accepts
requests on any IP address, and
restarts the WinRM service. Beginning in PowerShell 3.0,
Enable-PSSessionConfiguration
also sets the value of the Enabled property of the
session configuration
( WSMan:\<computer>\PlugIn\<SessionConfigurationName>\Enabled )
to True. However,
Enable-PSSessionConfiguration does not remove or change the
Network_Deny_All
( AccessMode=Local ) security descriptor setting that allows only users
of the local computer to use
to the session configuration.
Examples

Example 1: Re-enable the default session


This example re-enables the Microsoft.PowerShell default session configuration on the
computer.

PowerShell

Enable-PSSessionConfiguration

Example 2: Re-enable specified sessions


This example re-enables the MaintenanceShell and AdminShell session configurations
on the
computer.

PowerShell

Enable-PSSessionConfiguration -Name MaintenanceShell, AdminShell

Example 3: Re-enable the all sessions


This example re-enables all session configurations on the computer. These commands
are equivalent.
Therefore, you can use either.

PowerShell

Enable-PSSessionConfiguration -Name *

Get-PSSessionConfiguration | Enable-PSSessionConfiguration

Enable-PSSessionConfiguration does not generate an error if you enable a session


configuration
that is already enabled.

Example 4: Re-enable a session and specify a new security


descriptor
This example re-enables the MaintenanceShell session configuration and specifies a
new security
descriptor for the configuration.

PowerShell
$sddl = "O:NSG:BAD:P(A;;GXGWGR;;;BA)(A;;GAGR;;;S-1-5-21-123456789-188441444-
3100496)S:P"

Enable-PSSessionConfiguration -Name MaintenanceShell -SecurityDescriptorSDDL


$sddl

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Force

Indicates that the cmdlet does not prompt you for confirmation, 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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Name
Specifies the names of session configurations to enable. Enter one or more
configuration names.
Wildcard characters 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.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-NoServiceRestart

Indicates that the cmdlet does not restart the service.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SecurityDescriptorSddl

Specifies a security descriptor with which this cmdlet replaces the security descriptor
on the
session configuration.

If you omit this parameter, Enable-PSSessionConfiguration only deletes the deny all
item from the
security descriptor.

Type: String

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-SkipNetworkProfileCheck

Indicates that this cmdlet enables the session configuration when the computer is on
a public
network. This parameter enables a firewall rule for public networks that
allows remote access only
from computers in the same local subnet. By default,
Enable-PSSessionConfiguration fails on a
public network.

This parameter is designed for client versions of the Windows operating system.
Server versions of
the Windows operating system have a local subnet firewall rule for
public networks. However, if the
local subnet firewall rule is disabled on a server
version of the Windows operating system, this
parameter re-enables it.

To remove the local subnet restriction and enable remote access from all locations
on public
networks, use the Set-NetFirewallRule cmdlet in the NetSecurity module.
For more information, see
Enable-PSRemoting .

This parameter was introduced in PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


Inputs
Microsoft.PowerShell.Commands.PSSessionConfigurationCommands

You can pipe a session configuration object to this cmdlet.

String

You can pipe a string that contains the name of a session configuration to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
To use this cmdlet, you must start PowerShell by using the Run as administrator option.

Related Links
Disable-PSSessionConfiguration
Get-PSSessionConfiguration
New-PSSessionConfigurationFile
New-PSSessionOption
Register-PSSessionConfiguration
Set-PSSessionConfiguration
Test-PSSessionConfigurationFile
Unregister-PSSessionConfiguration
WSMan Provider
about_Session_Configurations
about_Session_Configuration_Files
Enter-PSHostProcess
Reference
Module: Microsoft.PowerShell.Core

Connects to and enters into an interactive session with a local process.

Syntax
PowerShell

Enter-PSHostProcess

[-Id] <Int32>

[[-AppDomainName] <String>]

[<CommonParameters>]

PowerShell

Enter-PSHostProcess

[-Process] <Process>

[[-AppDomainName] <String>]

[<CommonParameters>]

PowerShell

Enter-PSHostProcess

[-Name] <String>

[[-AppDomainName] <String>]

[<CommonParameters>]

PowerShell

Enter-PSHostProcess

[-HostProcessInfo] <PSHostProcessInfo>

[[-AppDomainName] <String>]

[<CommonParameters>]

Description
The Enter-PSHostProcess cmdlet connects to and enters into an interactive session with
a local
process.
Instead of creating a new process to host PowerShell and run a remote session, the
remote,
interactive session is run in an existing process that is already running
PowerShell. When you are
interacting with a remote session on a specified process, you
can enumerate running runspaces, and
then select a runspace to debug by running
either Debug-Runspace or Enable-RunspaceDebug .

The process that you want to enter must be hosting PowerShell


(System.Management.Automation.dll).
You must be either a member of the
Administrators group on the computer on which the process is
found, or you must be
the user who is running the script that started the process.

After you have selected a runspace to debug, a remote debug session is opened for the
runspace if it
is either currently running a command or is stopped in the debugger. You
can then debug the runspace
script in the same way you would debug other remote
session scripts.

Detach from a debugging session, and then the interactive session with the process, by
running exit
twice, or stop script execution by running the existing debugger quit
command.

If you specify a process by using the Name parameter, and there is only one process
found with
the specified name, the process is entered. If more than one process with the
specified name is
found, PowerShell returns an error, and lists all processes found with
the specified name.

To support attaching to processes on remote computers, the Enter-PSHostProcess


cmdlet is enabled
in a specified remote computer, so that you can attach to a local
process within a remote PowerShell
session.

Examples

Example Part 1: Start debugging a runspace within the


PowerShell ISE process
In this example, you run Enter-PSHostProcess from within the PowerShell console to
enter the
PowerShell ISE process. In the resulting interactive session, you can find a
runspace that you want
to debug by running Get-Runspace , and then debug the
runspace.

PowerShell
PS C:\> Enter-PSHostProcess -Name powershell_ise

[Process:1520]: PS C:\> Get-Runspace

Id Name InstanceId State


Availability

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


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

1 Runspace1 2d91211d-9cce-42f0-ab0e-71ac258b32b5 Opened


Available

2 Runspace2 a3855043-cb16-424a-a616-685360c3763b Opened


RemoteDebug

3 MyLocalRS 2236dbd8-2105-4dec-a15a-a27d0bfaacb5 Opened


LocalDebug

4 MyRunspace 771356e9-8c44-4b70-9de5-dd17cb41e48e Opened


Busy

5 Runspace8 3e517382-a97a-49ba-9c3c-fd21f6664288 Broken


None

Example part 2: Debug a specific runspace


Next, debug runspace ID 4, that is running another user's long-running script. From the
list
returned from Get-Runspace , note that the runspace State is Opened, and
Availability is
Busy, meaning that the runspace is still running the long-running script.
The runspace objects
returned by Get-Runspace also have a NoteProperty called
ScriptStackTrace of the running
command stack, if available.

PowerShell

[Process:1520]: PS C:\> (Get-Runspace -Id 4).ScriptStackTrace

Command Arguments Location

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

MyModuleWorkflowF1 {}
TestNoFile3.psm1: line 6

WFTest1 {}
TestNoFile2.ps1: line 14

TestNoFile2.ps1 {}
TestNoFile2.ps1: line 22

<ScriptBlock> {} <No file>

[Process: 1520]: PS C:\> Debug-Runspace -Id 4

Hit Line breakpoint on 'C:\TestWFVar1.ps1:83'

At C:\TestWFVar1.ps1:83 char:1

+ $scriptVar = "Script Variable"

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

[Process: 1520]: [RSDBG: 4]: PS C:\>


Start an interactive debugging session with this runspace by running the Debug-Runspace
cmdlet.

Example part 3: Finish the debugging session and exit


After you are finished debugging, allow the script to continue running without the
debugger attached
by running the exit debugger command. Alternatively, you can quit
the debugger with the q or Stop
commands.

When you are finished working in the process, exit the process by running the Exit-
PSHostProcess
cmdlet. This returns you to the PS C:\> prompt.

PowerShell

[Process:346]: [RSDBG: 3]: PS C:\> exit

[Process:1520]: PS C:\>

[Process:1520]: PS C:\> Exit-PSHostProcess

PS C:\>

Parameters
-AppDomainName

Specifies an application domain name to connect to if omitted, uses


DefaultAppDomain. Use
Get-PSHostProcessInfo to display the application domain
names.

Type: String

Position: 1

Default value: DefaultAppDomain

Accept pipeline input: False

Accept wildcard characters: False

-HostProcessInfo

Specifies a PSHostProcessInfo object that can be connected to with PowerShell. Use


Get-PSHostProcessInfo to get the object.

Type: PSHostProcessInfo
Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Id

Specifies a process by the process ID. To get a process ID, run the Get-Process
cmdlet.

Type: Int32

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Name

Specifies a process by the process name. To get a process name, run the Get-Process
cmdlet. You
can also get process names from the Properties dialog box of a process
in Task Manager.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Process

Specifies a process by the process object. The simplest way to use this parameter is
to save the
results of a Get-Process command that returns process that you want to
enter in a variable, and
then specify the variable as the value of this parameter.

Type: Process

Position: 0
Default value: None

Accept pipeline input: True

Accept wildcard characters: False

Inputs
Process

Notes
Enter-PSHostProcess cannot enter the process of the PowerShell session in which you
are running
the command. You can, however, enter the process of another PowerShell
session, or a PowerShell ISE
session that is running at the same time as the session in
which you are running
Enter-PSHostProcess .

Enter-PSHostProcess can enter only those processes that are hosting PowerShell. That is,

they have
loaded the PowerShell engine.

To exit a process from within the process, type exit, and then press Enter .

Related Links
Exit-PSHostProcess
Get-PSHostProcessInfo
Enter-PSSession
Reference
Module: Microsoft.PowerShell.Core

Starts an interactive session with a remote computer.

Syntax
PowerShell

Enter-PSSession

[-ComputerName] <String>

[-EnableNetworkAccess]

[-Credential <PSCredential>]
[-ConfigurationName <String>]

[-Port <Int32>]

[-UseSSL]

[-ApplicationName <String>]

[-SessionOption <PSSessionOption>]

[-Authentication <AuthenticationMechanism>]

[-CertificateThumbprint <String>]

[<CommonParameters>]

PowerShell

Enter-PSSession

[[-Session] <PSSession>]

[<CommonParameters>]

PowerShell

Enter-PSSession

[[-ConnectionUri] <Uri>]

[-EnableNetworkAccess]

[-Credential <PSCredential>]
[-ConfigurationName <String>]

[-AllowRedirection]

[-SessionOption <PSSessionOption>]

[-Authentication <AuthenticationMechanism>]

[-CertificateThumbprint <String>]

[<CommonParameters>]

PowerShell
Enter-PSSession

[-InstanceId <Guid>]

[<CommonParameters>]

PowerShell

Enter-PSSession

[[-Id] <Int32>]

[<CommonParameters>]

PowerShell

Enter-PSSession

[-Name <String>]

[<CommonParameters>]

PowerShell

Enter-PSSession

[-VMId] <Guid>

-Credential <PSCredential>

[-ConfigurationName <String>]

[<CommonParameters>]

PowerShell

Enter-PSSession

[-VMName] <String>

-Credential <PSCredential>

[-ConfigurationName <String>]

[<CommonParameters>]

PowerShell

Enter-PSSession

[-ContainerId] <String>

[-ConfigurationName <String>]

[-RunAsAdministrator]

[<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 if
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 the New-
PSSession cmdlet for the
interactive session. However, you cannot use the Disconnect-

PSSession , Connect-PSSession , or
Receive-PSSession cmdlets to disconnect from or re-

connect to an interactive session.

To end the interactive session and disconnect from the remote computer, use the Exit-
PSSession
cmdlet, or type exit .

Examples

Example 1: Start an interactive session


PowerShell

PS C:\> Enter-PSSession

[localhost]: PS C:\>

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: Work with an interactive session


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

PS C:\> Enter-PSSession -ComputerName Server01

[Server01]: PS C:\>

[Server01]: PS C:\> Get-Process PowerShell > C:\ps-test\Process.txt

[Server01]: PS C:\> exit

PS C:\>

PS C:\> 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

This command shows how to work in an interactive session with a remote computer.

Example 3: Use the Session parameter


PowerShell

PS> $s = New-PSSession -ComputerName Server01

PS> Enter-PSSession -Session $s

[Server01]: PS>

These commands use the Session parameter of Enter-PSSession to run the interactive
session in
an existing PowerShell session (PSSession).

Example 4: Start an interactive session and specify the


Port and Credential parameters
PowerShell

PS> Enter-PSSession -ComputerName Server01 -Port 90 -Credential


Domain01\User01

[Server01]: PS>

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 who
has permission to connect to the remote computer.

Example 5: Stop an interactive session


PowerShell
PS> Enter-PSSession -ComputerName Server01

[Server01]: PS> Exit-PSSession

PS>

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.

Parameters
-AllowRedirection

Allows redirection of this connection to an alternate Uniform Resource Identifier


(URI). By default,
redirection is not allowed.

When you use the ConnectionURI parameter, the remote destination can return an
instruction to
redirect to a different URI. By default, PowerShell does not redirect
connections, but you can use
this parameter to allow it to redirect the connection.

You can also limit the number of times the connection is redirected by changing the
MaximumConnectionRedirectionCount session option value. Use the
MaximumRedirection parameter
of the New-PSSessionOption cmdlet or set the
MaximumConnectionRedirectionCount property of the
$PSSessionOption
preference variable. The default value is 5.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-ApplicationName

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.

Type: String

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Authentication

Specifies the mechanism that is used to authenticate the user's credentials. The
acceptable values
for this parameter are:

Default
Basic
Credssp
Digest
Kerberos
Negotiate
NegotiateWithImplicitCredential

The default value is Default.

CredSSP authentication is available only in Windows Vista, Windows Server 2008,


and later versions
of the Windows operating system.

For more information about the values of this parameter, see


AuthenticationMechanism Enum.

U Caution
Credential Security Support 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.

Type: AuthenticationMechanism

Accepted values: Default, Basic, Negotiate, NegotiateWithImplicitCredential,


Credssp, Digest, Kerberos

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-CertificateThumbprint

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, use the Get-Item or Get-ChildItem command in the PowerShell


Cert: drive.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ComputerName

Specifies a computer name. This cmdlet starts an interactive session with the
specified remote
computer. Enter only one computer name. The default is the local
computer.
Type the NetBIOS name, the IP address, or the fully qualified domain name of the
computer. 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.

7 Note

On the Windows operating system, to include the local computer in the value of
the
ComputerName parameter, you must start PowerShell with the Run as
administrator option.

Type: String

Aliases: Cn

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-ConfigurationName

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.
Type: String

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-ConnectionUri

Specifies a URI that defines the connection endpoint for the 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:5985/WSMAN

If you do not specify a ConnectionURI, you can use the UseSSL, ComputerName,
Port,
and ApplicationName parameters to specify the ConnectionURI values.

Valid values for the Transport segment of the URI are HTTP and HTTPS. If you specify
a connection
URI with a Transport segment, but do not specify a port, the session is
created by using standards
ports: 80 for HTTP and 443 for HTTPS. To use the default
ports for PowerShell remoting, specify port
5985 for HTTP or 5986 for HTTPS.

If the destination computer redirects the connection to a different URI, PowerShell


prevents the
redirection unless you use the AllowRedirection parameter in the
command.

Type: Uri

Aliases: URI, CU

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-ContainerId

Specifies the ID of a container.


Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Credential

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
generated by the Get-Credential cmdlet. If you type a user name, you're
prompted to enter the
password.

Credentials are stored in a PSCredential


object and the password is stored as a
SecureString.

7 Note

For more information about SecureString data protection, see


How secure is
SecureString?.

Type: PSCredential

Position: 1

Default value: Current user

Accept pipeline input: True

Accept wildcard characters: False

-EnableNetworkAccess

Indicates that this cmdlet adds an interactive security token to loopback sessions.
The interactive
token lets you run commands in the loopback session that get data
from other computers. For example,
you can run a command in the session that
copies XML files from a remote computer to the local
computer.
A loopback session is a PSSession that originates and ends on the same computer.
To create a
loopback session, omit the ComputerName parameter or set its value to .
(dot), localhost, or the
name of the local computer.

By default, loopback sessions are created by using a network token, which might not
provide
sufficient permission to authenticate to remote computers.

The EnableNetworkAccess parameter is effective only in loopback sessions. If you


use
EnableNetworkAccess when you create a session on a remote computer, the
command succeeds, but
the parameter is ignored.

You can also allow remote access in a loopback session by using the CredSSP value
of the
Authentication parameter, which delegates the session credentials to other
computers.

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Id

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.

Type: Int32

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

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

Type: Guid

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

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.

Type: String

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Port

Specifies the network port on the remote computer that is used for this command.
To connect to a
remote computer, the remote computer must be listening on the
port that the connection uses. The
default ports are 5985, which is the WinRM port
for HTTP, and 5986, which is the WinRM port for
HTTPS.
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.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RunAsAdministrator

Indicates that the PSSession runs as administrator.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Session

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

Type: PSSession

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-SessionOption

Sets advanced options for the session. Enter a SessionOption object, such as one
that you create
by using the New-PSSessionOption cmdlet, or a hash table in which
the keys are session option
names and the values are session option values.

The default values for the options are determined by the value of the
$PSSessionOption preference
variable, if it is set. Otherwise, the default values are
established by options set in the session
configuration.

The session option values take precedence over default values for sessions set in the
$PSSessionOption preference variable and in the session configuration. However,

they do not take


precedence over maximum values, quotas or limits set in the
session configuration.

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. For more information about
session configurations,
see about_Session_Configurations.

Type: PSSessionOption

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-UseSSL

Indicates that this cmdlet 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. The UseSSL
parameter 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 that is used for the
command, the
command fails.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-VMId

Specifies the ID of a virtual machine.

Type: Guid

Aliases: VMGuid

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-VMName

Specifies the name of a virtual machine.

Type: String

Position: 0

Default value: None

Accept pipeline input: True


Accept wildcard characters: False

Inputs
String

You can pipe a computer name as a string to this cmdlet.

PSSession

You can pipe a session object to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
Windows PowerShell includes the following aliases for Enter-PSSession :

etsn

To connect to a remote computer, you must be a member of the Administrators group


on the remote
computer. To start an interactive session on the local computer, you must
start 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 PowerShell modules 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 it sends them
to the remote
computer, Enter-PSSession sends the commands directly to the remote
computer without
interpretation.

If the session you want to enter is busy processing a command, there might be a delay
before
PowerShell responds to the Enter-PSSession command. You are connected as
soon as the session
is available. To cancel the Enter-PSSession command, press CTRL +
C .

Related Links
Exit-PSSession
Get-PSSession
Invoke-Command
New-PSSession
Remove-PSSession
Connect-PSSession
Disconnect-PSSession
Receive-PSSession
about_PSSessions
about_Remote
Exit-PSHostProcess
Reference
Module: Microsoft.PowerShell.Core

Closes an interactive session with a local process.

Syntax
PowerShell

Exit-PSHostProcess []

Description
The Exit-PSHostProcess cmdlet closes an interactive session with a local process that
you have
opened by running the Enter-PSHostProcess cmdlet. You run the Exit-
PSHostProcess cmdlet from
within the process, when you are finished debugging or

troubleshooting a script that is running


within a process. Beginning in PowerShell 6.2,
this cmdlet is supported on non-Windows platforms.

Examples

Example 1: Exit a process


PowerShell

PS C:\> [Process:1520]: PS C:\> Exit-PSHostProcess

PS C:\>

In this example, you have been working in an active process to debug a script running in
a runspace
in the process, as described in Enter-PSHostProcess . After you type the exit
command to exit the
debugger, run the Exit-PSHostProcess cmdlet to close your
interactive session with the process.
The cmdlet closes your session in the process, and
returns you to the PS C:\> prompt.

Related Links
Enter-PSHostProcess
Exit-PSSession
Reference
Module: Microsoft.PowerShell.Core

Ends an interactive session with a remote computer.

Syntax
PowerShell

Exit-PSSession []

Description
The Exit-PSSession cmdlet ends interactive sessions that you started by using the
Enter-PSSession cmdlet.

You can also use the exit keyword to end an interactive session. The effect is the same
as using
Exit-PSSession .

Examples

Example 1: Start and stop an interactive session


PowerShell

PS C:\> Enter-PSSession -ComputerName Server01

Server01\PS> Exit-PSSession

PS C:\>

These commands start and then stop an interactive session with the Server01 remote
computer.

Example 2: Start and stop an interactive session by using


a PSSession object
PowerShell
PS C:\> $s = New-PSSession -ComputerName Server01

PS C:\> Enter-PSSession -Session $s

Server01\PS> Exit-PSSession

PS C:\> $s

Id Name ComputerName State ConfigurationName

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

1 Session1 Server01 Opened Microsoft.PowerShell

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, 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 Enter-PSSession to start an interactive session using the
PSSession in
$s .

The third command uses Exit-PSSession 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: Use the Exit keyword to stop a session


PowerShell

PS C:\> Enter-PSSession -ComputerName Server01

Server01\PS> exit

PS C:\>

This example uses the exit keyword to stop an interactive session started by using
Enter-PSSession . The exit keyword has the same effect as using Exit-PSSession .

Inputs
None

You can't pipe objects to this cmdlet.


Outputs
None

This cmdlet returns no output.

Notes
Windows PowerShell includes the following aliases for Exit-PSSession :

exsn

This cmdlet takes only the common parameters.

Related Links
Connect-PSSession
Disconnect-PSSession
Enter-PSSession
Get-PSSession
Invoke-Command
New-PSSession
Receive-PSSession
Remove-PSSession
Export-Console
Reference
Module: Microsoft.PowerShell.Core

Exports the names of snap-ins in the current session to a console file.

Syntax
PowerShell

Export-Console

[[-Path] <String>]

[-Force]

[-NoClobber]

[-WhatIf]

[-Confirm]

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

Examples

Example 1: Export the names of snap-ins in the current


session
PowerShell

PS C:\> 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 folder of the Windows PowerShell
installation folder, $pshome .

Example 2: Export the names of snap-ins to the most


recent console file
PowerShell

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: Add a snap-in and export the names of snap-


ins
PowerShell

Add-PSSnapin NewPSSnapin

Export-Console -path NewPSSnapinConsole.psc1

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: Export names of snap-ins to a specified
location
PowerShell

PS C:\> export-console -path Console01

PS C:\> notepad console01.psc1

<?xml version="1.0" encoding="utf-8"?>

<PSConsoleFile ConsoleSchemaVersion="1.0">

<PSVersion>2.0</PSVersion>

<PSSnapIns>

<PSSnapIn Name="NewPSSnapin" />

</PSSnapIns>

</PSConsoleFile>

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: Determine the console file to update


PowerShell

powershell.exe -PSConsoleFile Console01.psc1

Add-PSSnapin MySnapin

Export-Console NewConsole.psc1

$ConsoleFileName

Add-PSSnapin SnapIn03

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 displays the $ConsoleFileName variable. It contains 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 Export-Console 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 .

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Force

Indicates that this cmdlet 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
finishes.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-NoClobber
Indicates that this cmdlet does not overwrite an existing console file. By default, if a
file occurs
in the specified path, Export-Console overwrites the file without warning.

Type: SwitchParameter

Aliases: NoOverwrite

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Path

Specifies a path and file name for the console file ( *.psc1 ). Enter an optional path
and name.
Wildcard characters are not permitted.

If you specify only a file name, Export-Console creates a file that has 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 the console file that was used
most recently
in this session. The path of the most recently used console file is
stored in the value of the
$ConsoleFileName automatic variable. For more
information, see about_Automatic_Variables.

Type: String

Aliases: PSPath

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a path string to this cmdlet.

Outputs
FileInfo

This cmdlet 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.
Related Links
Add-PSSnapin
Get-PSSnapin
Remove-PSSnapin
Export-ModuleMember
Reference
Module: Microsoft.PowerShell.Core

Specifies the module members that are exported.

Syntax
PowerShell

Export-ModuleMember

[[-Function] <String[]>]

[-Cmdlet <String[]>]

[-Variable <String[]>]

[-Alias <String[]>]

[<CommonParameters>]

Description
The Export-ModuleMember cmdlet specifies the module members that are exported from
a script module
( .psm1 ) file, or from a dynamic module created by using the New-Module
cmdlet. Module members
include cmdlets, functions, variables, and aliases. 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


and aliases in
the script module are exported, but the variables are not. When a script
module includes
Export-ModuleMember commands, only the members specified in the
Export-ModuleMember commands are
exported. You can also use Export-ModuleMember to

suppress or export members that the script


module imports from other modules.

An Export-ModuleMember command is optional, but it is a best practice. Even if the


command
confirms the default values, it demonstrates the intention of the module
author.

Examples

Example 1: Export functions and aliases in a script module


PowerShell
Export-ModuleMember -Function * -Alias *

This command exports all the functions and aliases defined in the script module.

Example 2: Export specific aliases and functions


PowerShell

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: Export no members


PowerShell

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: Export a specific variable


PowerShell

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: Multiple export commands


PowerShell

# From TestModule.psm1

function New-Test

Write-Output 'I am New-Test function'

Export-ModuleMember -Function New-Test

function Validate-Test

Write-Output 'I am Validate-Test function'

function Start-Test

Write-Output 'I am Start-Test function'

Set-Alias stt Start-Test

Export-ModuleMember -Function Start-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 and the alias
would be
exported. With the Export-ModuleMember commands, only the New-Test and
Start-Test functions
and the STT alias are exported.

Example 6: Export members in a dynamic module


PowerShell

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.

Parameters
-Alias

Specifies the aliases that are exported from the script module file. Enter the alias
names. Wildcard
characters are permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-Cmdlet

Specifies the cmdlets that are exported from the script module file. Enter the cmdlet
names.
Wildcard characters 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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-Function

Specifies the functions that are exported from the script module file. Enter the
function names.
Wildcard characters are permitted. You can also pipe function name
strings to Export-ModuleMember .

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True


-Variable

Specifies the variables that are exported from the script module file. Enter the
variable names,
without a dollar sign character ( $ ). Wildcard characters are
permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

Inputs
String

You can pipe function name strings to this cmdlet.

Outputs
None

This cmdlet returns no 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.

Related Links
Get-Module
Import-Module
Remove-Module
about_Modules
ForEach-Object
Reference
Module: Microsoft.PowerShell.Core

Performs an operation against each item in a collection of input objects.

Syntax
PowerShell

ForEach-Object

[-InputObject <PSObject>]

[-Begin <ScriptBlock>]

[-Process] <ScriptBlock[]>

[-End <ScriptBlock>]

[-RemainingScripts <ScriptBlock[]>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

ForEach-Object

[-InputObject <PSObject>]

[-MemberName] <String>

[-ArgumentList <Object[]>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The ForEach-Object cmdlet performs an operation on each item in a collection of input
objects. The
input objects can be piped to the cmdlet or specified using the InputObject
parameter.

Starting in Windows PowerShell 3.0, there are two different ways to construct a ForEach-
Object
command.

Script block. You can use a script block to specify the operation. Within the script
block,
use the $_ variable to represent the current object. The script block is the
value of the
Process parameter. The script block can contain any PowerShell script.
For example, the following command gets the value of the ProcessName property
of each process
on the computer.

Get-Process | ForEach-Object {$_.ProcessName}

ForEach-Object supports the begin , process , and end blocks as described in


about_functions.

7 Note

The script blocks run in the caller's scope. Therefore the blocks have access to
variables in
that scope and can create new variables that persist in that scope
after the cmdlet completes.

Operation statement. You can also write an operation statement, which is much
more like
natural language. You can use the operation statement to specify a
property value or call a
method. Operation statements were introduced in
Windows PowerShell 3.0.

For example, the following command also gets the value of the ProcessName
property of each
process on the computer.

Get-Process | ForEach-Object ProcessName

Examples

Example 1: Divide integers in an array


This example takes an array of three integers and divides each one of them by 1024.

PowerShell

30000, 56798, 12432 | ForEach-Object -Process {$_/1024}

29.296875

55.466796875

12.140625

Example 2: Get the length of all the files in a directory


This example processes the files and directories in the PowerShell installation directory
$PSHOME .
PowerShell

Get-ChildItem $PSHOME |

ForEach-Object -Process {if (!$_.PSIsContainer) {$_.Name; $_.Length /


1024; " " }}

If the object is not a directory, the script block gets the name of the file, divides the
value of
its Length property by 1024, and adds a space (" ") to separate it from the next
entry. The
cmdlet uses the PSISContainer property to determine whether an object is a
directory.

Example 3: Operate on the most recent System events


This example writes the 1000 most recent events from the System event log to a text file.
The
current time is displayed before and after processing the events.

PowerShell

$Events = Get-EventLog -LogName System -Newest 1000

$events | ForEach-Object -Begin {Get-Date} -Process {Out-File -FilePath


Events.txt -Append -InputObject $_.Message} -End {Get-Date}

Get-EventLog gets the 1000 most recent events from the System event log and stores

them in the
$Events variable. $Events is then piped 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 that is 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 the processing
has completed.

Example 4: Change the value of a Registry key


This example changes the value of the RemotePath registry entry in all the subkeys
under the
HKCU:\Network key to uppercase text.

PowerShell

Get-ItemProperty -Path HKCU:\Network\* |

ForEach-Object {Set-ItemProperty -Path $_.PSPath -Name RemotePath -Value


$_.RemotePath.ToUpper();}

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 reconnects at
sign on. The
RemotePath entry contains the UNC path of the connected drive. For
example, if you map the E:
drive to \\Server\Share , an E subkey is created in
HKCU:\Network with the RemotePath
registry value set to \\Server\Share .

The command uses the Get-ItemProperty cmdlet to get all 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, 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.

Example 5: Use the $null automatic variable


This example shows the effect of piping the $null automatic variable to the ForEach-
Object
cmdlet.

PowerShell

1, 2, $null, 4 | ForEach-Object {"Hello"}

Hello

Hello

Hello

Hello

Because PowerShell treats $null as an explicit placeholder, the ForEach-Object cmdlet


generates
a value for $null as it does for other objects piped to it.

Example 6: Get property values


This example gets the value of the Path property of all installed PowerShell modules by
using
the MemberName parameter of the ForEach-Object cmdlet.

PowerShell

Get-Module -ListAvailable | ForEach-Object -MemberName Path

Get-Module -ListAvailable | Foreach Path


The second command is equivalent to the first. It uses the Foreach alias of the ForEach-
Object
cmdlet and omits the name of the MemberName parameter, which is optional.

The ForEach-Object cmdlet is useful for getting property values, because it gets the
value without
changing the type, unlike the Format cmdlets or the Select-Object
cmdlet, which change the
property value type.

Example 7: Split module names into component names


This example shows three ways to split two dot-separated module names into their
component names.
The commands call the Split method of strings. The three
commands use different syntax, but they
are equivalent and interchangeable. The
output is the same for all three cases.

PowerShell

"Microsoft.PowerShell.Core", "Microsoft.PowerShell.Host" | ForEach-Object


{$_.Split(".")}

"Microsoft.PowerShell.Core", "Microsoft.PowerShell.Host" | ForEach-Object -


MemberName Split -ArgumentList "."

"Microsoft.PowerShell.Core", "Microsoft.PowerShell.Host" | Foreach Split "."

Microsoft

PowerShell

Core

Microsoft

PowerShell

Host

The first command uses the traditional syntax, which includes a script block and the
current object
operator $_ . It uses the dot syntax to specify the method and
parentheses to enclose the delimiter
argument.

The second command uses the MemberName parameter to specify the Split method
and the
ArgumentList parameter to identify the dot ( . ) as the split delimiter.

The third command uses the Foreach alias of the ForEach-Object cmdlet and omits the
names of
the MemberName and ArgumentList parameters, which are optional.

Example 8: Using ForEach-Object with two script blocks


In this example, we pass two script blocks positionally. All the script blocks bind to the
Process parameter. However, they are treated as if they had been passed to the Begin
and
Process parameters.
PowerShell

1..2 | ForEach-Object { 'begin' } { 'process' }

begin

process

process

Example 9: Using ForEach-Object with more than two


script blocks
In this example, we pass four script blocks positionally. All the script blocks bind to the
Process parameter. However, they are treated as if they had been passed to the Begin,
Process, and End parameters.

PowerShell

1..2 | ForEach-Object { 'begin' } { 'process A' } { 'process B' } { 'end'


}

begin

process A

process B

process A

process B

end

7 Note

The first script block is always mapped to the begin block, the last block is mapped
to the
end block, and the blocks in between are all mapped to the process block.

Example 10: Run multiple script blocks for each pipeline


item
As shown in the previous example, multiple script blocks passed using the Process
parameter get
mapped to the Begin and End parameters. To avoid this mapping, you
must provide explicit
values for the Begin and End parameters.

PowerShell

1..2 | ForEach-Object -Begin $null -Process { 'one' }, { 'two' }, { 'three'


} -End $null

one

two

three

one

two

three

Parameters
-ArgumentList

Specifies an array of arguments to a method call. For more information about the
behavior of
ArgumentList, see about_Splatting.

This parameter was introduced in Windows PowerShell 3.0.

Type: Object[]

Aliases: Args

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Begin

Specifies a script block that runs before this cmdlet processes any input objects. This
script block
is only run once for the entire pipeline. For more information about the
begin block, see
about_Functions.

Type: ScriptBlock

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Confirm
Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-End

Specifies a script block that runs after this cmdlet processes all input objects. This
script block
is only run once for the entire pipeline. For more information about the
end block, see
about_Functions.

Type: ScriptBlock

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies the input objects. ForEach-Object runs the script block or operation
statement on each
input object. Enter a variable that contains the objects, or type a
command or expression that gets
the objects.

When you use the InputObject parameter with ForEach-Object , instead of piping
command results
to ForEach-Object , the InputObject value is treated as a single
object. This is true even if
the value is a collection that is the result of a command,
such as -InputObject (Get-Process) .
Because InputObject cannot return individual
properties from an array or collection of objects,
we recommend that if you use
ForEach-Object to perform operations on a collection of objects for
those objects
that have specific values in defined properties, you use ForEach-Object in the
pipeline, as shown in the examples in this topic.

Type: PSObject
Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-MemberName

Specifies the property to get or the method to call.

Wildcard characters are permitted, but work only if the resulting string resolves to a
unique value.
For example, if you run Get-Process | ForEach -MemberName *Name , the
wildcard pattern matches more
than one member causing the command to fail.

This parameter was introduced in Windows PowerShell 3.0.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Process

Specifies the operation that is performed on each input object. This script block is
run for every
object in the pipeline. For more information about the process block,
see
about_Functions.

When you provide multiple script blocks to the Process parameter, the first script
block is
always mapped to the begin block. If there are only two script blocks, the
second block is mapped
to the process block. If there are three or more script
blocks, first script block is always
mapped to the begin block, the last block is
mapped to the end block, and the blocks in between
are all mapped to the process
block.

Type: ScriptBlock[]

Position: 0

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-RemainingScripts

Specifies all script blocks that are not taken by the Process parameter.

This parameter was introduced in Windows PowerShell 3.0.

Type: ScriptBlock[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSObject

You can pipe any object to this cmdlet.

Outputs
PSObject

This cmdlet returns objects that are determined by the input.


Notes
Windows PowerShell includes the following aliases for ForEach-Object :

foreach

The ForEach-Object cmdlet works much like the Foreach statement, except that you
cannot pipe
input to a Foreach statement. For more information about the Foreach
statement, see
about_Foreach.

Starting in PowerShell 4.0, Where and ForEach methods were added for use with
collections. You
can read more about these new methods here about_arrays

Related Links
Compare-Object
Where-Object
Group-Object
Measure-Object
New-Object
Select-Object
Sort-Object
Tee-Object
Get-Command
Reference
Module: Microsoft.PowerShell.Core

Gets all commands.

Syntax
PowerShell

Get-Command

[-Verb <String[]>]

[-Noun <String[]>]

[-Module <String[]>]

[-FullyQualifiedModule <ModuleSpecification[]>]

[-TotalCount <Int32>]

[-Syntax]

[-ShowCommandInfo]

[[-ArgumentList] <Object[]>]

[-All]

[-ListImported]

[-ParameterName <String[]>]

[-ParameterType <PSTypeName[]>]

[<CommonParameters>]

PowerShell

Get-Command

[[-Name] <String[]>]

[-Module <String[]>]

[-FullyQualifiedModule <ModuleSpecification[]>]

[-CommandType <CommandTypes>]

[-TotalCount <Int32>]

[-Syntax]

[-ShowCommandInfo]

[[-ArgumentList] <Object[]>]

[-All]

[-ListImported]

[-ParameterName <String[]>]

[-ParameterType <PSTypeName[]>]

[<CommonParameters>]

Description
The Get-Command cmdlet gets all commands that are installed on the computer,
including cmdlets,
aliases, functions, filters, scripts, and applications. Get-Command gets
the commands from
PowerShell modules and commands that were imported from other
sessions. To get only commands that
have been imported into the current session, use
the ListImported parameter.

Without parameters, Get-Command gets all of the cmdlets, functions, and aliases installed
on the
computer. Get-Command * gets all types of commands, including all of the non-
PowerShell files in
the Path environment variable ( $env:Path ), which it lists in the
Application command type.

Get-Command that uses the exact name of the command, without wildcard characters,

automatically
imports the module that contains the command so that you can use the
command immediately. To enable,
disable, and configure automatic importing of
modules, use the $PSModuleAutoLoadingPreference
preference variable. For more
information, see about_Preference_Variables.

Get-Command gets its data directly from the command code, unlike Get-Help , which gets

its
information from help topics.

Starting in Windows PowerShell 5.0, results of the Get-Command cmdlet display a Version
column
by default. A new Version property has been added to the CommandInfo class.

Examples

Example 1: Get cmdlets, functions, and aliases


This command gets the PowerShell cmdlets, functions, and aliases that are installed on
the computer.

PowerShell

Get-Command

Example 2: Get commands in the current session


This command uses the ListImported parameter to get only the commands in the
current session.

PowerShell
Get-Command -ListImported

Example 3: Get cmdlets and display them in order


This command gets 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.

PowerShell

Get-Command -Type Cmdlet | Sort-Object -Property Noun | Format-Table -


GroupBy Noun

Example 4: Get commands in a module


This command uses the Module parameter to get the commands in the
Microsoft.PowerShell.Security
and Microsoft.PowerShell.Utility modules.

PowerShell

Get-Command -Module Microsoft.PowerShell.Security,


Microsoft.PowerShell.Utility

Example 5: Get information about a cmdlet


This command gets information about the Get-AppLockerPolicy cmdlet. It also imports
the
AppLocker module, which adds all of the commands in the AppLocker module to
the current
session.

PowerShell

Get-Command Get-AppLockerPolicy

When a module is imported automatically, the effect is the same as using the Import-
Module cmdlet.
The module can add commands, types and formatting files, and run
scripts in the session. To enable,
disable, and configuration automatic importing of
modules, use the $PSModuleAutoLoadingPreference
preference variable. For more
information, see about_Preference_Variables.
Example 6: Get the syntax of a cmdlet
This command uses the ArgumentList and Syntax parameters to get the syntax of the
Get-ChildItem cmdlet when it is used in the Cert: drive. The Cert: drive is a PowerShell

drive
that the Certificate Provider adds to the session.

PowerShell

Get-Command -Name Get-Childitem -Args Cert: -Syntax

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 adds a dynamic
parameter, CodeSigningCert, to the Get-ChildItem cmdlet.

For more information about the Certificate provider, see about_Certificate_Provider.

Example 7: Get dynamic parameters


The command in the example uses the Get-DynamicParameters function to get the
dynamic parameters
that the Certificate provider adds to the Get-ChildItem cmdlet
when it is used in the Cert: drive.

PowerShell

function Get-DynamicParameters

param ($Cmdlet, $PSDrive)

(Get-Command -Name $Cmdlet -ArgumentList $PSDrive).ParameterSets |

ForEach-Object {$_.Parameters} |

Where-Object { $_.IsDynamic } |

Select-Object -Property Name -Unique

Get-DynamicParameters -Cmdlet Get-ChildItem -PSDrive Cert:

Name

----

CodeSigningCert

The Get-DynamicParameters function in this example gets the dynamic parameters of a


cmdlet. This
is an alternative to the method used in the previous example. Dynamic
parameter can be added to a
cmdlet by another cmdlet or a provider.

Example 8: Get all commands of all types


This command gets all commands of all types on the local computer, including
executable files in the
paths of the Path environment variable ( $env:path ).

PowerShell

Get-Command *

It returns an ApplicationInfo object (System.Management.Automation.ApplicationInfo)


for each
file, not a FileInfo object (System.IO.FileInfo).

Example 9: Get cmdlets by using a parameter name and


type
This command gets cmdlets that have a parameter whose name includes Auth and
whose type is
AuthenticationMechanism.

PowerShell

Get-Command -ParameterName *Auth* -ParameterType AuthenticationMechanism

You can use a command like this one to find cmdlets that let you specify the method
that is used to
authenticate the user.

The ParameterType parameter distinguishes parameters that take an


AuthenticationMechanism
value from those that take an AuthenticationLevel
parameter, even when they have similar names.

Example 10: Get an alias


This example shows how to use the Get-Command cmdlet with an alias.

PowerShell

Get-Command -Name dir

CommandType Name
ModuleName

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


-

Alias dir -> Get-ChildItem

Although it is typically used on cmdlets and functions, Get-Command also gets scripts,
functions,
aliases, and executable files.
The output of the command shows the special view of the Name property value for
aliases. The
view shows the alias and the full command name.

Example 11: Get all instances of the Notepad command


This example uses the All parameter of the Get-Command cmdlet to show all instances of
the
Notepad command on the local computer.

PowerShell

Get-Command Notepad -All | Format-Table CommandType, Name, Definition

CommandType Name Definition

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

Application notepad.exe C:\WINDOWS\system32\notepad.exe

Application NOTEPAD.EXE C:\WINDOWS\NOTEPAD.EXE

The All parameter is useful when there is more than one command with the same name
in the
session.

Beginning in Windows PowerShell 3.0, by default, when the session includes multiple
commands with
the same name, Get-Command gets only the command that runs when
you type the command name. With
the All parameter, Get-Command gets all commands
with the specified name and returns them in
execution precedence order. To run a
command other than the first one in the list, type the fully
qualified path to the
command.

For more information about command precedence, see about_Command_Precedence.

Example 12: Get the name of a module that contains a


cmdlet
This command gets the name of the module in which the Get-Date cmdlet originated.
The command uses the ModuleName property of all commands.

PowerShell

(Get-Command Get-Date).ModuleName

Microsoft.PowerShell.Utility

This command format works on commands in PowerShell modules, even if they are not
imported into the
session.
Example 13: Get cmdlets and functions that have an
output type
PowerShell

Get-Command -Type Cmdlet | Where-Object OutputType | Format-List -Property


Name, OutputType

This command gets the cmdlets and functions that have an output type and the type of
objects that
they return.

The first part of the command gets all cmdlets. A pipeline operator ( | ) sends the
cmdlets to the
Where-Object cmdlet, which selects only the ones in which the
OutputType property is
populated. Another pipeline operator sends the selected cmdlet
objects to the Format-List cmdlet,
which displays the name and output type of each
cmdlet in a list.

The OutputType property of a CommandInfo object has a non-null value only when the
cmdlet
code defines the OutputType attribute for the cmdlet.

Example 14: Get cmdlets that take a specific object type


as input
PowerShell

Get-Command -ParameterType (((Get-NetAdapter)[0]).PSTypeNames)

CommandType Name
ModuleName

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


-

Function Disable-NetAdapter
NetAdapter

Function Enable-NetAdapter
NetAdapter

Function Rename-NetAdapter
NetAdapter

Function Restart-NetAdapter
NetAdapter

Function Set-NetAdapter
NetAdapter

This command finds cmdlets that take net adapter objects as input. You can use this
command format
to find the cmdlets that accept the type of objects that any command
returns.
The command uses the PSTypeNames intrinsic property of all objects, which gets the
types that
describe the object. To get the PSTypeNames property of a net adapter, and
not the
PSTypeNames property of a collection of net adapters, the command uses array
notation to get the
first net adapter that the cmdlet returns. To get the PSTypeNames
property of a net adapter, and
not the PSTypeNames property of a collection of net
adapters, the command uses array notation to
get the first net adapter that the cmdlet
returns.

Parameters
-All

Indicates that this cmdlet gets all commands, including commands of the same type
that have the same
name. By default, Get-Command gets only the commands that run
when you type the command name.

For more information about the method that PowerShell uses to select the command
to run when
multiple commands have the same name, see
about_Command_Precedence.
For information about module-qualified command
names and running commands that do not run by default
because of a name
conflict, see about_Modules.

This parameter was introduced in Windows PowerShell 3.0.

In Windows PowerShell 2.0, Get-Command gets all commands by default.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: True

Accept wildcard characters: False

-ArgumentList

Specifies an array of arguments. This cmdlet gets information about a cmdlet or


function when it is
used with the specified parameters ("arguments"). The alias for
ArgumentList is Args.

To detect dynamic parameters that are available only when certain other parameters
are used, set the
value of ArgumentList to the parameters that trigger the dynamic
parameters.

To detect the dynamic parameters that a provider adds to a cmdlet, set the value of
the
ArgumentList parameter to a path in the provider drive, such as WSMan:, HKLM:,
or Cert:. When
the command is a PowerShell provider cmdlet, enter only one path in
each command. The provider
cmdlets return only the dynamic parameters for the
first path the value of ArgumentList. For
information about the provider cmdlets, see
about_Providers.

Type: Object[]

Aliases: Args

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-CommandType

Specifies the types of commands that this cmdlet gets. Enter one or more command
types. Use
CommandType or its alias, Type. By default, Get-Command gets all cmdlets,
functions, and
aliases.

The acceptable values for this parameter are:

Alias : Gets the aliases of all PowerShell commands. For more information, see

about_Aliases.

All : Gets all command types. This parameter value is the equivalent of Get-
Command * .

Application : Gets non-PowerShell files in paths listed in the Path environment


variable
( $env:path ), including .txt , .exe , and .dll files. For more
information about the Path
environment variable, see
about_Environment_Variables.

Cmdlet : Gets all cmdlets.

ExternalScript : Gets all .ps1 files in the paths listed in the Path environment
variable
( $env:path ).
Filter and Function : Gets all PowerShell advanced and simple functions and

filters.

Script : Gets all script blocks. To get PowerShell scripts ( .ps1 files), use the

ExternalScript value.

Workflow : Gets all workflows. For more information about workflows, see

Introducing Windows
PowerShell Workflow.

These values are defined as a flag-based enumeration. You can combine multiple
values together to
set multiple flags using this parameter. The values can be passed
to the CommandType parameter
as an array of values or as a comma-separated
string of those values. The cmdlet will combine the
values using a binary-OR
operation. Passing values as an array is the simplest option and also
allows you to
use tab-completion on the values.

Type: CommandTypes

Aliases: Type

Accepted values: Alias, Function, Filter, Cmdlet, ExternalScript, Application,


Script, Workflow, Configuration, All

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-FullyQualifiedModule

The value can be a module name, a full module specification, or a path to a module
file.

When the value is a path, the path can be fully qualified or relative. A relative path is
resolved
relative to the script that contains the using statement.

When the value is a name or module specification, PowerShell searches the


PSModulePath for the
specified module.

A module specification is a hashtable that has the following keys.

ModuleName - Required Specifies the module name.

GUID - Optional Specifies the GUID of the module.


It's also Required to specify at least one of the three below keys.

ModuleVersion - Specifies a minimum acceptable version of the module.

MaximumVersion - Specifies the maximum acceptable version of the module.

RequiredVersion - Specifies an exact, required version of the module. This


can't be used with
the other Version keys.

You cannot specify the FullyQualifiedModule parameter in the same command as a


Module
parameter. The two parameters are mutually exclusive.

Type: ModuleSpecification[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-ListImported

Indicates that this cmdlet gets only commands in the current session.

Starting in PowerShell 3.0, by default, Get-Command gets all installed commands,


including, but
not limited to, the commands in the current session. In PowerShell 2.0,
it gets only commands in the
current session.

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Module

Specifies an array of modules. This cmdlet gets the commands that came from the
specified modules or
snap-ins. Enter the names of modules or snap-ins.
This parameter takes string values, but the value of this parameter can also be a
PSModuleInfo
or PSSnapinInfo object, such as the objects that the Get-Module , Get-
PSSnapin , and
Import-PSSession cmdlets return.

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

Type: String[]

Aliases: PSSnapin

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-Name

Specifies an array of names. This cmdlet gets only commands that have the specified
name. Enter a
name or name pattern. Wildcard characters are permitted.

To get commands that have the same name, use the All parameter. When two
commands have the same
name, by default, Get-Command gets the command that
runs when you type the command name.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-Noun

Specifies an array of command nouns. This cmdlet gets commands, which include
cmdlets, functions,
and aliases, that have names that include the specified noun.
Enter one or more nouns or noun
patterns. Wildcard characters are permitted.

Type: String[]

Position: Named
Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-ParameterName

Specifies an array of parameter names. This cmdlet gets commands in the session
that have the
specified parameters. Enter parameter names or parameter aliases.
Wildcard characters are supported.

The ParameterName and ParameterType parameters search only commands in the


current session.

This parameter was introduced in Windows PowerShell 3.0.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-ParameterType

Specifies an array of parameter names. This cmdlet gets commands in the session
that have parameters
of the specified type. Enter the full name or partial name of a
parameter type. Wildcard characters
are supported.

The ParameterName and ParameterType parameters search only commands in the


current session.

This parameter was introduced in Windows PowerShell 3.0.

Type: PSTypeName[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True


-ShowCommandInfo

Indicates that this cmdlet displays command information.

This parameter was introduced in Windows PowerShell 5.0.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Syntax

Indicates that this cmdlet gets only the following specified data about the command:

Aliases Gets the standard name.


Cmdlets. Gets the syntax.
Functions and filters. Gets the function definition.
Scripts and applications or files. Gets the path and filename.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-TotalCount

Specifies the number of commands to get. You can use this parameter to limit the
output of a
command.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False


-Verb

Specifies an array of command verbs. This cmdlet gets commands, which include
cmdlets, functions,
and aliases, that have names that include the specified verb. Enter
one or more verbs or verb
patterns. Wildcard characters are permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

Inputs
String

You can pipe command names to this cmdlet.

Outputs
CommandInfo

This cmdlet returns objects derived from the CommandInfo class. The type of object
that is
returned depends on the type of command that Get-Command gets.

AliasInfo

Represents aliases.

ApplicationInfo

Represents applications and files.

CmdletInfo

Represents cmdlets.

FunctionInfo

Represents functions and filters.


WorkflowInfo

Represents workflows.

Notes
Windows PowerShell includes the following aliases for Get-Command :

gcm

When more than one command that has the same name is available to the session,
Get-Command
returns the command that runs when you type the command name.

To get commands that have the same


name, listed in run order, use the All
parameter. For more information, see
about_Command_Precedence.

When a module is imported automatically, the effect is the same as using the
Import-Module
cmdlet. The module can add commands, types and formatting files,
and run scripts in the session.
To enable, disable, and configuration automatic
importing of modules, use the
$PSModuleAutoLoadingPreference preference
variable. For more information, see
about_Preference_Variables.

Related Links
Export-PSSession
Get-Help
Get-Member
Get-PSDrive
Import-PSSession
about_Command_Precedence
Get-Help
Reference
Module: Microsoft.PowerShell.Core

Displays information about PowerShell commands and concepts.

Syntax
PowerShell

Get-Help

[[-Name] <String>]

[-Path <String>]

[-Category <String[]>]

[-Component <String[]>]

[-Functionality <String[]>]

[-Role <String[]>]

[-Full]

[<CommonParameters>]

PowerShell

Get-Help

[[-Name] <String>]

[-Path <String>]

[-Category <String[]>]

[-Component <String[]>]

[-Functionality <String[]>]

[-Role <String[]>]

-Detailed

[<CommonParameters>]

PowerShell

Get-Help

[[-Name] <String>]

[-Path <String>]

[-Category <String[]>]

[-Component <String[]>]

[-Functionality <String[]>]

[-Role <String[]>]

-Examples

[<CommonParameters>]

PowerShell
Get-Help

[[-Name] <String>]

[-Path <String>]

[-Category <String[]>]

[-Component <String[]>]

[-Functionality <String[]>]

[-Role <String[]>]

-Parameter <String>

[<CommonParameters>]

PowerShell

Get-Help

[[-Name] <String>]

[-Path <String>]

[-Category <String[]>]

[-Component <String[]>]

[-Functionality <String[]>]

[-Role <String[]>]

-Online

[<CommonParameters>]

PowerShell

Get-Help

[[-Name] <String>]

[-Path <String>]

[-Category <String[]>]

[-Component <String[]>]

[-Functionality <String[]>]

[-Role <String[]>]

-ShowWindow

[<CommonParameters>]

Description
The Get-Help cmdlet displays information about PowerShell concepts and commands,
including
cmdlets, functions, Common Information Model (CIM) commands, workflows,
providers, aliases, and
scripts.

To get help for a PowerShell cmdlet, type Get-Help followed by the cmdlet name, such
as:
Get-Help Get-Process .

Conceptual help articles in PowerShell begin with about_, such as


about_Comparison_Operators. To see all about_ articles, type Get-Help about_* . To see
a
particular article, type Get-Help about_<article-name> , such as
Get-Help
about_Comparison_Operators .

To get help for a PowerShell provider, type Get-Help followed by the provider name. For
example,
to get help for the Certificate provider, type Get-Help Certificate .

You can also type help or man , which displays one screen of text at a time. Or,
<cmdlet-
name> -? , that's identical to Get-Help , but only works for cmdlets.

Get-Help gets the help content that it displays from help files on your computer.
Without the help
files, Get-Help displays only basic information about cmdlets. Some
PowerShell modules include
help files. Beginning in PowerShell 3.0, the modules that
come with the Windows operating system
don't include help files. To download or
update the help files for a module in PowerShell 3.0, use
the Update-Help cmdlet.

You can also view the PowerShell help documents online. To get the online version of a
help file,
use the Online parameter, such as: Get-Help Get-Process -Online .

If you type Get-Help followed by the exact name of a help article, or by a word unique
to a help
article, Get-Help displays the article's content. If you specify the exact name of
a command
alias, Get-Help displays the help for the original command. If you enter a
word or word pattern
that appears in several help article titles, Get-Help displays a list of
the matching titles. If
you enter any text that doesn't appear in any help article titles,
Get-Help displays a list of
articles that include that text in their contents.

Get-Help can get help articles for all supported languages and locales. Get-Help first

looks for
help files in the locale set for Windows, then in the parent locale, such as pt for
pt-BR,
and then in a fallback locale. Beginning in PowerShell 3.0, if Get-Help doesn't find
help in the
fallback locale, it looks for help articles in English, en-US, before it returns an
error
message or displaying autogenerated help.

For information about the symbols that Get-Help displays in the command syntax
diagram, see
about_Command_Syntax. For information about parameter attributes,
such
as Required and Position, see about_Parameters.

7 Note

In PowerShell 3.0 and PowerShell 4.0, Get-Help can't find About articles in modules
unless
the module is imported into the current session. To get About articles in a
module, import the
module using the Import-Module cmdlet or by running a cmdlet
that's included in the module.
Beginning with PSReadLine v2.2.2, the module ships with two functions that provide
quick access
to help while you are typing a command on the command line. The help is
displayed in the terminal in
an alternate screen buffer with paging.

When you hit the F1 key, the PSReadLine ShowCommandHelp function invokes
Get-Help -
Full for the cmdlet name closest to the left of the cursor. When the cursor is

immediately to the left of a parameter, the function jumps to that parameter's


description in the
full help topic. When you hit Q to exit the help view, you are returned
to the command
line at the same cursor position so you can continue typing the
command.

When you use the key combination Alt + h , the PSReadLine ShowParameterHelp
function
displays help information for the parameter immediately to the left of the
cursor. The help text is
displayed below the command line. This allows you to see the
description of the parameter and
continue typing your command.

For more information, see Using dynamic help.

Examples

Example 1: Display basic help information about a cmdlet


These examples display basic help information about the Format-Table cmdlet.

PowerShell

Get-Help Format-Table

Get-Help -Name Format-Table

Format-Table -?

Get-Help <cmdlet-name> is the simplest and default syntax of Get-Help cmdlet. You can

omit the
Name parameter.

The syntax <cmdlet-name> -? works only for cmdlets.

Example 2: Display basic information one page at a time


These examples display basic help information about the Format-Table cmdlet one page
at a time.

PowerShell
help Format-Table

man Format-Table

Get-Help Format-Table | Out-Host -Paging

help is a function that runs Get-Help cmdlet internally and displays the result one page

at a
time.

man is an alias for the help function.

Get-Help Format-Table sends the object down the pipeline. Out-Host -Paging receives
the output
from the pipeline and displays it one page at a time. For more information,
see
Out-Host.

Example 3: Display more information for a cmdlet


These examples display more detailed help information about the Format-Table cmdlet.

PowerShell

Get-Help Format-Table -Detailed

Get-Help Format-Table -Full

The Detailed parameter displays the help article's detailed view that includes parameter
descriptions and examples.

The Full parameter displays the help article's full view that includes parameter
descriptions,
examples, input and output object types, and additional notes.

The Detailed and Full parameters are effective only for the commands that have help
files
installed on the computer. The parameters aren't effective for the conceptual
(about_) help
articles.

Example 4: Display selected parts of a cmdlet by using


parameters
These examples display selected portions of the Format-Table cmdlet help.

PowerShell

Get-Help Format-Table -Examples

Get-Help Format-Table -Parameter *

Get-Help Format-Table -Parameter GroupBy


The Examples parameter displays the help file's NAME and SYNOPSIS sections, and all
the
Examples. You can't specify an Example number because the Examples parameter is
a switch
parameter.

The Parameter parameter displays only the descriptions of the specified parameters. If
you
specify only the asterisk ( * ) wildcard character, it displays the descriptions of all
parameters.
When Parameter specifies a parameter name such as GroupBy, information
about that parameter
is shown.

These parameters aren't effective for the conceptual (about_) help articles.

Example 5: Display online version of help


This example displays the online version of the help article for the Format-Table cmdlet
in your
default web browser.

PowerShell

Get-Help Format-Table -Online

Example 6: Display help about the help system


The Get-Help cmdlet without parameters displays information about the PowerShell
help system.

PowerShell

Get-Help

Example 7: Display available help articles


This example displays a list of all help articles available on your computer.

PowerShell

Get-Help *

Example 8: Display a list of conceptual articles


This example displays a list of the conceptual articles included in PowerShell help. All
these
articles begin with the characters about_. To display a particular help file, type
Get-Help \<about_article-name\> , for example, Get-Help about_Signing .

Only the conceptual articles that have help files installed on your computer are
displayed. For
information about downloading and installing help files in PowerShell 3.0,
see
Update-Help.

PowerShell

Get-Help about_*

Example 9: Search for a word in cmdlet help


This example shows how to search for a word in a cmdlet help article.

PowerShell

Get-Help Add-Member -Full | Out-String -Stream | Select-String -Pattern


Clixml

the Export-Clixml cmdlet to save the instance of the object, including the
additional members...

can use the Import-Clixml cmdlet to re-create the instance of the object
from the information...

Export-Clixml

Import-Clixml

Get-Help uses the Full parameter to get help information for Add-Member . The
MamlCommandHelpInfo object is sent down the pipeline. Out-String uses the Stream
parameter
to convert the object into a string. Select-String uses the Pattern parameter
to search the
string for Clixml.

Example 10: Display a list of articles that include a word


This example displays a list of articles that include the word remoting.

When you enter a word that doesn't appear in any article title, Get-Help displays a list of
articles that include that word.

PowerShell

Get-Help -Name remoting

Name Category Module


Synopsis

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


--

Install-PowerShellRemoting.ps1 External
Install-PowerShellRemoting.ps1

Disable-PSRemoting Cmdlet Microsoft.PowerShell.Core


Prevents remote users...

Enable-PSRemoting Cmdlet Microsoft.PowerShell.Core


Configures the computer...

Example 11: Display provider-specific help


This example shows two ways of getting the provider-specific help for Get-Item . These
commands get
help that explains how to use the Get-Item cmdlet in the PowerShell
SQL Server provider's
DataCollection node.

The first example uses the Get-Help Path parameter to specify the SQL Server provider's
path.
Because the provider's path is specified, you can run the command from any path
location.

The second example uses Set-Location to navigate to the SQL Server provider's path.
From that
location, the Path parameter isn't needed for Get-Help to get the provider-
specific help.

PowerShell

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.

...

Set-Location SQLSERVER:\DataCollection

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.

...

Example 12: Display help for a script


This example gets help for the MyScript.ps1 script . For information about how to write
help for
your functions and scripts, see about_Comment_Based_Help.

PowerShell

Get-Help -Name C:\PS-Test\MyScript.ps1

Parameters
-Category

Displays help only for items in the specified category and their aliases. Conceptual
articles are in
the HelpFile category.

The acceptable values for this parameter are as follows:

Alias
Cmdlet
Provider
General
FAQ
Glossary
HelpFile
ScriptCommand
Function
Filter
ExternalScript
All
DefaultHelp
Workflow
DscResource
Class
Configuration

Type: String[]
Accepted values: Alias, Cmdlet, Provider, General, FAQ, Glossary, HelpFile,
ScriptCommand, Function, Filter, ExternalScript, All,
DefaultHelp, Workflow, DscResource, Class, Configuration

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Component

Displays commands with the specified component value, such as Exchange. Enter a
component name.
Wildcard characters are permitted. This parameter has no effect
on displays of conceptual
(About_) help.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Detailed

Adds parameter descriptions and examples to the basic help display. This parameter
is effective only
when the help files are installed on the computer. It has no effect on
displays of conceptual
(About_) help.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Examples

Displays only the name, synopsis, and examples. This parameter is effective only
when the help files
are installed on the computer. It has no effect on displays of
conceptual (About_) help.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Full

Displays the entire help article for a cmdlet. Full includes parameter descriptions and
attributes, examples, input and output object types, and additional notes.

This parameter is effective only when the help files are installed on the computer. It
has no effect
on displays of conceptual (About_) help.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Functionality

Displays help for items with the specified functionality. Enter the functionality.
Wildcard
characters are permitted. This parameter has no effect on displays of
conceptual (About_) help.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Name
Gets help about the specified command or concept. Enter the name of a cmdlet,
function, provider,
script, or workflow, such as Get-Member , a conceptual article name,
such as about_Objects , or an
alias, such as ls . Wildcard characters are permitted in
cmdlet and provider names, but you can't
use wildcard characters to find the names
of function help and script help articles.

To get help for a script that isn't located in a path that's listed in the $env:Path
environment
variable, type the script's path and file name.

If you enter the exact name of a help article, Get-Help displays the article contents.

If you enter a word or word pattern that appears in several help article titles, Get-
Help displays
a list of the matching titles.

If you enter any text that doesn't match any help article titles, Get-Help displays a list
of
articles that include that text in their contents.

The names of conceptual articles, such as about_Objects , must be entered in English,


even in
non-English versions of PowerShell.

Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-Online

Displays the online version of a help article in the default browser. This parameter is
valid only
for cmdlet, function, workflow, and script help articles. You can't use the
Online parameter
with Get-Help in a remote session.

For information about supporting this feature in help articles that you write, see
about_Comment_Based_Help, and
Supporting Online Help, and
Writing Help for
PowerShell Cmdlets.

Type: SwitchParameter

Position: Named

Default value: False


Accept pipeline input: False

Accept wildcard characters: False

-Parameter

Displays only the detailed descriptions of the specified parameters. Wildcards are
permitted. This
parameter has no effect on displays of conceptual (About_) help.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Path

Gets help that explains how the cmdlet works in the specified provider path. Enter a
PowerShell
provider path.

This parameter gets a customized version of a cmdlet help article that explains how
the cmdlet works
in the specified 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
article in its help file. To use this
parameter, install the help file for the module that includes
the provider.

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. You can also find custom cmdlet help
online in the provider help section of the
help articles.

For more information about PowerShell providers, see about_Providers.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True


-Role

Displays help customized for the specified user role. Enter a role. Wildcard characters
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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-ShowWindow

Displays the help topic in a window for easier reading. The window includes a Find
search
feature and a Settings box that lets you set options for the display, including
options to
display only selected sections of a help topic.

The ShowWindow parameter supports help topics for commands (cmdlets,


functions, CIM commands,
workflows, scripts) and conceptual About articles. It does
not support provider help.

This parameter was introduced in PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.


Outputs
ExtendedCmdletHelpInfo

If you run Get-Help on a command that doesn't have a help file, Get-Help returns an
ExtendedCmdletHelpInfo object that represents autogenerated help.

String

If you get a conceptual help article, Get-Help returns it as a string.

MamlCommandHelpInfo

If you get a command that has a help file, Get-Help returns a MamlCommandHelpInfo
object.

Notes
PowerShell 3.0 doesn't include help files. To download and install the help files that Get-
Help
reads, use the Update-Help cmdlet. You can use the Update-Help cmdlet to

download and install


help files for the core commands that come with PowerShell and
for any modules that you install. You
can also use it to update the help files so that the
help on your computer is never outdated.

You can also read the help articles about the commands that come with PowerShell
online starting at
Getting Started with Windows PowerShell.

Get-Help displays help in the locale set for the Windows operating system or in the
fallback
language for that locale. If you don't have help files for the primary or fallback
locale,
Get-Help behaves as if there are no help files on the computer. To get help for a
different
locale, use Region and Language in Control Panel to change the settings. On
Windows 10 or
higher, Settings, Time & Language.

The full view of help 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 (numeric).


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.
Numeric 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 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 or default behavior that PowerShell uses if you
don't
include the parameter in the command.

Accepts pipeline input. Indicates whether you can (true) or can't (false) send
objects to the
parameter through a pipeline. By Property Name means that the
pipelined object must have a
property that has the same name as the parameter
name.

Accepts wildcard characters. Indicates whether the value of a parameter can


include wildcard
characters, such as an asterisk ( * ) or question mark ( ? ).

Related Links
about_Command_Syntax
about_Comment_Based_Help
Get-Command
Supporting Updatable Help
Update-Help
Writing Comment-Based Help Topics
Writing Help for PowerShell Cmdlets
Get-History
Reference
Module: Microsoft.PowerShell.Core

Gets a list of the commands entered during the current session.

Syntax
PowerShell

Get-History

[[-Id] <Int64[]>]

[[-Count] <Int32>]

[<CommonParameters>]

Description
The Get-History cmdlet gets the session history, that is, the list of commands entered
during the
current session.

PowerShell automatically maintains a history of each session. The number of entries in


the session
history is determined by the value of the $MaximumHistoryCount preference
variable. Beginning in
Windows PowerShell 3.0, the default value is 4096 . By default,
history files are saved in the home
directory, but you can save the file in any location.
For more information about the history
features in PowerShell, see about_History.

The session history is managed separately from the history maintained by the
PSReadLine module.
Both histories are available in sessions where PSReadLine is
loaded. This cmdlet only works with
the session history. For more information see,
about_PSReadLine.

Examples

Example 1: Get the session history


This example gets the entries in the session history. The default display shows each
command and its
ID, which indicates the order in which they ran.

PowerShell
Get-History

Example 2: Get entries that include a string


This example gets entries in the command history that include the string service. The
first command
gets all entries in the session history. The pipeline operator ( | ) passes
the results to the
Where-Object cmdlet, which selects only the commands that include
service.

PowerShell

Get-History | Where-Object {$_.CommandLine -like "*Service*"}

Example 3: Export history entries up to a specific ID


This example 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. This includes the status and start and
end times of the command.

PowerShell

Get-History -ID 7 -Count 5 | Export-Csv History.csv

Example 4: Display the most recent command


This example gets the last command in the command history. The last command is the
most recently
entered command. This command uses the Count parameter to display
just one command. By default,
Get-History gets the most recent commands. This
command can be abbreviated to "h -c 1" and is
equivalent to pressing the up-arrow key.

PowerShell

Get-History -Count 1

Example 5: Display all the properties of the entries in the


history
This example displays all of the properties of entries in the session history. The pipeline
operator
passes the results of a Get-History command to the Format-List cmdlet,
which displays all of the
properties of each history entry. This includes the ID, status, and
start and end times of the
command.

PowerShell

Get-History | Format-List -Property *

Parameters
-Count

Specifies the number of the most recent history entries that this cmdlet gets. By,
default,
Get-History gets all entries in the session history. If you use both the Count
and Id
parameters in a command, the display ends with the command that is
specified by the Id
parameter.

In Windows PowerShell 2.0, by default, Get-History gets the 32 most recent entries.

Type: Int32

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Id

Specifies an array of the IDs of entries in the session history. Get-History gets only
specified
entries. If you use both the Id and Count parameters in a command, Get-
History gets the
most recent entries ending with the entry specified by the Id
parameter.

Type: Int64[]

Position: 0

Default value: None

Accept pipeline input: True


Accept wildcard characters: False

Inputs
Int64

You can pipe a history ID to this cmdlet.

Outputs
HistoryInfo

This cmdlet returns a history object for each history item that it gets.

Notes
Windows PowerShell includes the following aliases for Get-History :

history
ghy

The session history is a list of the commands entered during the session. The session
history
represents the run order, the status, and the start and end times of the
command. As you enter each
command, PowerShell adds it to the history so that you
can reuse it. For more information about the
command history, see about_History.

Starting in Windows PowerShell 3.0, the default value of the $MaximumHistoryCount


preference
variable is 4096 . In Windows PowerShell 2.0, the default value is 64 . For
more information about
the $MaximumHistoryCount variable, see
about_Preference_Variables.

Related Links
Add-History
Clear-History
Invoke-History
about_History
Get-Job
Reference
Module: Microsoft.PowerShell.Core

Gets PowerShell background jobs that are running in the current session.

Syntax
PowerShell

Get-Job

[-IncludeChildJob]

[-ChildJobState <JobState>]

[-HasMoreData <Boolean>]

[-Before <DateTime>]

[-After <DateTime>]

[-Newest <Int32>]

[[-Id] <Int32[]>]

[<CommonParameters>]

PowerShell

Get-Job

[-IncludeChildJob]

[-ChildJobState <JobState>]

[-HasMoreData <Boolean>]

[-Before <DateTime>]

[-After <DateTime>]

[-Newest <Int32>]

[-Command <String[]>]

[<CommonParameters>]

PowerShell

Get-Job

[-IncludeChildJob]

[-ChildJobState <JobState>]

[-HasMoreData <Boolean>]

[-Before <DateTime>]

[-After <DateTime>]

[-Newest <Int32>]

[-InstanceId] <Guid[]>

[<CommonParameters>]

PowerShell
Get-Job

[-IncludeChildJob]

[-ChildJobState <JobState>]

[-HasMoreData <Boolean>]

[-Before <DateTime>]

[-After <DateTime>]

[-Newest <Int32>]

[-Name] <String[]>

[<CommonParameters>]

PowerShell

Get-Job

[-IncludeChildJob]

[-ChildJobState <JobState>]

[-HasMoreData <Boolean>]

[-Before <DateTime>]

[-After <DateTime>]

[-Newest <Int32>]

[-State] <JobState>

[<CommonParameters>]

PowerShell

Get-Job

[-Filter] <Hashtable>

[<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 the
Start-Job
cmdlet, 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 finish. For more information about
background jobs in Windows PowerShell, see
about_Jobs.
Beginning in Windows PowerShell 3.0, the Get-Job cmdlet also gets custom job types,
such as
workflow jobs and instances of scheduled jobs. To find the job type of a job, use
the
PSJobTypeName property of the job.

To enable Get-Job to get a custom job type, import the module that supports the
custom job type
into the session before you run a Get-Job command, either by using
the Import-Module cmdlet or
by using or getting a cmdlet in the module. For
information about a particular custom job type, see
the documentation of the custom
job type feature.

Examples

Example 1: Get all background jobs started in the current


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

PowerShell

PS C:\> Get-Job

Example 2: Stop a job by using an instance ID


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.

PowerShell

PS C:\> $j = Get-Job -Name Job1

PS C:\> $ID = $j.InstanceID

PS C:\> $ID

Guid

----

03c3232e-1d23-453b-a6f4-ed73c9e29d55

PS C:\> Stop-Job -InstanceId $ID

Example 3: Get jobs that include a specific command


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 in the command string.

PowerShell

PS C:\> Get-Job -Command "*get-process*"

Example 4: Get jobs that include a specific command by


using the pipeline
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 quotation
marks, to the Get-Job cmdlet. It is the equivalent of the
previous command.

PowerShell

PS C:\> "*get-process*" | Get-Job

Example 5: Get jobs that have not been started


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.

PowerShell

PS C:\> Get-Job -State NotStarted

Example 6: Get jobs that have not been assigned a name


This command gets all jobs that have job names that begin 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.

PowerShell

PS C:\> Get-Job -Name Job*

Example 7: Use a job object to represent the job in a


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

PowerShell

PS C:\> Start-Job -ScriptBlock {Get-Process} -Name MyJob

PS C:\> $j = Get-Job -Name MyJob

PS C:\> $j

Id Name PSJobTypeName State HasMoreData


Location Command

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


- -------

6 MyJob BackgroundJob Completed True


localhost Get-Process

PS C:\> 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

...
Example 8: Get all jobs including jobs started by a
different method
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 the Invoke-Command cmdlet 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. By using 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
PSJobTypeName
property of jobs, introduced in Windows PowerShell 3.0, shows that
the local job started by using
the Start-Job cmdlet is a background job and the job
started in a remote session by using the
Invoke-Command cmdlet is a remote job. 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 command. On the S2
computer, the job appears to be a local job. The computer name is localhost and the job
type is a
background job.For more information about how to run background jobs on
remote computers, see
about_Remote_Jobs.

PowerShell

PS C:\> Start-Job -ScriptBlock {Get-EventLog System}

PS C:\> Invoke-Command -ComputerName S1 -ScriptBlock {Get-EventLog System} -


AsJob

PS C:\> Invoke-Command -ComputerName S2 -ScriptBlock {Start-Job -ScriptBlock


{Get-EventLog System}}

PS C:\> Get-Job

Id Name PSJobTypeName State HasMoreData Location


Command

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


-------

1 Job1 BackgroundJob Running True localhost


Get-EventLog System

2 Job2 RemoteJob Running True S1


Get-EventLog System

PS C:\> Invoke-Command -ComputerName S2 -ScriptBlock {Start-Job -ScriptBlock


{Get-EventLog System}}

Id Name PSJobTypeName State HasMoreData Location Command

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

4 Job4 BackgroundJob Running True localhost Get-


Eventlog System

Example 9: Investigate a failed job


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 the Get-Job cmdlet to get the job. 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 more. It uses a Get-Job command to get the job and
then uses a
pipeline operator to send the whole 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 starting 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.

PowerShell

PS C:\> Start-Job -ScriptBlock {Get-Process}

Id Name PSJobTypeName State HasMoreData Location


Command

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


-------

1 Job1 BackgroundJob Failed False localhost


Get-Process

PS C:\> (Get-Job).JobStateInfo | Format-List -Property *


State : Failed

Reason :

PS C:\> Get-Job | Format-List -Property *

HasMoreData : False

StatusMessage :

Location : localhost

Command : get-process

JobStateInfo : Failed

Finished : System.Threading.ManualReset

EventInstanceId : fb792295-1318-4f5d-8ac8-8a89c5261507

Id : 1

Name : Job1

ChildJobs : {Job2}

Output : {}

Error : {}

Progress : {}

Verbose : {}

Debug : {}

Warning : {}

StateChanged :

PS C:\> (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.

Example 10: Get filtered results


This example shows how to use the Filter parameter to get a workflow job. The Filter
parameter, introduced in Windows PowerShell 3.0 is valid only on custom job types,
such as workflow
jobs and scheduled jobs.

The first command uses the Workflow keyword to create the WFProcess workflow. The
second command
uses the AsJob parameter of the WFProcess workflow to run the
workflow as a background job. It
uses the JobName parameter of the workflow to
specify a name for the job, and the
PSPrivateMetadata parameter of the workflow to
specify a custom ID. The third command uses the
Filter parameter of Get-Job to get the
job by custom ID that was specified in the
PSPrivateMetadata parameter.

PowerShell

PS C:\> Workflow WFProcess {Get-Process}

PS C:\> WFProcess -AsJob -JobName WFProcessJob -PSPrivateMetadata


@{MyCustomId = 92107}

PS C:\> Get-Job -Filter @{MyCustomId = 92107}

Id Name State HasMoreData Location


Command

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


-----

1 WFProcessJob Completed True localhost


WFProcess

Example 11: Get information about child jobs


This example shows the effect of using the IncludeChildJob and ChildJobState
parameters of
the Get-Job cmdlet.

The first command gets the jobs in the current session. The output includes a
background job, a
remote job and several instances of a scheduled job. The remote job,
Job4, appears to have failed.
The second command uses the IncludeChildJob parameter
of Get-Job . The output adds the child
jobs of all jobs that have child jobs.In this case,
the revised output shows that only the Job5
child job of Job4 failed. The third command
uses the ChildJobState parameter with a value of
Failed.The output includes all parent
jobs and only the child jobs that failed. The fifth command
uses the JobStateInfo
property of jobs and its Reason property to discover why Job5 failed.

PowerShell

PS C:\> Get-Job

Id Name PSJobTypeName State HasMoreData


Location Command

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


- -------

2 Job2 BackgroundJob Completed True


localhost .\Get-Archive.ps1

4 Job4 RemoteJob Failed True


Server01, Server02 .\Get-Archive.ps1

7 UpdateHelpJob PSScheduledJob Completed True


localhost Update-Help

8 UpdateHelpJob PSScheduledJob Completed True


localhost Update-Help

9 UpdateHelpJob PSScheduledJob Completed True


localhost Update-Help

10 UpdateHelpJob PSScheduledJob Completed True


localhost Update-Help

PS C:\> Get-Job -IncludeChildJob

Id Name PSJobTypeName State HasMoreData


Location Command

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


- -------

2 Job2 BackgroundJob Completed True


localhost .\Get-Archive.ps1

3 Job3 Completed True


localhost .\Get-Archive.ps1

4 Job4 RemoteJob Failed True


Server01, Server02 .\Get-Archive.ps1

5 Job5 Failed False


Server01 .\Get-Archive.ps1

6 Job6 Completed True


Server02 .\Get-Archive.ps1

7 UpdateHelpJob PSScheduledJob Completed True


localhost Update-Help

8 UpdateHelpJob PSScheduledJob Completed True


localhost Update-Help

9 UpdateHelpJob PSScheduledJob Completed True


localhost Update-Help

10 UpdateHelpJob PSScheduledJob Completed True


localhost Update-Help

PS C:\> Get-Job -Name Job4 -ChildJobState Failed

Id Name PSJobTypeName State HasMoreData


Location Command

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


- -------

2 Job2 BackgroundJob Completed True


localhost .\Get-Archive.ps1

4 Job4 RemoteJob Failed True


Server01, Server02 .\Get-Archive.ps1

5 Job5 Failed False


Server01 .\Get-Archive.ps1

7 UpdateHelpJob PSScheduledJob Completed True


localhost Update-Help

8 UpdateHelpJob PSScheduledJob Completed True


localhost Update-Help

9 UpdateHelpJob PSScheduledJob Completed True


localhost Update-Help

10 UpdateHelpJob PSScheduledJob Completed True


localhost Update-Help

PS C:\> (Get-Job -Name Job5).JobStateInfo.Reason

Connecting to remote server Server01 failed with the following error


message:

Access is denied.

For more information, see the


about_Remote_Troubleshooting Help topic.

Parameters
-After

Gets completed jobs that ended after the specified date and time. Enter a DateTime
object, such
as one returned by the Get-Date cmdlet or a string that can be
converted to a DateTime object,
such as Dec 1, 2012 2:00 AM or 11/06 .
This parameter works only on custom job types, such as workflow jobs and
scheduled jobs, that have
an EndTime property. It does not work on standard
background jobs, such as those created by
using the Start-Job cmdlet. For
information about support for this parameter, see the help topic
for the job type.

This parameter was introduced in Windows PowerShell 3.0.

Type: DateTime

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Before

Gets completed jobs that ended before the specified date and time. Enter a
DateTime object.

This parameter works only on custom job types, such as workflow jobs and
scheduled jobs, that have
an EndTime property. It does not work on standard
background jobs, such as those created by
using the Start-Job cmdlet. For
information about support for this parameter, see the help topic
for the job type.

This parameter was introduced in Windows PowerShell 3.0.

Type: DateTime

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ChildJobState

Gets only the child jobs that have the specified state. The acceptable values for this
parameter
are:

NotStarted
Running
Completed
Failed
Stopped
Blocked
Suspended
Disconnected
Suspending
Stopping

By default, Get-Job does not get child jobs. By using the IncludeChildJob parameter,
Get-Job
gets all child jobs. If you use the ChildJobState parameter, the
IncludeChildJob parameter
has no effect.

This parameter was introduced in Windows PowerShell 3.0.

Type: JobState

Accepted values: NotStarted, Running, Completed, Failed, Stopped, Blocked,


Suspended, Disconnected, Suspending, Stopping,
AtBreakpoint

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Command

Specifies an array of commands as strings. This cmdlet gets the jobs that include the
specified
commands. The default is all jobs. You can use wildcard characters to
specify a command pattern.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-Filter
Specifies a hash table of conditions. This cmdlet gets jobs that satisfy all of the
conditions.
Enter a hash table where the keys are job properties and the values are
job property values.

This parameter works only on custom job types, such as workflow jobs and
scheduled jobs. It does not
work on standard background jobs, such as those
created by using the Start-Job cmdlet. For
information about support for this
parameter, see the help topic for the job type.

This parameter was introduced in Windows PowerShell 3.0.

Type: Hashtable

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-HasMoreData

Indicates whether this cmdlet gets only jobs that have the specified HasMoreData
property value.
The HasMoreData property indicates whether all job results have
been received in the current
session. To get jobs that have more results, specify a
value of $True . To get jobs that do not
have more results, specify a value of $False .

To get the results of a job, use the Receive-Job cmdlet.

When you use the Receive-Job cmdlet, it deletes from its in-memory, session-
specific storage the
results that it returned. When it has returned all results of the job
in the current session, it
sets the value of the HasMoreData property of the job to
$False ) to indicate that it has no
more results for the job in the current session. Use

the Keep parameter of Receive-Job to


prevent Receive-Job from deleting results
and changing the value of the HasMoreData property.
For more information, type
Get-Help Receive-Job .

The HasMoreData property is specific to the current session. If results for a custom
job type
are saved outside of the session, such as the scheduled job type, which
saves job results on disk,
you can use the Receive-Job cmdlet in a different session
to get the job results again, even if
the value of HasMoreData is $False . For more
information, see the help topics for the custom
job type.
This parameter was introduced in Windows PowerShell 3.0.

Type: Boolean

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Id

Specifies an array of IDs of jobs that this cmdlet gets.

The ID is an integer that uniquely identifies the job in the current session. It is easier
to
remember and to type than the instance ID, but it is unique only in 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.

Type: Int32[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-IncludeChildJob

Indicates that this cmdlet returns child jobs, in addition to parent jobs.

This parameter is especially useful for investigating workflow jobs, for which Get-Job
returns a
container parent job, and job failures, because the reason for the failure is
saved in a property of
the child job.

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-InstanceId

Specifies an array of instance IDs of jobs that this cmdlet gets. 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 .

Type: Guid[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies an array of instance friendly names of jobs that this cmdlet gets. 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.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-Newest

Specifies a number of jobs to get. This cmdlet gets the jobs that ended most
recently.

The Newest parameter does not sort or return the newest jobs in end-time order. To
sort the
output, use the Sort-Object cmdlet.

This parameter was introduced in Windows PowerShell 3.0.

Type: Int32
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-State

Specifies a job state. This cmdlet gets only jobs in the specified state. The acceptable
values for
this parameter are:

NotStarted
Running
Completed
Failed
Stopped
Blocked
Suspended
Disconnected
Suspending
Stopping

By default, Get-Job gets all the jobs in the current session.

For more information about job states, see


JobState Enumeration.

Type: JobState

Accepted values: NotStarted, Running, Completed, Failed, Stopped, Blocked,


Suspended, Disconnected, Suspending, Stopping,
AtBreakpoint

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

Inputs
None
You can't pipe objects to this cmdlet.

Outputs
System.Management.Automation.RemotingJob

This cmdlet returns objects that represent the jobs in the session.

Notes
Windows PowerShell includes the following aliases for Get-Job :

gjb

The PSJobTypeName property of jobs indicates the job type of the job. The property
value is
determined by the job type author. The following list shows common job types.

BackgroundJob. Local job started by using Start-Job .


RemoteJob. Job started in a PSSession by using the AsJob parameter of the
Invoke-Command cmdlet.

PSWorkflowJob. Job started by using the AsJob common parameter of workflows.

Related Links
Invoke-Command
Receive-Job
Remove-Job
Resume-Job
Start-Job
Stop-Job
Suspend-Job
Wait-Job
about_Jobs
about_Job_Details
about_Remote_Jobs
about_Scheduled_Jobs
Get-Module
Reference
Module: Microsoft.PowerShell.Core

List the modules imported in the current session or that can be imported from the
PSModulePath.

Syntax
PowerShell

Get-Module

[[-Name] <String[]>]

[-FullyQualifiedName <ModuleSpecification[]>]

[-All]

[<CommonParameters>]

PowerShell

Get-Module

[[-Name] <String[]>]

[-FullyQualifiedName <ModuleSpecification[]>]

[-All]

[-ListAvailable]

[-PSEdition <String>]

[-Refresh]

[<CommonParameters>]

PowerShell

Get-Module

[[-Name] <String[]>]

[-FullyQualifiedName <ModuleSpecification[]>]

[-ListAvailable]

[-PSEdition <String>]

[-Refresh]

-PSSession <PSSession>

[<CommonParameters>]

PowerShell

Get-Module

[[-Name] <String[]>]

[-FullyQualifiedName <ModuleSpecification[]>]

[-ListAvailable]

[-Refresh]

-CimSession <CimSession>

[-CimResourceUri <Uri>]

[-CimNamespace <String>]

[<CommonParameters>]

Description
The Get-Module cmdlet lists the PowerShell modules that have been imported, or that
can be
imported, into a PowerShell session. Without parameters, Get-Module gets
modules that have been
imported into the current session. The ListAvailable parameter
is used to list the modules that
are available to be imported from the paths specified in
the PSModulePath environment variable
( $env:PSModulePath ).

The module object that Get-Module returns contains valuable information about the
module. You can
also pipe the module objects to other cmdlets, such as the Import-
Module and Remove-Module
cmdlets.

Get-Module lists modules, but it does not import them. Starting in Windows PowerShell

3.0, modules
are automatically imported when you use a command in the module, but a
Get-Module command does not
trigger an automatic import. You can also import the

modules into your session using the


Import-Module cmdlet.

Starting in Windows PowerShell 3.0, you can get and then, import modules from remote
sessions into
the local session. This strategy uses the Implicit Remoting feature of
PowerShell and is equivalent
to using the Import-PSSession cmdlet. When you use
commands in modules imported from another
session, the commands run implicitly in
the remote session. This feature lets you manage the remote
computer from the local
session.

Also, starting in Windows PowerShell 3.0, you can use Get-Module and Import-Module to
get and
import Common Information Model (CIM) modules. CIM modules define
cmdlets in Cmdlet Definition XML
(CDXML) files. This feature lets you use cmdlets that
are implemented in non-managed code
assemblies, such as those written in C++.

Implicit remoting can be used to manage remote computers that have PowerShell
remoting enabled.
Create a PSSession on the remote computer and then use the
PSSession parameter of
Get-Module to get the PowerShell modules in the remote
session. When you import a module from the
remote session the imported commands
run in the session on the remote computer.
You can use a similar strategy to manage computers that do not have PowerShell
remoting enabled.
These include computers that are not running the Windows
operating system, and computers that have
PowerShell but do not have PowerShell
remoting enabled.

Start by creating a CIM session on the remote computer. A CIM session is a connection
to Windows
Management Instrumentation (WMI) on the remote computer. Then use the
CIMSession parameter of
Get-Module to get CIM modules from the CIM session. When
you import a CIM module by using the
Import-Module cmdlet and then run the
imported commands, the commands run implicitly on the remote
computer. You can
use this WMI and CIM strategy to manage the remote computer.

Examples

Example 1: Get modules imported into the current session


PowerShell

Get-Module

This command gets modules that have been imported into the current session.

Example 2: Get installed modules and available modules


PowerShell

Get-Module -ListAvailable

This command gets the modules that are installed on the computer and 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: Get all exported files


PowerShell

Get-Module -ListAvailable -All


This command gets all of the exported files for all available modules.

Example 4: Get a module by its fully qualified name


PowerShell

$FullyQualifiedName =
@{ModuleName="Microsoft.PowerShell.Management";ModuleVersion="3.1.0.0"}

Get-Module -FullyQualifiedName $FullyQualifiedName | Format-Table -Property


Name,Version

Name Version

---- -------

Microsoft.PowerShell.Management 3.1.0.0

This example gets the Microsoft.PowerShell.Management module by specifying the


fully qualified
name of the module by using the FullyQualifiedName parameter. The
command then pipes the results
into the Format-Table cmdlet to format the results as a
table with Name and Version as the
column headings.

In a fully qualified name for a module, the value ModuleVersion acts as minimum
version. So, for
this example, it matches any Microsoft.PowerShell.Management module
that is version 3.1.0.0 or
higher.

Example 5: Get properties of a module


PowerShell

Get-Module | Get-Member -MemberType Property | Format-Table Name

Name

----

AccessMode

Author

ClrVersion

CompanyName

Copyright

Definition

Description

DotNetFrameworkVersion

ExportedAliases

ExportedCmdlets

ExportedCommands

ExportedFormatFiles

ExportedFunctions

ExportedTypeFiles

ExportedVariables

ExportedWorkflows

FileList

Guid

HelpInfoUri

LogPipelineExecutionDetails

ModuleBase

ModuleList

ModuleType

Name

NestedModules

OnRemove

Path

PowerShellHostName

PowerShellHostVersion

PowerShellVersion

PrivateData

ProcessorArchitecture

RequiredAssemblies

RequiredModules

RootModule

Scripts

SessionState

Version

This command gets 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 PSModuleInfo Properties.

The output includes the new properties, such as Author and CompanyName, that were
introduced
in Windows PowerShell 3.0.

Example 6: Group all modules by name


PowerShell

Get-Module -ListAvailable -All | Format-Table -Property Name, Moduletype,


Path -Groupby Name

Name: AppLocker

Name ModuleType Path

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

AppLocker Manifest
C:\Windows\system32\WindowsPowerShell\v1.0\Modules\AppLocker\AppLocker.psd1

Name: Appx

Name ModuleType Path

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

Appx Manifest C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Appx\en-


US\Appx.psd1

Appx Manifest
C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Appx\Appx.psd1

Appx Script
C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Appx\Appx.psm1

Name: BestPractices

Name ModuleType Path

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

BestPractices Manifest
C:\Windows\system32\WindowsPowerShell\v1.0\Modules\BestPractices\BestPractic
es.psd1

Name: BitsTransfer

Name ModuleType Path

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

BitsTransfer Manifest
C:\Windows\system32\WindowsPowerShell\v1.0\Modules\BitsTransfer\BitsTransfer
.psd1

This command gets all module files, both imported and available, and then groups them
by module
name. This lets you see the module files that each script is exporting.

Example 7: Display the contents of a module manifest


These commands display the contents of the module manifest for the Windows
PowerShell
BitsTransfer module.

Modules are not required to have manifest files. When they do have a manifest file, the
manifest
file is required only to include a version number. However, manifest files often
provide useful
information about a module, its requirements, and its contents.

PowerShell

# First command

$m = Get-Module -list -Name BitsTransfer

# Second command

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"

The first command gets the PSModuleInfo object that represents BitsTransfer module. It
saves the
object in the $m variable.

The second command uses the Get-Content cmdlet to get the content of the manifest
file in the
specified path. It uses dot notation to get the path to the manifest file, which
is stored in the
Path property of the object. The output shows the contents of the
module manifest.

Example 8: List files in module directory


PowerShell

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

This command lists the files in the directory of the module. 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.

Example 9: Get modules installed on a computer


PowerShell

$s = New-PSSession -ComputerName Server01

Get-Module -PSSession $s -ListAvailable


These commands get the modules that are installed on the Server01 computer.

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 PSSession and ListAvailable parameters of Get-Module
to get
the modules in the PSSession in the $s variable.

If you pipe modules from other sessions to the Import-Module cmdlet, Import-Module
imports the
module into the current session by using the implicit remoting feature. This
is equivalent to using
the Import-PSSession cmdlet. You can use the cmdlets from the
module in the current session, but
commands that use these cmdlets actually run the
remote session. For more information, see
Import-Module and
Import-PSSession.

Example 10: Manage a computer that does not run the


Windows operating system
The commands in this example enable you to manage the storage systems of a remote
computer that is
not running the Windows operating system. In this example, because
the administrator of the computer
has installed the Module Discovery WMI provider, the
CIM commands can use the default values, which
are designed for the provider.

PowerShell

$cs = New-CimSession -ComputerName RSDGF03

Get-Module -CimSession $cs -Name Storage | Import-Module

Get-Command Get-Disk

CommandType Name ModuleName

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

Function Get-Disk Storage

Get-Disk

Number Friendly Name OperationalStatus Total Size


Partition Style

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


-----------

0 Virtual HD ATA Device Online 40 GB MBR

The first command uses the New-CimSession cmdlet to create a session on the RSDGF03
remote
computer. The session connects to WMI on the remote computer. The
command saves the CIM session in
the $cs variable.
The second command uses the CIM session in the $cs variable to run a Get-Module
command on the
RSDGF03 computer. The command uses the Name parameter to
specify the Storage module. The command
uses a pipeline operator ( | ) to send the
Storage module to the Import-Module cmdlet, which
imports it into the local session.

The third command runs the Get-Command cmdlet on the Get-Disk command in the
Storage module.
When you import a CIM module into the local session, PowerShell
converts the CDXML files that
represent the CIM module into PowerShell scripts, which
appear as functions in the local session.

The fourth command runs the Get-Disk command. Although the command is typed in
the local session,
it runs implicitly on the remote computer from which it was imported.
The command gets objects from
the remote computer and returns them to the local
session.

Parameters
-All

Indicates that this cmdlet gets all modules in each module folder, including nested
modules,
manifest ( .psd1 ) files, script module ( .psm1 ) files, and binary module
( .dll ) files. Without
this parameter, Get-Module gets only the default module in each
module folder.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-CimNamespace

Specifies the namespace of an alternate CIM provider that exposes CIM modules.
The default value is
the namespace of the Module Discovery WMI provider.

Use this parameter to get CIM modules from computers and devices that are not
running the Windows
operating system.

This parameter was introduced in Windows PowerShell 3.0.


Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-CimResourceUri

Specifies an alternate location for CIM modules. The default value is the resource URI
of the Module
Discovery WMI provider on the remote computer.

Use this parameter to get CIM modules from computers and devices that are not
running the Windows
operating system.

This parameter was introduced in Windows PowerShell 3.0.

Type: Uri

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-CimSession

Specifies a CIM session on the remote computer. Enter a variable that contains the
CIM session or a
command that gets the CIM session, such as a
Get-CimSession
command.

Get-Module uses the CIM session connection to get modules from the remote
computer. When you
import the module by using the Import-Module cmdlet and use
the commands from the imported module
in the current session, the commands
actually run on the remote computer.

You can use this parameter to get modules from computers and devices that are not
running the
Windows operating system, and computers that have PowerShell, but do
not have PowerShell remoting
enabled.

The CimSession parameter gets all modules in the CIMSession. However, you can
import only
CIM-based and Cmdlet Definition XML (CDXML)-based modules.
Type: CimSession

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-FullyQualifiedName

The value can be a module name, a full module specification, or a path to a module
file.

When the value is a path, the path can be fully qualified or relative. A relative path is
resolved
relative to the script that contains the using statement.

When the value is a name or module specification, PowerShell searches the


PSModulePath for the
specified module.

A module specification is a hashtable that has the following keys.

ModuleName - Required Specifies the module name.

GUID - Optional Specifies the GUID of the module.


It's also Required to specify at least one of the three below keys.
ModuleVersion - Specifies a minimum acceptable version of the module.
MaximumVersion - Specifies the maximum acceptable version of the module.

RequiredVersion - Specifies an exact, required version of the module. This

can't be used with


the other Version keys.

You cannot specify the FullyQualifiedName parameter in the same command as a


Name parameter.

Type: ModuleSpecification[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-ListAvailable
Indicates that this cmdlet gets all installed modules. Get-Module gets modules in
paths listed in
the PSModulePath environment variable. Without this parameter,
Get-Module gets only the
modules that are both listed in the PSModulePath

environment variable, and that are loaded in


the current session. ListAvailable does
not return information about modules that are not found
in the PSModulePath
environment variable, even if those modules are loaded in the current
session.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Name

Specifies names or name patterns of modules that this cmdlet gets. Wildcard
characters are
permitted. You can also pipe the names to Get-Module . You cannot
specify the
FullyQualifiedName parameter in the same command as a Name
parameter.

Name cannot accept a module GUID as a value. To return modules by specifying a


GUID, use
FullyQualifiedName instead.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-PSEdition

Gets the modules that support specified edition of PowerShell.

The acceptable values for this parameter are:

Desktop

Core
The Get-Module cmdlet checks CompatiblePSEditions property of PSModuleInfo
object for the
specified value and returns only those modules that have it set.

7 Note

Desktop Edition: Built on .NET Framework and provides compatibility with


scripts and modules
targeting versions of PowerShell running on full
footprint editions of Windows such as Server
Core and Windows Desktop.
Core Edition: Built on .NET Core and provides compatibility with scripts
and modules
targeting versions of PowerShell running on reduced
footprint editions of Windows such as Nano
Server and Windows IoT.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-PSSession

Gets the modules in the specified user-managed PowerShell session (PSSession).


Enter a variable
that contains the session, a command that gets the session, such as a
Get-PSSession command, or a
command that creates the session, such as a New-
PSSession command.

When the session is connected to a remote computer, you must specify the
ListAvailable
parameter.

A Get-Module command that uses the PSSession parameter is equivalent to using


the
Invoke-Command cmdlet to run a Get-Module -ListAvailable command in a
PSSession.

This parameter was introduced in Windows PowerShell 3.0.

Type: PSSession

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-Refresh

Indicates that this cmdlet refreshes the cache of installed commands. The command
cache is created
when the session starts. It enables the Get-Command cmdlet to get
commands from modules that are
not imported into the session.

This parameter is designed for development and testing scenarios in which the
contents of modules
have changed since the session started.

When you specify the Refresh parameter in a command, you must specify
ListAvailable.

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe module names to this cmdlet.

Outputs
PSModuleInfo

This cmdlet returns objects that represent modules. When you specify the ListAvailable
parameter, Get-Module returns a ModuleInfoGrouping object, which is a type of
PSModuleInfo
object that has the same properties and methods.

Notes
Windows PowerShell includes the following aliases for Get-Module :

gmo

Beginning in Windows PowerShell 3.0, the core commands that are included in
PowerShell are
packaged in modules. The exception is Microsoft.PowerShell.Core,
which is a snap-in
(PSSnapin). By default, only the Microsoft.PowerShell.Core
snap-in is added to the
session. Modules are imported automatically on first use
and you can use the Import-Module
cmdlet to import them.

In Windows PowerShell 2.0, and in host programs that create older-style sessions
in later versions
of PowerShell, the core commands are packaged in snap-ins
(PSSnapins). The exception is
Microsoft.PowerShell.Core, which is always a snap-
in. Also, remote sessions, such as those
started by the New-PSSession cmdlet, are
older-style sessions that include core snap-ins.

For information about the CreateDefault2 method that creates newer-style


sessions with core
modules, see
CreateDefault2 Method.

Get-Module only gets modules in locations that are stored in the value of the

PSModulePath
environment variable ( $env:PSModulePath ). The Import-Module
cmdlet can import modules in other
locations, but you cannot use the Get-Module
cmdlet to get them.

Also, starting in PowerShell 3.0, new properties have been added to the object that
Get-Module
returns that make it easier to learn about modules even before they

are imported. All properties


are populated before importing. These include the
ExportedCommands, ExportedCmdlets and
ExportedFunctions properties that list
the commands that the module exports.

The ListAvailable parameter gets only well-formed modules, that is, folders that
contain at
least one file whose base name is the same as the name of the module
folder. The base name is the
name without the file name extension. Folders that
contain files that have different names are
considered to be containers, but not
modules.

To get modules that are implemented as DLL files, but are not enclosed in a
module folder,
specify both the ListAvailable and All parameters.

To use the CIM session feature, the remote computer must have WS-Management
remoting and Windows
Management Instrumentation (WMI), which is the
Microsoft implementation of the Common Information
Model (CIM) standard. The
computer must also have the Module Discovery WMI provider or an
alternate WMI
provider that has the same basic features.

You can use the CIM session feature on computers that are not running the
Windows operating system
and on Windows computers that have PowerShell, but
do not have PowerShell remoting enabled.

You can also use the CIM parameters to get CIM modules from computers that
have PowerShell
remoting enabled. This includes the local computer. When you
create a CIM session on the local
computer, PowerShell uses DCOM, instead of
WMI, to create the session.

Related Links
Get-CimSession
New-CimSession
about_Modules
Get-PSSession
Import-Module
Import-PSSession
New-PSSession
Remove-Module
Get-PSHostProcessInfo
Reference
Module: Microsoft.PowerShell.Core

Gets process information about the PowerShell host.

Syntax
PowerShell

Get-PSHostProcessInfo

[[-Name] <String[]>]

[<CommonParameters>]

PowerShell

Get-PSHostProcessInfo

[-Process] <Process[]>

[<CommonParameters>]

PowerShell

Get-PSHostProcessInfo

[-Id] <Int32[]>

[<CommonParameters>]

Description
The Get-PSHostProcessInfo cmdlet gets information about PowerShell host processes
running on the
local computer.

Beginning in PowerShell 6.2, this cmdlet is supported on non-Windows platforms.

Examples

1: Get a list of PowerShell hosts running on the system


PowerShell
Get-PSHostProcessInfo

ProcessName ProcessId AppDomainName MainWindowTitle

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

powershell 14676 DefaultAppDomain Windows PowerShell

powershell 5184 DefaultAppDomain Windows PowerShell

2: Get PowerShell host information for a specific process


PowerShell

Get-PSHostProcessInfo -Id 14676

ProcessName ProcessId AppDomainName MainWindowTitle

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

powershell 14676 DefaultAppDomain Windows PowerShell

Parameters
-Id

Specifies a process by the process ID. To get a process ID, run the Get-Process
cmdlet.

Type: Int32[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Name

Specifies a process by the process name. To get a process name, run the Get-Process
cmdlet.

Type: String[]

Position: 0

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-Process

Specifies a process by the process object. The simplest way to use this parameter is
to save the
results of a Get-Process command that returns process that you want to
enter in a variable, and
then specify the variable as the value of this parameter.

Type: Process[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

Inputs
Process

You can pipe a Process object from Get-Process to this cmdlet.

Outputs
PSHostProcessInfo

Related Links
Get-Process
Get-PSSession
Reference
Module: Microsoft.PowerShell.Core

Gets the PowerShell sessions on local and remote computers.

Syntax
PowerShell

Get-PSSession

[-Name <String[]>]

[<CommonParameters>]

PowerShell

Get-PSSession

[-ComputerName] <String[]>

[-ApplicationName <String>]

[-ConfigurationName <String>]

[-Name <String[]>]

[-Credential <PSCredential>]

[-Authentication <AuthenticationMechanism>]

[-CertificateThumbprint <String>]

[-Port <Int32>]

[-UseSSL]

[-ThrottleLimit <Int32>]

[-State <SessionFilterState>]

[-SessionOption <PSSessionOption>]

[<CommonParameters>]

PowerShell

Get-PSSession

[-ComputerName] <String[]>

[-ApplicationName <String>]

[-ConfigurationName <String>]

-InstanceId <Guid[]>

[-Credential <PSCredential>]

[-Authentication <AuthenticationMechanism>]

[-CertificateThumbprint <String>]

[-Port <Int32>]

[-UseSSL]

[-ThrottleLimit <Int32>]

[-State <SessionFilterState>]

[-SessionOption <PSSessionOption>]

[<CommonParameters>]

PowerShell

Get-PSSession

[-ConnectionUri] <Uri[]>

[-ConfigurationName <String>]

[-AllowRedirection]

-InstanceId <Guid[]>

[-Credential <PSCredential>]

[-Authentication <AuthenticationMechanism>]

[-CertificateThumbprint <String>]

[-ThrottleLimit <Int32>]

[-State <SessionFilterState>]

[-SessionOption <PSSessionOption>]

[<CommonParameters>]

PowerShell

Get-PSSession

[-ConnectionUri] <Uri[]>

[-ConfigurationName <String>]

[-AllowRedirection]

[-Name <String[]>]

[-Credential <PSCredential>]

[-Authentication <AuthenticationMechanism>]

[-CertificateThumbprint <String>]

[-ThrottleLimit <Int32>]

[-State <SessionFilterState>]

[-SessionOption <PSSessionOption>]

[<CommonParameters>]

PowerShell

Get-PSSession

[-ConfigurationName <String>]

[-Name <String[]>]

[-State <SessionFilterState>]

-ContainerId <String[]>

[<CommonParameters>]

PowerShell

Get-PSSession

[-ConfigurationName <String>]

-InstanceId <Guid[]>

[-State <SessionFilterState>]

-ContainerId <String[]>

[<CommonParameters>]

PowerShell

Get-PSSession

[-ConfigurationName <String>]

[-Name <String[]>]

[-State <SessionFilterState>]

-VMId <Guid[]>

[<CommonParameters>]

PowerShell

Get-PSSession

[-ConfigurationName <String>]

-InstanceId <Guid[]>

[-State <SessionFilterState>]

-VMId <Guid[]>

[<CommonParameters>]

PowerShell

Get-PSSession

[-ConfigurationName <String>]

[-Name <String[]>]

[-State <SessionFilterState>]

-VMName <String[]>

[<CommonParameters>]

PowerShell

Get-PSSession

[-ConfigurationName <String>]

-InstanceId <Guid[]>

[-State <SessionFilterState>]

-VMName <String[]>

[<CommonParameters>]

PowerShell

Get-PSSession

[-InstanceId <Guid[]>]

[<CommonParameters>]

PowerShell
Get-PSSession

[-Id] <Int32[]>

[<CommonParameters>]

Description
The Get-PSSession cmdlet gets the user-managed PowerShell sessions (PSSessions) on
local and
remote computers.

Starting in Windows PowerShell 3.0, sessions are stored on the computers at the remote
end of each
connection. You can use the ComputerName or ConnectionUri parameters
of Get-PSSession to
get the sessions that connect to the local computer or remote
computers, even if they were not
created in the current session.

Without parameters, Get-PSSession gets all sessions that were created in the current
session.

Use the filtering parameters, including Name, ID, InstanceID, State,


ApplicationName,
and ConfigurationName to select from among the sessions that
Get-PSSession returns.

Use the remaining parameters to configure the temporary connection in which the Get-
PSSession
command runs when you use the ComputerName or ConnectionUri

parameters.

7 Note

In Windows PowerShell 2.0, without parameters, Get-PSSession gets all sessions


that were created
in the current session. The ComputerName parameter gets
sessions that were created in the
current session and connect to the specified
computer.

For more information about PowerShell sessions, see about_PSSessions.

Examples

Example 1: Get sessions created in the current session


PowerShell

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: Get sessions connected to the local computer


PowerShell

Get-PSSession -ComputerName "localhost"

This command gets the PSSessions that are connected to the local computer. To
indicate the local
computer, type the computer name, localhost, or a dot ( . )

The command returns all of the sessions on the local computer, even if they were
created in
different sessions or on different computers.

Example 3: Get sessions connected to a computer


PowerShell

Get-PSSession -ComputerName "Server02"

Id Name ComputerName State ConfigurationName


Availability

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


--------

2 Session3 Server02 Disconnected ITTasks


Busy

1 ScheduledJobs Server02 Opened Microsoft.PowerShell


Available

3 Test Server02 Disconnected Microsoft.PowerShell


Busy

This command gets the PSSessions that are connected to the Server02 computer.

The command returns all of the sessions on Server02, even if they were created in
different sessions
or on different computers.

The output shows that two of the sessions have a Disconnected state and a Busy
availability.
They were created in different sessions and are currently in use. The
ScheduledJobs session, which
is Opened and Available , was created in the current
session.
Example 4: Save results of this command
PowerShell

New-PSSession -ComputerName Server01, Server02, Server03

$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 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 5: Delete a session by using an instance ID


PowerShell

Get-PSSession | Format-Table -Property ComputerName, InstanceID

$s = Get-PSSession -InstanceID a786be29-a6bb-40da-80fb-782c67f7db0f

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 that were created in the current session. 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 6: Get a session that has a particular name
The commands in this example find a session that has a particular name format and uses
a particular
session configuration and then connect to the session. You can use a
command like this one to find a
session in which a colleague started a task and connect
to finish the task.

PowerShell

Get-PSSession -ComputerName Server02, Server12 -Name BackupJob* -


ConfigurationName ITTasks -SessionOption @{OperationTimeout=240000}

Id Name ComputerName State ConfigurationName


Availability

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


--------

3 BackupJob04 Server02 Disconnected ITTasks


None

$s = Get-PSSession -ComputerName Server02 -Name BackupJob04 -


ConfigurationName ITTasks | Connect-PSSession

$s

Id Name ComputerName State ConfigurationName


Availability

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


-------

5 BackupJob04 Server02 Opened ITTasks


Available

The first command gets sessions on the Server02 and Server12 remote computers that
have names that
begin with BackupJob and use the ITTasks session configuration.The
command uses the Name
parameter to specify the name pattern and the
ConfigurationName parameter to specify the session
configuration. The value of the
SessionOption parameter is a hash table that sets the value of
the OperationTimeout to
240000 milliseconds (4 minutes). This setting gives the command more
time to

complete.The ConfigurationName and SessionOption parameters are used to configure


the temporary sessions in which the Get-PSSession cmdlet runs on each computer.The
output shows
that the command returns the BackupJob04 session. The session is
disconnected and the
Availability is None , which indicates that it is not in use.

The second command uses the Get-PSSession cmdlet to get to the BackupJob04 session
and the
Connect-PSSession cmdlet to connect to the session. The command saves the
session in the $s
variable.
The third command gets the session in the $s variable. The output shows that the
Connect-PSSession command was successful. The session is in the Opened state and is
available
for use.

Example 7: Get a session by using its ID


PowerShell

Get-PSSession -Id 2

This command gets the PSSession with ID 2 . Because the value of the ID property is
unique
only in the current session, the Id parameter is valid only for local commands.

Parameters
-AllowRedirection

Indicates that this cmdlet allows redirection of this connection to an alternate


Uniform Resource
Identifier (URI). By default, PowerShell does not redirect
connections.

This parameter configures the temporary connection that is created to run a Get-
PSSession command
with the ConnectionUri parameter.

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-ApplicationName

Specifies the name of an application. This cmdlet connects only to sessions that use
the specified
application.

Enter the application name segment of the connection URI. For example, in the
following connection
URI, the application name is WSMan:
http://localhost:5985/WSMAN . The application name of a session
is stored in the

Runspace.ConnectionInfo.AppName property of the session.

The value of this parameter is used to select and filter sessions. It does not change
the
application that the session uses.

Type: String

Position: Named

Default value: All sessions

Accept pipeline input: True

Accept wildcard characters: False

-Authentication

Specifies the mechanism that is used to authenticate credentials for the session in
which the
Get-PSSession command runs.

This parameter configures the temporary connection that is created to run a Get-
PSSession command
with the ComputerName or ConnectionUri parameter.

The acceptable values for this parameter are:

Default

Basic
CredSSP

Digest

Kerberos
Negotiate

NegotiateWithImplicitCredential .

The default value is Default .

For more information about the values of this parameter, see


AuthenticationMechanism Enumeration.

U Caution

Credential Security Support 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.

This parameter was introduced in Windows PowerShell 3.0.

Type: AuthenticationMechanism

Accepted values: Default, Basic, Negotiate, NegotiateWithImplicitCredential,


Credssp, Digest, Kerberos

Position: Named

Default value: Default

Accept pipeline input: False

Accept wildcard characters: False

-CertificateThumbprint

Specifies the digital public key certificate (X509) of a user account that has
permission to create
the session in which the Get-PSSession command runs. Enter
the certificate thumbprint of the
certificate.

This parameter configures the temporary connection that is created to run a Get-
PSSession command
with the ComputerName or ConnectionUri parameter.

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 a Get-Item or Get-ChildItem command in the


PowerShell
Cert: drive.

This parameter was introduced in Windows PowerShell 3.0.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-ComputerName

Specifies an array of names of computers. Gets the sessions that connect to the
specified computers.
Wildcard characters are not permitted. There is no default
value.

Beginning in Windows PowerShell 3.0, PSSession objects are stored on the


computers at the remote
end of each connection. To get the sessions on the
specified computers, PowerShell creates a
temporary connection to each computer
and runs a Get-PSSession command.

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

7 Note

This parameter gets sessions only from computers that run Windows PowerShell
3.0 or later versions
of PowerShell. Earlier versions do not store sessions.

Type: String[]

Aliases: Cn

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-ConfigurationName

Specifies the name of a configuration. This cmdlet gets only to sessions that use the
specified
session configuration.

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 configuration name of
a session is stored in the
ConfigurationName property of the session.

The value of this parameter is used to select and filter sessions. It does not change
the session
configuration that the session uses.
For more information about session configurations, see
about_Session_Configurations.

Type: String

Position: Named

Default value: All sessions

Accept pipeline input: True

Accept wildcard characters: False

-ConnectionUri

Specifies a URI that defines the connection endpoint for the temporary session in
which the
Get-PSSession command runs. The URI must be fully qualified.

This parameter configures the temporary connection that is created to run a Get-
PSSession command
with the ConnectionUri parameter.

The format of this string is:

<Transport>://<ComputerName>:<Port\>/<ApplicationName>

The default value is: http://localhost:5985/WSMAN .

If you do not specify a ConnectionUri, you can use the UseSSL, ComputerName,
Port,
and ApplicationName parameters to specify the ConnectionURI values. Valid
values for the
Transport segment of the URI are HTTP and HTTPS. If you specify a
connection URI with a Transport
segment, but do not specify a port, the session is
created with standards ports: 80 for HTTP and
443 for HTTPS. To use the default
ports for PowerShell remoting, specify port 5985 for HTTP or
5986 for HTTPS.

If the destination computer redirects the connection to a different URI, PowerShell


prevents the
redirection unless you use the AllowRedirection parameter in the
command.

This parameter was introduced in Windows PowerShell 3.0.

This parameter gets sessions only from computers that run Windows PowerShell 3.0
or later versions
of Windows PowerShell. Earlier versions do not store sessions.

Type: Uri[]

Aliases: URI, CU
Position: 0

Default value: Http://localhost:5985/WSMAN

Accept pipeline input: True

Accept wildcard characters: False

-ContainerId

Specifies an array of IDs of containers. This cmdlet starts an interactive session with
each of the
specified containers. Use the docker ps command to get a list of
container IDs. For more
information, see the help for the
docker ps command.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Credential

Specifies a user credential. This cmdlet runs the command with the permissions of
the specified
user. Specify a user account that has permission to connect to the
remote computer and run a
Get-PSSession command. The default is the current user.

Type a user name, such as User01 or Domain01\User01 , or enter a PSCredential


object
generated by the Get-Credential cmdlet. If you type a user name, you're
prompted to enter the
password.

Credentials are stored in a PSCredential


object and the password is stored as a
SecureString.

7 Note

For more information about SecureString data protection, see


How secure is
SecureString?.

This parameter configures to the temporary connection that is created to run a Get-
PSSession
command with the ComputerName or ConnectionUri parameter.
This parameter was introduced in Windows PowerShell 3.0.

Type: PSCredential

Position: Named

Default value: Current user

Accept pipeline input: False

Accept wildcard characters: False

-Id

Specifies an array of session IDs. This cmdlet gets only the sessions with the specified
IDs. Type
one or more IDs, separated by commas, or use the range operator ( .. ) to
specify a range of IDs.
You cannot use the ID parameter together with the
ComputerName parameter.

An ID is an integer that uniquely identifies the user-managed sessions in the current


session. It is
easier to remember and type than the InstanceId, but it is unique only
within the current
session. The ID of a session is stored in the ID property of the
session.

Type: Int32[]

Position: 0

Default value: All sessions

Accept pipeline input: True

Accept wildcard characters: False

-InstanceId

Specifies an array of instance IDs of sessions. This cmdlet gets only the sessions with
the
specified instance IDs.

The instance ID is a GUID that uniquely identifies a session on a local or remote


computer. The
InstanceID is unique, even when you have multiple sessions running
in PowerShell.

The instance ID of a session is stored in the InstanceID property of the session.

Type: Guid[]
Position: Named

Default value: All sessions

Accept pipeline input: False

Accept wildcard characters: False

-Name

Specifies an array of session names. This cmdlet gets only the sessions that have the
specified
friendly names. Wildcard characters are permitted.

The friendly name of a session is stored in the Name property of the session.

Type: String[]

Position: Named

Default value: All sessions

Accept pipeline input: True

Accept wildcard characters: True

-Port

Specifies the specified network port that is used for the temporary connection in
which the
Get-PSSession command runs. To connect to a remote computer, the
remote computer must be listening
on the port that the connection uses. The default
ports are 5985 , which is the WinRM port for
HTTP, and 5986 , which is the WinRM
port for HTTPS.

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 PowerShell
prompt:

Remove-Item -Path WSMan:\Localhost\listener\listener* -Recurse

New-Item -Path WSMan:\Localhost\listener -Transport http -Address * -Port \

<port-number\>

This parameter configures to the temporary connection that is created to run a Get-
PSSession
command with the ComputerName or ConnectionUri parameter.
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.

This parameter was introduced in Windows PowerShell 3.0.

Type: Int32

Position: Named

Default value: 5985, 5986

Accept pipeline input: False

Accept wildcard characters: False

-SessionOption

Specifies advanced options for the session. Enter a SessionOption object, such as
one that you
create by using the New-PSSessionOption cmdlet, or a hash table in
which the keys are session
option names and the values are session option values.

The default values for the options are determined by the value of the
$PSSessionOption preference
variable, if it is set. Otherwise, the default values are
established by options set in the session
configuration.

The session option values take precedence over default values for sessions set in the
$PSSessionOption preference variable and in the session configuration. However,

they do not take


precedence over maximum values, quotas or limits set in the
session configuration.

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. For more information about
session configurations,
see about_Session_Configurations.

Type: PSSessionOption

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-State

Specifies a session state. This cmdlet gets only sessions in the specified state. The
acceptable
values for this parameter are: All , Opened , Disconnected , Closed , and
Broken . The default
value is All .

The session state value is relative to the current sessions. Sessions that were not
created in the
current sessions and are not connected to the current session have a
state of Disconnected even when
they are connected to a different session.

The state of a session is stored in the State property of the session.

This parameter was introduced in Windows PowerShell 3.0.

Type: SessionFilterState

Accepted values: All, Opened, Disconnected, Closed, Broken

Position: Named

Default value: All

Accept pipeline input: False

Accept wildcard characters: False

-ThrottleLimit

Specifies the maximum number of concurrent connections that can be established to


run the
Get-PSSession 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.

This parameter was introduced in Windows PowerShell 3.0.

Type: Int32

Position: Named

Default value: 32

Accept pipeline input: False

Accept wildcard characters: False

-UseSSL
Indicates that this cmdlet uses the Secure Sockets Layer (SSL) protocol to establish
the connection
in which the Get-PSSession command runs. By default, SSL is not
used. If you use this parameter,
but SSL is not available on the port used for the
command, the command fails.

This parameter configures the temporary connection that is created to run a Get-
PSSession command
with the ComputerName parameter.

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-VMId

Specifies an array of ID of virtual machines. This cmdlet starts an interactive session


with each of
the specified virtual machines. To see the virtual machines that are
available to you, use the
following command:

Get-VM | Select-Object -Property Name, ID

Type: Guid[]

Aliases: VMGuid

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-VMName

Specifies an array of names of virtual machines. This cmdlet starts an interactive


session with each
of the specified virtual machines. To see the virtual machines that
are available to you, use the
Get-VM cmdlet.

Type: String[]
Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
PSSession

Notes
Windows PowerShell includes the following aliases for Get-PSSession :

gsn

This cmdlet gets user-managed sessions PSSession objects" such as those that are
created by
using the New-PSSession , Enter-PSSession , and Invoke-Command
cmdlets. It does not get the
system-managed session that is created when you
start PowerShell.

Starting in Windows PowerShell 3.0, PSSession objects are stored on the computer
that is at
the server-side or receiving end of a connection. To get the sessions that
are stored on the local
computer or a remote computer, PowerShell establishes a
temporary session to the specified
computer and runs query commands in the
session.

To get sessions that connect to a remote computer, use the ComputerName or


ConnectionUri
parameters to specify the remote computer. To filter the sessions
that Get-PSSession gets, use
the Name, ID, InstanceID, and State parameters. Use
the remaining parameters to
configure the temporary session that Get-PSSession
uses.
When you use the ComputerName or ConnectionUri parameters, Get-PSSession
gets only
sessions from computers running Windows PowerShell 3.0 and later
versions of PowerShell.

The value of the State property of a PSSession is relative to the current session.
Therefore, a value of Disconnected means that the PSSession is not connected to
the
current session. However, it does not mean that the PSSession is disconnected
from all
sessions. It might be connected to a different session. To determine
whether you can connect or
reconnect to the PSSession from the current session,
use the Availability property.

An Availability value of None indicates that you can connect to the session. A value of
Busy indicates that you cannot connect to the PSSession because it is connected to
another
session.

For more information about the values of the State property of sessions, see
RunspaceState Enumeration.

For more information about the values of the Availability property of sessions, see
RunspaceAvailability Enumeration.

Related Links
Connect-PSSession
Disconnect-PSSession
Receive-PSSession
Enter-PSSession
Exit-PSSession
Invoke-Command
New-PSSession
Remove-PSSession
about_PSSessions
about_Remote
Get-PSSessionCapability
Reference
Module: Microsoft.PowerShell.Core

Gets the capabilities of a specific user on a constrained session configuration.

Syntax
PowerShell

Get-PSSessionCapability

[-ConfigurationName] <String>

[-Username] <String>

[-Full]

[<CommonParameters>]

Description
The Get-PSSessionCapability cmdlet gets the capabilities of a specific user on a
constrained
session configuration. Use this cmdlet to audit customized session
configurations for users.

Starting in Windows PowerShell 5.0, you can use the RoleDefinitions property in a
session
configuration ( .pssc ) file. Using this property lets you grant users different
capabilities on a
single constrained endpoint based on group membership. The Get-
PSSessionCapability cmdlet reduces
complexity when auditing these endpoints by

letting you determine the exact capabilities granted to


a user.

By default, the Get-PSSessionCapability cmdlet returns a list of commands the specified


user can
run in the specified endpoint. This is equivalent to the user running Get-
Command in the specified
endpoint. When run with the Full parameter, this cmdlet returns
an InitialSessionState
object. This object contains details about the Windows PowerShell
runspace the specified user would
interact with for the specified endpoint. It includes
information such as Language Mode, Execution
Policy, and Environmental Variables.

Examples

Example 1: Get commands available for a user


PowerShell

Get-PSSessionCapability -ConfigurationName Endpoint1 -Username


'CONTOSO\User'

This example returns the commands available to the user CONTOSO\User when
connecting to the
Endpoint1 constrained endpoint on the local computer.

Example 2: Get details about a runspace for a user


PowerShell

Get-PSSessionCapability -ConfigurationName Endpoint1 -Username


'CONTOSO\User' -Full

This example returns details about the runspace the user CONTOSO\User would interact
with when
connecting to the Endpoint1 constrained endpoint.

Parameters
-ConfigurationName

Specifies the constrained session configuration (endpoint) that you are inspecting.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Full

Indicates that this cmdlet returns the entire initial session state for the specified user
at the
specified constrained endpoint.

Type: SwitchParameter

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-Username

Specifies the user whose capabilities you are inspecting.

Type: String

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Outputs
AliasInfo

FunctionInfo

InitialSessionState

Related Links
New-PSRoleCapabilityFile
Get-PSSessionConfiguration
Reference
Module: Microsoft.PowerShell.Core

Gets the registered session configurations on the computer.

Syntax
PowerShell

Get-PSSessionConfiguration

[[-Name] <String[]>]

[-Force]

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

Beginning in PowerShell 3.0, you can define the properties of a session configuration by
using a
session configuration (.pssc) file. This feature lets you create customized and
restricted sessions
without writing a computer program. For more information about
session configuration files, see
about_Session_Configuration_Files.

Also, beginning in PowerShell 3.0, new note properties have been added to the session
configuration
object that Get-PSSessionConfiguration returns. These properties make it
easier for users and
session configuration authors to examine and compare session
configurations.

To create and register a session configuration, use the Register-PSSessionConfiguration


cmdlet.
For more information about session configurations, see
about_Session_Configurations.

Examples
Example 1 - Get session configurations on the local
computer
PowerShell

Get-PSSessionConfiguration

Example 2 - Get the two default session configurations


The command uses the Name parameter of Get-PSSessionConfiguration to get only the
session
configurations with names that begin with "Microsoft".

PowerShell

Get-PSSessionConfiguration -Name Microsoft*

Name PSVersion StartupScript Permission

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

microsoft.powershell 5.1
BUILTIN\Administrators AccessAll...

microsoft.powershell32 5.1
BUILTIN\Administrators AccessAll...

Example 3 - Get the properties and values of a session


configuration
This example shows the properties and property values of a session configuration that
was created
by using a session configuration file.

PowerShell

Get-PSSessionConfiguration -Name Full | Format-List -Property *

Copyright : (c) 2011 User01. All rights reserved.

AliasDefinitions : {System.Collections.Hashtable}

SessionType : Default

CompanyName : Unknown

GUID : 1e9cb265-dae0-4bd3-89a9-8338a47698a1

Author : User01

ExecutionPolicy : Restricted

SchemaVersion : 1.0.0.0

LanguageMode : FullLanguage

Architecture : 64

Filename : %windir%\system32\pwrshplugin.dll

ResourceUri : http://schemas.microsoft.com/powershell/Full

MaxConcurrentCommandsPerShell : 1500

UseSharedProcess : false

ProcessIdleTimeoutSec : 0
xmlns :
http://schemas.microsoft.com/wbem/wsman/1/config/PluginConfiguration

MaxConcurrentUsers : 10

lang : en-US

SupportsOptions : true

ExactMatch : true

configfilepath :
C:\WINDOWS\System32\WindowsPowerShell\v1.0\SessionConfig\Full_1e9cb265-dae0-
4bd3-89a9-8338a47698a1.pssc

RunAsUser :

IdleTimeoutms : 7200000

PSVersion : 3.0

OutputBufferingMode : Block

AutoRestart : false

MaxShells : 300

MaxMemoryPerShellMB : 1024

MaxIdleTimeoutms : 43200000

SDKVersion : 1
Name : Full

XmlRenderingType : text

Capability : {Shell}

RunAsPassword :

MaxProcessesPerShell : 25

Enabled : True

MaxShellsPerUser : 30

Permission :

The example uses the Get-PSSessionConfiguration cmdlet to get the full session
configuration. A
pipeline operator sends the Full session configuration to the Format-
List cmdlet. The Property
parameter with a value of * (all) directs Format-List to
display all the properties and values
of the object in a list.

The output includes useful information, including the author of the session
configuration, the
session type, language mode, and execution policy of sessions that
are created with this session
configuration, session quotas, and the full path to the
session configuration file.

This view of a session configuration is used for sessions that include a session
configuration file.
For more information about session configuration files, see
about_Session_Configuration_Files.

Example 4 - Another way to look at the session


configurations
This example 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.

PowerShell

dir wsman:\localhost\plugin

Type Keys Name

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

Container {Name=Event Forwarding Plugin} Event Forwarding Plugin

Container {Name=Full} Full

Container {Name=microsoft.powershell} microsoft.powershell

Container {Name=microsoft.powershell.workf...
microsoft.powershell.workflow

Container {Name=microsoft.powershell32} microsoft.powershell32

Container {Name=microsoft.ServerManager} microsoft.ServerManager

Container {Name=WMI Provider} WMI Provider

The PlugIn node contains ContainerElement objects


(Microsoft.WSMan.Management.WSManConfigContainerElement) that represent the
registered PowerShell
session configurations, along with other plug-ins for WS-
Management.

Example 6 - View session configurations on a remote


computer
This example shows how to use the WSMan provider to view the session configurations
on a remote
computer. This method does not provide as much information as a Get-
PSSessionConfiguration
command, but the user does not need to be a member of the
Administrators group to run this cmdlet.

PowerShell

Connect-WSMan -ComputerName Server01

dir WSMan:\Server01\Plugin

WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Plugin

Type Keys Name

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

Container {Name=Empty} Empty

Container {Name=Event Forwarding Plugin} Event Forwarding Plugin

Container {Name=Full} Full

Container {Name=microsoft.powershell} microsoft.powershell

Container {Name=microsoft.powershell.workf...
microsoft.powershell.workflow

Container {Name=microsoft.powershell32} microsoft.powershell32

Container {Name=microsoft.ServerManager} microsoft.ServerManager

Container {Name=NoLanguage} NoLanguage

Container {Name=RestrictedLang} RestrictedLang

Container {Name=RRS} RRS

Container {Name=SEL Plugin} SEL Plugin

Container {Name=WithProfile} WithProfile

Container {Name=WMI Provider} WMI Provider

The Connect-WSMan cmdlet connects to the WinRM service on the Server01 remote
computer. The
Get-ChildItem cmdlet (alias dir ) of the WSMan: drive gets the items in
the Server01\Plugin
path. The output shows the items in the Plugin directory on the
Server01 computer. The items include
the session configurations, which are a type of
WSMan plug-in, along with other types of plug-ins on
the computer.

Example 7 - Get detailed session configurations from a


remote computer
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
and remote computers and you must start PowerShell with the Run
as administrator option.

PowerShell

Enable-WSManCredSSP -Delegate Server02

Connect-WSMan Server02

Set-Item WSMan:\Server02*\Service\Auth\CredSSP -Value $true

Invoke-Command -ScriptBlock {Get-PSSessionConfiguration} -ComputerName


Server02 -Authentication CredSSP -Credential Domain01\Admin01

Name PSVersion StartupScript Permission


PSComputerName

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


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

microsoft.powershell 5.1
BUILTIN\Administrators AccessAll... server02.corp.fabrikam.com

microsoft.powershell32 5.1
BUILTIN\Administrators AccessAll... server02.corp.fabrikam.com

MyX86Shell 5.1 c:\test\x86Shell.ps1


BUILTIN\Administrators AccessAll... server02.corp.fabrikam.com

The Enable-WSManCredSSP cmdlet enables CredSSP delegation on Server01, the local


computer. The
Connect-WSMan cmdlet connects to Server02 computer. This action adds a
node for Server02 to the
WSMan: drive on the local computer, allowing you to view and
change the WS-Management settings on
the Server02 computer. The Set-Item cmdlet
changes 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 Invoke-Command
cmdlet runs the Get-PSSessionConfiguration command on the
Server02 computer. The
command uses the Credential parameter, and it uses the Authentication
parameter with
a value of CredSSP. The output shows the session configurations on the Server02
remote computer.

Example 8 - Get the resource URI of a session


configuration
This example is useful for setting the value of the $PSSessionConfigurationName
preference
variable, which takes a resource URI.

PowerShell

(Get-PSSessionConfiguration -Name CustomShell).resourceURI

http://schemas.microsoft.com/powershell/microsoft.CustomShell

The $PSSessionConfigurationName 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.

Parameters
-Force

Suppresses the prompt to restart the WinRM service, if the service is not already
running.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-Name

Gets only the session configurations with the specified name or name pattern. Enter
one or more
session configuration names. Wildcards are permitted.

Type: String[]

Position: 0

Default value: All session configurations on the local computer

Accept pipeline input: False

Accept wildcard characters: True

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
Microsoft.PowerShell.Commands.PSSessionConfigurationCommands

Notes
To run this cmdlet, start 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. Also,
you must use the CredSSP
value of the Authentication parameter when establishing the
remote session.
Otherwise, access is denied.

The note properties of the object that Get-PSSessionConfiguration returns appear


on the object
only when they have a value. Only session configurations that were
created by using a session
configuration file have all the defined properties.
The properties of a session configuration object vary with the options set for the
session
configuration and the values of those options. Also, session configurations
that use a session
configuration file have additional properties.

You can use commands in the WSMan: drive to change the properties of session
configurations.
However, you cannot use the WSMan: drive in PowerShell 2.0 to
change session configuration
properties that are introduced in PowerShell 3.0,
such as OutputBufferingMode. PowerShell 2.0
commands do not generate an
error, but they are ineffective. To change properties introduced in
PowerShell 3.0,
use the WSMan: drive in PowerShell 3.0.

Related Links
Disable-PSSessionConfiguration
Enable-PSSessionConfiguration
Get-PSSessionConfiguration
New-PSSessionConfigurationFile
New-PSSessionOption
Register-PSSessionConfiguration
Set-PSSessionConfiguration
Test-PSSessionConfigurationFile
Unregister-PSSessionConfiguration
WSMan Provider
about_Session_Configurations
about_Session_Configuration_Files
Get-PSSnapin
Reference
Module: Microsoft.PowerShell.Core

Gets the Windows PowerShell snap-ins on the computer.

Syntax
PowerShell

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. This cmdlet lists the
snap-ins 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 .

Starting in Windows PowerShell 3.0, the core commands that are included in Windows
PowerShell are
packaged in modules. The exception is Microsoft.PowerShell.Core, which
is a snap-in (PSSnapin).
By default, only the Microsoft.PowerShell.Core snap-in is added
to the session. Modules are
imported automatically on first use and you can use the
Import-Module cmdlet to import them.

Examples

Example 1: Get snap-ins that are currently loaded


PowerShell

PS C:\> 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: Get snap-ins that have been registered


PowerShell

PS C:\> 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: Get current snap-ins that match a string


PowerShell

PS C:\> Get-PSSnapIn -Name smp*

This command gets the Windows PowerShell snap-ins in the current session that have
names that begin
with smp.

Parameters
-Name

Specifies an array of snap-in names. This cmdlet gets only the specified Windows
PowerShell
snap-ins. Wildcard characters are permitted.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-Registered

Indicates that this cmdlet 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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You cannot pipe input to this cmdlet.

Outputs
PSSnapInInfo

Get-PSSnapin returns an object for each snap-in that it gets.

Notes
Starting in Windows PowerShell 3.0, the core commands that are installed with Windows
PowerShell are
packaged in modules. In Windows PowerShell 2.0, and in host programs
that create older-style
sessions in later versions of Windows PowerShell, the core
commands are packaged in snap-ins
(PSSnapin). The exception is
Microsoft.PowerShell.Core, which is always a snap-in. Also,
remote sessions, such as
those started by the New-PSSession cmdlet, are older-style sessions that
include core
snap-ins.

For information about the CreateDefault2 method that creates newer-style sessions
with core
modules, see
CreateDefault2 Method.
Related Links
Add-PSSnapin
Remove-PSSnapin
Get-Verb
Reference
Module: Microsoft.PowerShell.Core

Gets approved PowerShell verbs.

Syntax
PowerShell

Get-Verb

[[-verb] <String[]>]

[<CommonParameters>]

Description
The Get-Verb function gets verbs that are approved for use in PowerShell commands.

PowerShell recommends cmdlet and function names have the Verb-Noun format and
include an approved
verb. This practice makes command names more consistent,
predictable, and easier to use.

Commands that use unapproved verbs run in PowerShell. However, when you import a
module that
includes a command with an unapproved verb in its name, the Import-
Module command displays a
warning message.

7 Note

The verb list that Get-Verb returns might not be complete. For an updated list of
approved
PowerShell verbs with descriptions, see
Approved Verbs.

Examples

Example 1 - Get a list of all verbs


PowerShell

Get-Verb
Example 2 - Get a list of approved verbs that begin with
"un"
PowerShell

Get-Verb un*

Verb Group

---- -----

Undo Common

Unlock Common

Unpublish Data

Uninstall Lifecycle

Unregister Lifecycle

Unblock Security

Unprotect Security

Example 3 - Get all approved verbs in the Security group


PowerShell

Get-Verb | Where-Object Group -EQ Security

Verb Group

---- -----

Block Security

Grant Security

Protect Security

Revoke Security

Unblock Security

Unprotect Security

Example 4 - Finds all commands in a module that have


unapproved verbs
PowerShell

Get-Command -Module Microsoft.PowerShell.Utility | Where-Object Verb -NotIn


(Get-Verb).Verb

CommandType Name Version Source

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

Cmdlet Sort-Object 3.1.0.0 Microsoft.PowerShell.Utility

Cmdlet Tee-Object 3.1.0.0 Microsoft.PowerShell.Utility


Parameters
-Verb

Gets only the specified verbs. Enter the name of a verb or a name pattern. Wildcards
are allowed.

Type: String[]

Position: 1

Default value: All verbs

Accept pipeline input: True

Accept wildcard characters: True

Inputs
None

Outputs
Selected.Microsoft.PowerShell.Commands.MemberDefinition

Notes
Get-Verb returns a modified version of a

Microsoft.PowerShell.Commands.MemberDefinition
object. The object doesn't have
the standard properties of a MemberDefinition object. Instead it
has Verb and Group
properties. The Verb property contains a string with the verb name.
The Group property
contains a string with the verb group.

PowerShell verbs are assigned to a group based on their most common use. The groups
are designed to
make the verbs easy to find and compare, not to restrict their use. You
can use any approved verb
for any type of command.

Each PowerShell verb is assigned to one of the following groups.

Common: Define generic actions that can apply to almost any cmdlet, such as Add.
Communications: Define actions that apply to communications, such as Connect.
Data: Define actions that apply to data handling, such as Backup.
Diagnostic: Define actions that apply to diagnostics, such as Debug.
Lifecycle: Define actions that apply to the lifecycle of a cmdlet, such as Complete.
Security: Define actions that apply to security, such as Revoke.
Other: Define other types of actions.

Some of the cmdlets installed with PowerShell, such as Tee-Object and Where-Object ,
use
unapproved verbs. These cmdlets are historic exceptions and their verbs are
classified as
reserved.

Related Links
Import-Module
Import-Module
Reference
Module: Microsoft.PowerShell.Core

Adds modules to the current session.

Syntax
PowerShell

Import-Module

[-Global]

[-Prefix <String>]

[-Name] <String[]>

[-Function <String[]>]

[-Cmdlet <String[]>]

[-Variable <String[]>]

[-Alias <String[]>]

[-Force]

[-PassThru]

[-AsCustomObject]

[-MinimumVersion <Version>]
[-MaximumVersion <String>]

[-RequiredVersion <Version>]

[-ArgumentList <Object[]>]

[-DisableNameChecking]

[-NoClobber]

[-Scope <String>]

[<CommonParameters>]

PowerShell

Import-Module

[-Global]

[-Prefix <String>]

[-Name] <String[]>

[-Function <String[]>]

[-Cmdlet <String[]>]

[-Variable <String[]>]

[-Alias <String[]>]

[-Force]

[-PassThru]

[-AsCustomObject]

[-MinimumVersion <Version>]
[-MaximumVersion <String>]

[-RequiredVersion <Version>]

[-ArgumentList <Object[]>]

[-DisableNameChecking]

[-NoClobber]

[-Scope <String>]

-PSSession <PSSession>

[<CommonParameters>]

PowerShell

Import-Module

[-Global]

[-Prefix <String>]

[-Name] <String[]>

[-Function <String[]>]

[-Cmdlet <String[]>]

[-Variable <String[]>]

[-Alias <String[]>]

[-Force]

[-PassThru]

[-AsCustomObject]

[-MinimumVersion <Version>]
[-MaximumVersion <String>]

[-RequiredVersion <Version>]

[-ArgumentList <Object[]>]

[-DisableNameChecking]

[-NoClobber]

[-Scope <String>]

-CimSession <CimSession>

[-CimResourceUri <Uri>]

[-CimNamespace <String>]

[<CommonParameters>]

PowerShell

Import-Module

[-Global]

[-Prefix <String>]

[-FullyQualifiedName] <ModuleSpecification[]>

[-Function <String[]>]

[-Cmdlet <String[]>]

[-Variable <String[]>]

[-Alias <String[]>]

[-Force]

[-PassThru]

[-AsCustomObject]

[-ArgumentList <Object[]>]

[-DisableNameChecking]

[-NoClobber]

[-Scope <String>]

[<CommonParameters>]

PowerShell
Import-Module

[-Global]

[-Prefix <String>]

[-FullyQualifiedName] <ModuleSpecification[]>

[-Function <String[]>]

[-Cmdlet <String[]>]

[-Variable <String[]>]

[-Alias <String[]>]

[-Force]

[-PassThru]

[-AsCustomObject]

[-ArgumentList <Object[]>]

[-DisableNameChecking]

[-NoClobber]

[-Scope <String>]

-PSSession <PSSession>

[<CommonParameters>]

PowerShell

Import-Module

[-Global]

[-Prefix <String>]

[-Assembly] <Assembly[]>

[-Function <String[]>]

[-Cmdlet <String[]>]

[-Variable <String[]>]

[-Alias <String[]>]

[-Force]

[-PassThru]

[-AsCustomObject]

[-ArgumentList <Object[]>]

[-DisableNameChecking]

[-NoClobber]

[-Scope <String>]

[<CommonParameters>]

PowerShell

Import-Module

[-Global]

[-Prefix <String>]

[-Function <String[]>]

[-Cmdlet <String[]>]

[-Variable <String[]>]

[-Alias <String[]>]

[-Force]

[-PassThru]

[-AsCustomObject]

[-ModuleInfo] <PSModuleInfo[]>

[-ArgumentList <Object[]>]

[-DisableNameChecking]

[-NoClobber]

[-Scope <String>]

[<CommonParameters>]

Description
The Import-Module cmdlet adds one or more modules to the current session. Starting in
PowerShell
3.0, installed modules are automatically imported to the session when you
use any commands or
providers in the module. However, you can still use the Import-
Module command to import a module.
You can disable automatic module importing

using the $PSModuleAutoloadingPreference preference


variable. For more information
about the $PSModuleAutoloadingPreference variable, see
about_Preference_Variables.

A module is a package that contains members that can be used in PowerShell. Members
include cmdlets,
providers, scripts, functions, variables, and other tools and files. After a
module is imported, you
can use the module members in your session. For more
information about modules, see
about_Modules.

By default, Import-Module imports all members that the module exports, but you can
use the
Alias, Function, Cmdlet, and Variable parameters to restrict which members are
imported. The NoClobber parameter prevents Import-Module from importing members
that have the
same names as members in the current session.

Import-Module imports a module only into the current session. To import the module
into every new
session, add an Import-Module command to your PowerShell profile. For
more information about
profiles, see about_Profiles.

You can manage remote Windows computers that have PowerShell remoting enabled by
creating a
PSSession on the remote computer. Then use the PSSession parameter of
Import-Module to
import the modules that are installed on the remote computer. When
you use the imported commands in
the current session the commands implicitly run on
the remote computer.

Starting in Windows PowerShell 3.0, you can use Import-Module to import Common
Information Model
(CIM) modules. CIM modules define cmdlets in Cmdlet Definition
XML (CDXML) files. This feature lets
you use cmdlets that are implemented in non-
managed code assemblies, such as those written in C++.

For remote computers that don't have PowerShell remoting enabled, including
computers that aren't
running the Windows operating system, you can use the
CIMSession parameter of Import-Module to
import CIM modules from the remote
computer. The imported commands run implicitly on the remote
computer. A
CIMSession is a connection to Windows Management Instrumentation (WMI) on the
remote
computer.

Examples

Example 1: Import the members of a module into the


current session
This example imports the members of the PSDiagnostics module into the current
session.

PowerShell

Import-Module -Name PSDiagnostics

Example 2: Import all modules specified by the module


path
This example imports all available modules in the path specified by the
$env:PSModulePath
environment variable into the current session.

PowerShell

Get-Module -ListAvailable | Import-Module

Example 3: Import the members of several modules into


the current session
This example imports the members of the PSDiagnostics and Dism modules into the
current session.

PowerShell

$m = Get-Module -ListAvailable PSDiagnostics, Dism

Import-Module -ModuleInfo $m

The Get-Module cmdlet gets the PSDiagnostics and Dism modules and saves the
objects
in the $m variable. The ListAvailable parameter is required when you're getting
modules
that aren't yet imported into the session.

The ModuleInfo parameter of Import-Module is used to import the modules into the
current
session.

Example 4: Import all modules specified by a path


This example uses an explicit path to identify the module to import.

PowerShell

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

VERBOSE: Exporting function 'Get-Specification'.

VERBOSE: Exporting function 'Get-SpecDetails'.

Using the Verbose parameter causes Import-Module to report progress as it loads the
module.
Without the Verbose, PassThru, or AsCustomObject parameter, Import-Module
does not
generate any output when it imports a module.

Example 5: Restrict module members imported into a


session
This example shows how to restrict which module members are imported into the
session and the effect
of this command on the session. The Function parameter limits
the members that are imported from
the module. You can also use the Alias, Variable,
and Cmdlet parameters to restrict
other members that a module imports.

The Get-Module cmdlet gets the object that represents the PSDiagnostics module. The
ExportedCmdlets property lists all the cmdlets that the module exports, even though
they were
not all imported.

PowerShell

Import-Module PSDiagnostics -Function Disable-PSTrace, Enable-PSTrace

(Get-Module PSDiagnostics).ExportedCommands

Key Value

--- -----

Disable-PSTrace Disable-PSTrace

Disable-PSWSManCombinedTrace Disable-PSWSManCombinedTrace

Disable-WSManTrace Disable-WSManTrace

Enable-PSTrace Enable-PSTrace

Enable-PSWSManCombinedTrace Enable-PSWSManCombinedTrace

Enable-WSManTrace Enable-WSManTrace

Get-LogProperties Get-LogProperties

Set-LogProperties Set-LogProperties

Start-Trace Start-Trace

Stop-Trace Stop-Trace

Get-Command -Module PSDiagnostics

CommandType Name Version Source

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

Function Disable-PSTrace 6.1.0.0 PSDiagnostics

Function Enable-PSTrace 6.1.0.0 PSDiagnostics

Using the Module parameter of the Get-Command cmdlet shows the commands that were
imported
from the PSDiagnostics module. The results confirm that only the Disable-
PSTrace and
Enable-PSTrace cmdlets were imported.

Example 6: Import the members of a module and add a


prefix
This example imports the PSDiagnostics module into the current session, adds a prefix
to the
member names, and then displays the prefixed member names. The Prefix
parameter of
Import-Module adds the x prefix to all members that are imported from the
module. The prefix
applies only to the members in the current session. It does not
change the module. The PassThru
parameter returns a module object that represents
the imported module.

PowerShell

Import-Module PSDiagnostics -Prefix x -PassThru

ModuleType Version Name ExportedCommands

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

Script 6.1.0.0 PSDiagnostics {Disable-xPSTrace, Disable-


xPSWSManCombinedTrace, Disable-xW...

Get-Command -Module PSDiagnostics

CommandType Name Version Source

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

Function Disable-xPSTrace 6.1.0.0


PSDiagnostics

Function Disable-xPSWSManCombinedTrace 6.1.0.0


PSDiagnostics

Function Disable-xWSManTrace 6.1.0.0


PSDiagnostics

Function Enable-xPSTrace 6.1.0.0


PSDiagnostics

Function Enable-xPSWSManCombinedTrace 6.1.0.0


PSDiagnostics

Function Enable-xWSManTrace 6.1.0.0


PSDiagnostics

Function Get-xLogProperties 6.1.0.0


PSDiagnostics

Function Set-xLogProperties 6.1.0.0


PSDiagnostics

Function Start-xTrace 6.1.0.0


PSDiagnostics

Function Stop-xTrace 6.1.0.0


PSDiagnostics

Get-Command gets the members that have been imported from the module. The output
shows that the
module members were correctly prefixed.

Example 7: Get and use a custom object


This example demonstrates how to get and use the custom object returned by Import-
Module .

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 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 when importing a script module. Use
Get-Module
to determine which of the available modules is a script module.

PowerShell

Get-Module -List | Format-Table -Property Name, ModuleType -AutoSize

Name ModuleType

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

Show-Calendar Script

BitsTransfer Manifest

PSDiagnostics Manifest

TestCmdlets Script

...

$a = Import-Module -Name Show-Calendar -AsCustomObject -Passthru

$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();

$a."Show-Calendar"()

The Show-Calendar script module is imported using the AsCustomObject parameter to


request a
custom object and the PassThru parameter to return the object. The resulting
custom object is
saved in the $a variable.

The $a variable is piped to the Get-Member cmdlet to show the properties and methods
of the
saved object. The output shows a Show-Calendar script method.

To call the Show-Calendar script method, the method name must be enclosed in
quotation marks
because the name includes a hyphen.

Example 8: Reimport a module into the same session


This example shows how to use the Force parameter of Import-Module when you're
reimporting a
module into the same session. The Force parameter removes the loaded
module and then imports it
again.

PowerShell

Import-Module PSDiagnostics

Import-Module PSDiagnostics -Force -Prefix PS

The first command imports the PSDiagnostics module. The second command imports
the module again,
this time using the Prefix parameter.

Without the Force parameter, the session would include two copies of each
PSDiagnostics
cmdlet, one with the standard name and one with the prefixed name.

Example 9: Run commands that have been hidden by


imported commands
This example shows how to run commands that have been hidden by imported
commands. The
TestModule module includes a function named Get-Date that returns
the year and day of the
year.

PowerShell

Get-Date

Thursday, August 15, 2019 2:26:12 PM

Import-Module TestModule

Get-Date

19227

Get-Command Get-Date -All | Format-Table -Property CommandType, Name,


ModuleName -AutoSize

CommandType Name ModuleName

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

Function Get-Date TestModule

Cmdlet Get-Date Microsoft.PowerShell.Utility

Microsoft.PowerShell.Utility\Get-Date

Thursday, August 15, 2019 2:28:31 PM

The first Get-Date cmdlet returns a DateTime object with the current date. After
importing the
TestModule module, Get-Date returns the year and day of the year.

Using the All parameter of Get-Command show all the Get-Date commands in the session.
The
results show that there are two Get-Date commands in the session, a function from
the
TestModule module and a cmdlet from the Microsoft.PowerShell.Utility module.

Because functions take precedence over cmdlets, the Get-Date function from the
TestModule
module runs, instead of the Get-Date cmdlet. To run the original version of
Get-Date , you must
qualify the command name with the module name.

For more information about command precedence in PowerShell, see


about_Command_Precedence.

Example 10: Import a minimum version of a module


This example imports the PowerShellGet module. It uses the MinimumVersion
parameter of
Import-Module to import only version 2.0.0 or greater of the module.

PowerShell

Import-Module -Name PowerShellGet -MinimumVersion 2.0.0


You can also use the RequiredVersion parameter to import a particular version of a
module, or
use the Module and Version parameters of the #Requires keyword to
require a particular
version of a module in a script.

Example 11: Import using a fully qualified name


This example imports a specific version of a module using the FullyQualifiedName.

PowerShell

PS> Get-Module -ListAvailable PowerShellGet | Select-Object Name, Version

Name Version

---- -------

PowerShellGet 2.2.1

PowerShellGet 2.1.3

PowerShellGet 2.1.2

PowerShellGet 1.0.0.1

PS> Import-Module -FullyQualifiedName @{ModuleName = 'PowerShellGet';


ModuleVersion = '2.1.3' }

Example 12: Import using a fully qualified path


This example imports a specific version of a module using the fully qualified path.

PowerShell

PS> Get-Module -ListAvailable PowerShellGet | Select-Object Path

Path

----

C:\Program Files\PowerShell\Modules\PowerShellGet\2.2.1\PowerShellGet.psd1

C:\program files\powershell\6\Modules\PowerShellGet\PowerShellGet.psd1

C:\Program
Files\WindowsPowerShell\Modules\PowerShellGet\2.1.2\PowerShellGet.psd1

C:\Program
Files\WindowsPowerShell\Modules\PowerShellGet\1.0.0.1\PowerShellGet.psd1

PS> Import-Module -Name 'C:\Program


Files\PowerShell\Modules\PowerShellGet\2.2.1\PowerShellGet.psd1'

Example 13: Import a module from a remote computer


This example shows how to use the Import-Module cmdlet to import a module from a
remote computer.
This command uses the Implicit Remoting feature of PowerShell.

When you import modules from another session, you can use the cmdlets in the current
session.
However, commands that use the cmdlets run in the remote session.

PowerShell

$s = New-PSSession -ComputerName Server01

Get-Module -PSSession $s -ListAvailable -Name NetSecurity

ModuleType Name ExportedCommands

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

Manifest NetSecurity {New-NetIPsecAuthProposal, New-


NetIPsecMainModeCryptoProposal, New-Ne...

Import-Module -PSSession $s -Name NetSecurity

Get-Command -Module NetSecurity -Name Get-*Firewall*

CommandType Name
ModuleName

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


-

Function Get-NetFirewallAddressFilter
NetSecurity

Function Get-NetFirewallApplicationFilter
NetSecurity

Function Get-NetFirewallInterfaceFilter
NetSecurity

Function Get-NetFirewallInterfaceTypeFilter
NetSecurity

Function Get-NetFirewallPortFilter
NetSecurity

Function Get-NetFirewallProfile
NetSecurity

Function Get-NetFirewallRule
NetSecurity

Function Get-NetFirewallSecurityFilter
NetSecurity

Function Get-NetFirewallServiceFilter
NetSecurity

Function Get-NetFirewallSetting
NetSecurity

Get-NetFirewallRule -DisplayName "Windows Remote Management*" |

Format-Table -Property DisplayName, Name -AutoSize

DisplayName Name

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

Windows Remote Management (HTTP-In) WINRM-HTTP-In-TCP

Windows Remote Management (HTTP-In) WINRM-HTTP-In-TCP-


PUBLIC

Windows Remote Management - Compatibility Mode (HTTP-In) WINRM-HTTP-Compat-


In-TCP

New-PSSession creates a remote session (PSSession) to the Server01 computer. The

PSSession
is saved in the $s variable.

Running Get-Module with the PSSession parameter shows that the NetSecurity module
is
installed and available on the remote computer. This command is equivalent to using
the
Invoke-Command cmdlet to run Get-Module command in the remote session. For
example:
( Invoke-Command $s {Get-Module -ListAvailable -Name NetSecurity

Running Import-Module with the PSSession parameter imports the NetSecurity module
from the
remote computer into the current session. The Get-Command cmdlet is used to
get commands that
begin with Get and include Firewall from the NetSecurity module.
The output confirms
that the module and its cmdlets were imported into the current
session.

Next, the Get-NetFirewallRule cmdlet gets Windows Remote Management firewall rules
on the Server01
computer. This is equivalent to using the Invoke-Command cmdlet to run
Get-NetFirewallRule
on the remote session.

Example 14: Manage storage on a remote computer


without the Windows operating system
In this example, the administrator of the computer has installed the Module Discovery
WMI
provider, which allows you to use CIM commands that are designed for the
provider.

The New-CimSession cmdlet creates a session on the remote computer named RSDGF03.
The session
connects to the WMI service on the remote computer. The CIM session is
saved in the $cs variable.
Import-Module uses the CimSession in $cs to import the
Storage CIM module from the
RSDGF03 computer.

The Get-Command cmdlet shows the Get-Disk command in the Storage module. When
you import a
CIM module into the local session, PowerShell converts the CDXML files for
each command into
PowerShell scripts, which appear as functions in the local session.

Although Get-Disk is typed in the local session, the cmdlet implicitly runs on the remote
computer
from which it was imported. The command returns objects from the remote
computer to the local
session.

PowerShell
$cs = New-CimSession -ComputerName RSDGF03

Import-Module -CimSession $cs -Name Storage

# Importing a CIM module, converts the CDXML files for each command into
PowerShell scripts.

# These appear as functions in the local session.

Get-Command Get-Disk

CommandType Name ModuleName

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

Function Get-Disk Storage

# Use implicit remoting to query disks on the remote computer from which the
module was imported.

Get-Disk

Number Friendly Name OperationalStatus Total Size Partition Style

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

0 Virtual HD ATA Device Online 40 GB MBR

Parameters
-Alias

Specifies the aliases that this cmdlet imports 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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-ArgumentList

Specifies an array of arguments, or parameter values, that are passed to a script


module during the
Import-Module command. This parameter is valid only when
you're importing a script module.

You can also refer to the ArgumentList parameter by its alias, args. For more
information
about the behavior of ArgumentList, see about_Splatting.
Type: Object[]

Aliases: Args

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-AsCustomObject

Indicates that this cmdlet 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.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Assembly

Specifies an array of assembly objects. This cmdlet 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 aren't
imported, and you might be missing
important members of the module. Use this
parameter for debugging and testing the module, or when
you're instructed to use it
by the module author.

Type: Assembly[]
Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-CimNamespace

Specifies the namespace of an alternate CIM provider that exposes CIM modules.
The default value is
the namespace of the Module Discovery WMI provider.

Use this parameter to import CIM modules from computers and devices that aren't
running a Windows
operating system.

This parameter was introduced in Windows PowerShell 3.0.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-CimResourceUri

Specifies an alternate location for CIM modules. The default value is the resource URI
of the Module
Discovery WMI provider on the remote computer.

Use this parameter to import CIM modules from computers and devices that aren't
running a Windows
operating system.

This parameter was introduced in Windows PowerShell 3.0.

Type: Uri

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-CimSession

Specifies a CIM session on the remote computer. Enter a variable that contains the
CIM session or a
command that gets the CIM session, such as a Get-CimSession
command.

Import-Module uses the CIM session connection to import modules from the remote
computer into the
current session. When you use the commands from the imported
module in the current session, the
commands run on the remote computer.

You can use this parameter to import modules from computers and devices that
aren't running the
Windows operating system, and Windows computers that have
PowerShell, but don't have PowerShell
remoting enabled.

This parameter was introduced in Windows PowerShell 3.0.

Type: CimSession

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Cmdlet

Specifies an array of cmdlets that this cmdlet imports from the module into the
current session.
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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-DisableNameChecking
Indicates that this cmdlet suppresses the message that warns you when you import a
cmdlet or
function whose name includes an unapproved verb or a prohibited
character.

By default, when a module that you import exports cmdlets or functions that have
unapproved verbs in
their names, PowerShell displays the following warning
message:

WARNING: Some imported command names include unapproved verbs which


might make them less
discoverable. Use the Verbose parameter for more detail
or type Get-Verb to see the list of
approved verbs.

This message is only a warning. The complete module is still imported, including the
non-conforming
commands. Although the message is displayed to module users,
the naming problem should be fixed by
the module author.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Force

This parameter causes a module to be loaded, or reloaded, over top of the current
one.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-FullyQualifiedName

The value can be a module name, a full module specification, or a path to a module
file.
When the value is a path, the path can be fully qualified or relative. A relative path is
resolved
relative to the script that contains the using statement.

When the value is a name or module specification, PowerShell searches the


PSModulePath for the
specified module.

A module specification is a hashtable that has the following keys.

ModuleName - Required Specifies the module name.

GUID - Optional Specifies the GUID of the module.


It's also Required to specify at least one of the three below keys.
ModuleVersion - Specifies a minimum acceptable version of the module.
MaximumVersion - Specifies the maximum acceptable version of the module.

RequiredVersion - Specifies an exact, required version of the module. This

can't be used with


the other Version keys.

Type: ModuleSpecification[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Function

Specifies an array of functions that this cmdlet imports from the module into the
current session.
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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Global
Indicates that this cmdlet imports modules into the global session state so they are
available to
all commands in the session.

By default, when Import-Module cmdlet is called from the command prompt, script
file, or
scriptblock, all the commands are imported into the global session state.

When invoked from another module, Import-Module cmdlet imports the commands
in a module, including
commands from nested modules, into the calling module's
session state.

 Tip

You should avoid calling Import-Module from within a module. Instead, declare
the target module
as a nested module in the parent module's manifest.
Declaring nested modules improves the
discoverability of dependencies.

The Global parameter is equivalent to the Scope parameter with a value of Global.

To restrict the commands that a module exports, use an Export-ModuleMember


command in the script
module.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-MaximumVersion

Specifies a maximum version. This cmdlet imports only a version of the module that
is less than or
equal to the specified value. If no version qualifies, Import-Module
returns an error.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-MinimumVersion

Specifies a minimum version. This cmdlet imports only a version of the module that
is greater than
or equal to the specified value. Use the MinimumVersion parameter
name or its alias,
Version. If no version qualifies, Import-Module generates an error.

To specify an exact version, use the RequiredVersion parameter. You can also use the
Module
and Version parameters of the #Requires keyword to require a specific
version of a module in
a script.

This parameter was introduced in Windows PowerShell 3.0.

Type: Version

Aliases: Version

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ModuleInfo

Specifies an array of module objects to import. Enter a variable that contains the
module objects,
or a command that gets the module objects, such as the following
command:
Get-Module -ListAvailable . You can also pipe module objects to Import-
Module .

Type: PSModuleInfo[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

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. Wildcard
characters aren't permitted. You can also pipe module names
and filenames to Import-Module .

If you omit a path, Import-Module looks for the module in the paths saved in the
$env:PSModulePath environment variable.

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 aren't
imported, and you might be missing important
members of the module.

7 Note

While it is possible to import a script ( .ps1 ) file as a module, script files are
usually not
structured like script modules file ( .psm1 ) file. Importing a script file
does not guarantee
that it is usable as a module. For more information, see
about_Modules.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-NoClobber

Prevents importing commands that have the same names as existing commands in
the current session. By
default, Import-Module imports all exported module
commands.

Commands that have the same names can hide or replace commands in the session.
To avoid command name
conflicts in a session, use the Prefix or NoClobber
parameters. For more information about
name conflicts and command precedence,
see "Modules and Name Conflicts" in
about_Modules and
about_Command_Precedence.

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter
Aliases: NoOverwrite

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-PassThru

Returns an object representing the item with which you're working. By default, this
cmdlet does not
generate any output.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Prefix

Specifies a prefix that this cmdlet adds 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. These are known
as nested modules. This cmdlet 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.

The value of this parameter takes precedence over the DefaultCommandPrefix


property of the
module, which specifies the default prefix.

Type: String

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-PSSession

Specifies a PowerShell user-managed session (PSSession) from which this cmdlet


imports modules
into the current session. Enter a variable that contains a PSSession
or a command that gets a
PSSession, such as a Get-PSSession command.

When you import a module from a different session into the current session, you can
use the cmdlets
from the module in the current session, just as you would use
cmdlets from a local module. Commands
that use the remote cmdlets run in the
remote session, but the remoting details are managed
in the background by
PowerShell.

This parameter uses the Implicit Remoting feature of PowerShell. It is equivalent to


using the
Import-PSSession cmdlet to import particular modules from a session.

Import-Module cannot import core PowerShell modules from another session. The
core PowerShell
modules have names that begin with Microsoft.PowerShell.

This parameter was introduced in Windows PowerShell 3.0.

Type: PSSession

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RequiredVersion

Specifies a version of the module that this cmdlet imports. If the version is not
installed,
Import-Module generates an error.

By default, Import-Module imports the module without checking the version number.

To specify a minimum version, use the MinimumVersion parameter. You can also use
the Module
and Version parameters of the #Requires keyword to require a specific
version of a module in
a script.
This parameter was introduced in Windows PowerShell 3.0.

Scripts that use RequiredVersion to import modules that are included with existing
releases of
the Windows operating system don't automatically run in future releases
of the Windows operating
system. This is because PowerShell module version
numbers in future releases of the Windows
operating system are higher than module
version numbers in existing releases of the Windows
operating system.

Type: Version

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Scope

Specifies a scope into which this cmdlet imports the module.

The acceptable values for this parameter are:

Global. Available to all commands in the session. Equivalent to the Global


parameter.
Local. Available only in the current scope.

By default, when Import-Module cmdlet is called from the command prompt, script
file, or
scriptblock, all the commands are imported into the global session state. You
can use the
-Scope Local parameter to import module content into the script or
scriptblock scope.

When invoked from another module, Import-Module cmdlet imports the commands
in a module, including
commands from nested modules, into the caller's session
state. Specifying -Scope Global or
-Global indicates that this cmdlet imports
modules into the global session state so they are
available to all commands in the
session.

The Global parameter is equivalent to the Scope parameter with a value of Global.

This parameter was introduced in Windows PowerShell 3.0.

Type: String

Accepted values: Local, Global


Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Variable

Specifies an array of variables that this cmdlet imports 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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

Inputs
String

You can pipe a module name to this cmdlet.

PSModuleInfo

You can pipe a module object to this cmdlet.

Assembly

You can pipe an assembly object to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.


PSModuleInfo

If you specify the PassThru parameter, the cmdlet generates a


System.Management.Automation.PSModuleInfo object that represents the module.

PSCustomObject

If you specify the AsCustomObject and PassThru parameters together, the cmdlet
generates a
PSCustomObject object that represents the module.

Notes
Windows PowerShell includes the following aliases for Import-Module :

ipmo

Before you can import a module, the module must be installed on the local
computer. That is, the
module directory must be copied to a directory that is
accessible to your local computer. For more
information, see about_Modules.

You can also use the PSSession and CIMSession parameters to import modules
that are
installed on remote computers. However, commands that use the cmdlets
in these modules run in the
remote session on the remote computer.

If you import members with the same name and the same type into your session,
PowerShell uses the
member imported last by default. Variables and aliases are
replaced, and the originals aren't
accessible. Functions, cmdlets, and providers are
merely shadowed by the new members. 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 don't
need
to import the module again.

Starting in Windows PowerShell 3.0, the core commands that are installed with
PowerShell are
packaged in modules. In Windows PowerShell 2.0, and in host
programs that create older-style
sessions in later versions of PowerShell, the core
commands are packaged in snap-ins
(PSSnapins). The exception is
Microsoft.PowerShell.Core, which is always a snap-in. Also,
remote sessions, such
as those started by the New-PSSession cmdlet, are older-style sessions
that include
core snap-ins.

For information about the CreateDefault2 method that creates newer-style


sessions with core
modules, see the CreateDefault2 Method.

In Windows PowerShell 2.0, some of the property values of the module object,
such as the
ExportedCmdlets and NestedModules property values, were not
populated until the module was
imported.

If you attempt to import a module that contains mixed-mode assemblies that


aren't compatible with
Windows PowerShell 3.0+, Import-Module returns an error
message like the following one.

Import-Module : Mixed mode assembly is built against version 'v2.0.50727' of


the runtime and
cannot be loaded in the 4.0 runtime without additional
configuration information.

This error occurs when a module that is designed for Windows PowerShell 2.0
contains at least one
mixed-module assembly. A mixed-module assembly that
includes both managed and non-managed code,
such as C++ and C#.

To import a module that contains mixed-mode assemblies, start Windows


PowerShell 2.0 by using the
following command, and then try the Import-Module
command again.

PowerShell.exe -Version 2.0

To use the CIM session feature, the remote computer must have WS-Management
remoting and Windows
Management Instrumentation (WMI), which is the
Microsoft implementation of the Common Information
Model (CIM) standard. The
computer must also have the Module Discovery WMI provider or an
alternate CIM
provider that has the same basic features.

You can use the CIM session feature on computers that aren't running a Windows
operating system
and on Windows computers that have PowerShell, but don't
have PowerShell remoting enabled.

You can also use the CIM parameters to get CIM modules from computers that
have PowerShell
remoting enabled, including the local computer. When you create
a CIM session on the local
computer, PowerShell uses DCOM, instead of WMI, to
create the session.
By default, Import-Module imports modules in the global scope even when called
from a
descendant scope. The top-level scope and all descendant scopes have
access to the module's
exported elements.

In a descendant scope, -Scope Local limits the import to that scope and all its
descendant
scopes. Parent scopes then do not see the imported members.

7 Note

Get-Module shows all modules loaded in the current session. This includes
modules loaded
locally in a descendant scope. Use Get-Command -Module
modulename to see which members are
loaded in the current scope.

Import-Module does not load class and enum definitions in the module. Use the

using module
statement at the beginning of your script. This imports the module,

including the class and enum


definitions. For more information, see about_Using.

Related Links
about_Modules
Export-ModuleMember
Get-Module
New-Module
Remove-Module
Invoke-Command
Reference
Module: Microsoft.PowerShell.Core

Runs commands on local and remote computers.

Syntax
PowerShell

Invoke-Command

[-ScriptBlock] <ScriptBlock>

[-NoNewScope]

[-InputObject <PSObject>]

[-ArgumentList <Object[]>]

[<CommonParameters>]

PowerShell

Invoke-Command

[[-Session] <PSSession[]>]

[-ThrottleLimit <Int32>]

[-AsJob]

[-HideComputerName]

[-JobName <String>]

[-ScriptBlock] <ScriptBlock>

[-InputObject <PSObject>]

[-ArgumentList <Object[]>]

[<CommonParameters>]

PowerShell

Invoke-Command

[[-Session] <PSSession[]>]

[-ThrottleLimit <Int32>]

[-AsJob]

[-HideComputerName]

[-JobName <String>]

[-FilePath] <String>

[-InputObject <PSObject>]

[-ArgumentList <Object[]>]

[<CommonParameters>]

PowerShell
Invoke-Command

[[-ComputerName] <String[]>]

[-Credential <PSCredential>]

[-Port <Int32>]

[-UseSSL]

[-ConfigurationName <String>]

[-ApplicationName <String>]
[-ThrottleLimit <Int32>]

[-AsJob]

[-InDisconnectedSession]

[-SessionName <String[]>]

[-HideComputerName]

[-JobName <String>]

[-FilePath] <String>

[-SessionOption <PSSessionOption>]

[-Authentication <AuthenticationMechanism>]

[-EnableNetworkAccess]

[-InputObject <PSObject>]

[-ArgumentList <Object[]>]

[<CommonParameters>]

PowerShell

Invoke-Command

[[-ComputerName] <String[]>]

[-Credential <PSCredential>]

[-Port <Int32>]

[-UseSSL]

[-ConfigurationName <String>]

[-ApplicationName <String>]
[-ThrottleLimit <Int32>]

[-AsJob]

[-InDisconnectedSession]

[-SessionName <String[]>]

[-HideComputerName]

[-JobName <String>]

[-ScriptBlock] <ScriptBlock>

[-SessionOption <PSSessionOption>]

[-Authentication <AuthenticationMechanism>]

[-EnableNetworkAccess]

[-InputObject <PSObject>]

[-ArgumentList <Object[]>]

[-CertificateThumbprint <String>]

[<CommonParameters>]

PowerShell

Invoke-Command

[-Credential <PSCredential>]

[-ConfigurationName <String>]

[-ThrottleLimit <Int32>]

[[-ConnectionUri] <Uri[]>]

[-AsJob]

[-InDisconnectedSession]

[-HideComputerName]

[-JobName <String>]

[-ScriptBlock] <ScriptBlock>

[-AllowRedirection]

[-SessionOption <PSSessionOption>]

[-Authentication <AuthenticationMechanism>]

[-EnableNetworkAccess]

[-InputObject <PSObject>]

[-ArgumentList <Object[]>]

[-CertificateThumbprint <String>]

[<CommonParameters>]

PowerShell

Invoke-Command

[-Credential <PSCredential>]

[-ConfigurationName <String>]

[-ThrottleLimit <Int32>]

[[-ConnectionUri] <Uri[]>]

[-AsJob]

[-InDisconnectedSession]

[-HideComputerName]

[-JobName <String>]

[-FilePath] <String>

[-AllowRedirection]

[-SessionOption <PSSessionOption>]

[-Authentication <AuthenticationMechanism>]

[-EnableNetworkAccess]

[-InputObject <PSObject>]

[-ArgumentList <Object[]>]

[<CommonParameters>]

PowerShell

Invoke-Command

-Credential <PSCredential>

[-ConfigurationName <String>]

[-ThrottleLimit <Int32>]

[-AsJob]

[-HideComputerName]

[-ScriptBlock] <ScriptBlock>

[-InputObject <PSObject>]

[-ArgumentList <Object[]>]

[-VMId] <Guid[]>

[<CommonParameters>]

PowerShell
Invoke-Command

-Credential <PSCredential>

[-ConfigurationName <String>]

[-ThrottleLimit <Int32>]

[-AsJob]

[-HideComputerName]

[-ScriptBlock] <ScriptBlock>

[-InputObject <PSObject>]

[-ArgumentList <Object[]>]

-VMName <String[]>

[<CommonParameters>]

PowerShell

Invoke-Command

-Credential <PSCredential>

[-ConfigurationName <String>]

[-ThrottleLimit <Int32>]

[-AsJob]

[-HideComputerName]

[-FilePath] <String>

[-InputObject <PSObject>]

[-ArgumentList <Object[]>]

[-VMId] <Guid[]>

[<CommonParameters>]

PowerShell

Invoke-Command

-Credential <PSCredential>

[-ConfigurationName <String>]

[-ThrottleLimit <Int32>]

[-AsJob]

[-HideComputerName]

[-FilePath] <String>

[-InputObject <PSObject>]

[-ArgumentList <Object[]>]

-VMName <String[]>

[<CommonParameters>]

PowerShell

Invoke-Command

[-ConfigurationName <String>]

[-ThrottleLimit <Int32>]

[-AsJob]

[-HideComputerName]

[-JobName <String>]

[-ScriptBlock] <ScriptBlock>

[-RunAsAdministrator]

[-InputObject <PSObject>]

[-ArgumentList <Object[]>]

-ContainerId <String[]>

[<CommonParameters>]

PowerShell

Invoke-Command

[-ConfigurationName <String>]

[-ThrottleLimit <Int32>]

[-AsJob]

[-HideComputerName]

[-JobName <String>]

[-FilePath] <String>

[-RunAsAdministrator]

[-InputObject <PSObject>]

[-ArgumentList <Object[]>]

-ContainerId <String[]>

[<CommonParameters>]

Description
The Invoke-Command cmdlet runs commands on a local or remote computer and returns
all output from
the commands, including errors. Using 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, use the New-PSSession cmdlet to
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. To run a
command in a disconnected
session, use the InDisconnectedSession parameter. To run
a command in a background job, use the
AsJob parameter.

You can also use Invoke-Command on a local computer to a run script block as a
command. PowerShell
runs the script block immediately in a child scope of the current
scope.

Before using Invoke-Command to run commands on a remote computer, read


about_Remote.

Some code samples use splatting to reduce the line length. For more information, see
about_Splatting.

Examples
Example 1: Run a script on a server
This example runs the Test.ps1 script on the Server01 computer.

PowerShell

Invoke-Command -FilePath c:\scripts\test.ps1 -ComputerName Server01

The FilePath parameter specifies 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: Run a command on a remote server


This example runs a Get-Culture command on the Server01 remote computer.

PowerShell

Invoke-Command -ComputerName Server01 -Credential Domain01\User01 -


ScriptBlock {

Get-Culture

The ComputerName parameter specifies the name of the remote computer. The
Credential
parameter is used to run the command in the security context of
Domain01\User01, a user who has
permission to run commands. The ScriptBlock
parameter specifies the command to be run on the
remote computer.

In response, PowerShell 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: Run a command in a persistent connection


This example runs the same Get-Culture command in a session, using a persistent
connection, on the
remote computer named Server02.

PowerShell

$s = New-PSSession -ComputerName Server02 -Credential Domain01\User01

Invoke-Command -Session $s -ScriptBlock { Get-Culture }

The New-PSSession cmdlet creates a session on the Server02 remote computer and
saves it in the
$s variable. Typically, you create a session only when you run a series of
commands on the remote
computer.

The Invoke-Command cmdlet runs the Get-Culture command on Server02. The Session
parameter
specifies the session saved in the $s variable.

In response, PowerShell runs the command in the session on the Server02 computer.

Example 4: Use a session to run a series of commands


that share data
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.

PowerShell

Invoke-Command -ComputerName Server02 -ScriptBlock { $p = Get-Process


PowerShell }

Invoke-Command -ComputerName Server02 -ScriptBlock { $p.VirtualMemorySize }

$s = New-PSSession -ComputerName Server02

Invoke-Command -Session $s -ScriptBlock { $p = Get-Process PowerShell }

Invoke-Command -Session $s -ScriptBlock { $p.VirtualMemorySize }

17930240

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

When you use the ComputerName parameter, PowerShell creates a new session to run
the command.
The session is closed when the command completes. The $p variable was
created in one connection,
but it doesn't exist in the connection created for the second
command.

The problem is solved by creating a persistent session on the remote computer, then
running both of
the commands in the same session.

The New-PSSession cmdlet creates a persistent session on the computer Server02 and
saves the
session in the $s variable. The Invoke-Command lines that follow use the
Session parameter
to run both of the commands in the same session. Since both
commands run in the same session, the
$p value remains active.
Example 5: Invoke a command with a script block stored
in a variable
This example shows how to run a command that is stored as a script block in a variable.
When the
script block is saved in a variable, you can specify the variable as the value of
the
ScriptBlock parameter.

PowerShell

$command = {

Get-EventLog -LogName 'Windows PowerShell' |

Where-Object { $_.Message -like '*certificate*' }

Invoke-Command -ComputerName S1, S2 -ScriptBlock $command

The $command variable stores the Get-EventLog command that's formatted as a script
block. The
Invoke-Command runs the command stored in $command on the S1 and S2
remote computers.

Example 6: Run a single command on several computers


This example demonstrates how to use Invoke-Command to run a single command on
multiple computers.

PowerShell

$parameters = @{

ComputerName = 'Server01', 'Server02', 'TST-0143', 'localhost'

ConfigurationName = 'MySession.PowerShell'

ScriptBlock = { Get-EventLog 'Windows PowerShell' }

Invoke-Command @parameters

The ComputerName parameter specifies a comma-separated list of computer names.


The list of
computers includes the localhost value, which represents the local computer.
The
ConfigurationName parameter specifies an alternate session configuration. The
ScriptBlock
parameter runs Get-EventLog to get the Windows PowerShell event logs
from each computer.

Example 7: Get the version of the host program on


multiple computers
This example gets the version of the PowerShell host program running on 200 remote
computers.

PowerShell

$version = Invoke-Command -ComputerName (Get-Content Machines.txt) -


ScriptBlock {

(Get-Host).Version

Because only one command is run, you don't have to create persistent connections to
each of the
computers. Instead, the command uses the ComputerName parameter to
indicate the computers. To
specify the computers, it uses the Get-Content cmdlet to get
the contents of the Machine.txt file,
a file of computer names.

The Invoke-Command cmdlet runs a Get-Host command on the remote computers. It uses
dot notation
to get the Version property of the PowerShell host.

These commands run 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: Run a background job on several remote


computers
This example runs a command on two remote computers. The Invoke-Command
command uses the AsJob
parameter so that the command runs as a background job.
The commands run on the remote computers,
but the job exists on the local computer.
The results are transmitted to the local computer.

PowerShell

$s = New-PSSession -ComputerName Server01, Server02

Invoke-Command -Session $s -ScriptBlock { Get-EventLog system } -AsJob

Id Name State HasMoreData Location Command

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

1 Job1 Running True Server01,Server02 Get-EventLog system

$j = Get-Job

$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 :

$results = $j | Receive-Job

The New-PSSession cmdlet creates sessions on the Server01 and Server02 remote
computers. The
Invoke-Command cmdlet runs 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 Get-Job command saves the job object in the $j variable. The $j variable is then
piped to
the Format-List cmdlet to display all properties of the job object in a list. The
last 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: Include local variables in a command run on a


remote computer
This example shows how to include the values of local variables in a command run on a
remote
computer. The command uses the Using scope modifier to identify a local
variable in a remote
command. By default, all variables are assumed to be defined in the
remote session. The Using
scope modifier was introduced in PowerShell 3.0. For more
information about the Using scope
modifier, see about_Remote_Variables and
about_Scopes.

PowerShell

$Log = 'Windows PowerShell'

Invoke-Command -ComputerName Server01 -ScriptBlock {

Get-EventLog -LogName $Using:Log -Newest 10

}
The $Log variable stores the name of the event log, Windows PowerShell. The Invoke-
Command
cmdlet runs Get-EventLog on Server01 to get the ten newest events from the
event log. The value of
the LogName parameter is the $Log variable, which is prefixed
by the Using scope modifier to
indicate that it was created in the local session, not in
the remote session.

Example 10: Hide the computer name


This example shows the effect of using the HideComputerName parameter of Invoke-
Command .
HideComputerName doesn't change the object that this cmdlet returns. It

changes only the


display. You can still use the Format cmdlets to display the
PsComputerName property of any
of the affected objects.

PowerShell

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

Invoke-Command -ComputerName S1, S2 -HideComputerName -ScriptBlock {

Get-Process PowerShell

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

The first two commands use Invoke-Command 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
HideComputerName, doesn't include the
PsComputerName column.

Example 11: Use the Param keyword in a script block


The Param keyword and the ArgumentList parameter are used to pass variable values to
named
parameters in a script block. This example displays filenames that begin with the
letter a and
have the .pdf extension.

For more information about the Param keyword, see


about_Language_Keywords.

PowerShell

$parameters = @{

ComputerName = 'Server01'

ScriptBlock = {

Param ($param1, $param2)

Get-ChildItem -Name $param1 -Include $param2

ArgumentList = 'a*', '*.pdf'

Invoke-Command @parameters

aa.pdf

ab.pdf

ac.pdf

az.pdf

Invoke-Command uses the ScriptBlock parameter that defines two variables, $param1 and

$param2 . Get-ChildItem uses the named parameters, Name and Include with the
variable
names. The ArgumentList passes the values to the variables.

Example 12: Use the $args automatic variable in a script


block
The $args automatic variable and the ArgumentList parameter are used to pass array
values to
parameter positions in a script block. This example displays a server's directory
contents of .txt
files. The Get-ChildItem Path parameter is position 0 and the Filter
parameter is position
1.

For more information about the $args variable, see


about_Automatic_Variables

PowerShell

$parameters = @{

ComputerName = 'Server01'

ScriptBlock = { Get-ChildItem $args[0] $args[1] }

ArgumentList = 'C:\Test', '*.txt*'

Invoke-Command @parameters

Directory: C:\Test

Mode LastWriteTime Length Name

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

-a--- 6/12/2019 15:15 128 alog.txt

-a--- 7/27/2019 15:16 256 blog.txt

-a--- 9/28/2019 17:10 64 zlog.txt

Invoke-Command uses a ScriptBlock parameter and Get-ChildItem specifies the $args[0]

and
$args[1] array values. The ArgumentList passes the $args array values to the Get-
ChildItem
parameter positions for Path and Filter.

Example 13: Run a script on all the computers listed in a


text file
This example uses the Invoke-Command cmdlet to run the Sample.ps1 script on all the
computers
listed in the Servers.txt file. The command uses the FilePath parameter to
specify the script
file. This command lets you run the script on the remote computers,
even if the script file isn't
accessible to the remote computers.

PowerShell

$parameters = @{

ComputerName = (Get-Content Servers.txt)

FilePath = 'C:\Scripts\Sample.ps1'

ArgumentList = 'Process', 'Service'

Invoke-Command @parameters

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 14: Run a command on a remote computer using


a URI
This example shows how to run a command on a remote computer that's identified by a
Uniform Resource
Identifier (URI). This particular example runs a Set-Mailbox command
on a remote Exchange server.

PowerShell

$LiveCred = Get-Credential

$parameters = @{

ConfigurationName = 'Microsoft.Exchange'

ConnectionUri = 'https://ps.exchangelabs.com/PowerShell'

Credential = $LiveCred

Authentication = 'Basic'

ScriptBlock = { Set-Mailbox Dan -DisplayName 'Dan Park' }

Invoke-Command @parameters

The first line uses the Get-Credential cmdlet to store Windows Live ID credentials in the
$LiveCred variable. PowerShell prompts the user to enter Windows Live ID credentials.

The $parameters variable is a hash table containing the parameters to be passed to the
Invoke-Command cmdlet. The Invoke-Command cmdlet runs a Set-Mailbox command using
the
Microsoft.Exchange session configuration. The ConnectionURI parameter specifies
the URL of
the Exchange server endpoint. The Credential parameter specifies the
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 15: Use a session option


This example shows how to create and use a SessionOption parameter.

PowerShell

$so = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck

$parameters = @{

ComputerName = 'server01'

UseSSL = $true

ScriptBlock = { Get-HotFix }

SessionOption = $so

Credential = 'server01\user01'

Invoke-Command @parameters

The New-PSSessionOption cmdlet creates a session option object that causes the remote
end not to
verify the Certificate Authority, Canonical Name, and Revocation Lists while
evaluating the incoming
HTTPS connection. The SessionOption object is saved in the
$so variable.

7 Note

Disabling these checks is convenient for troubleshooting, but obviously not secure.

The Invoke-Command cmdlet runs a Get-HotFix command remotely. The SessionOption


parameter is
given the $so variable.
Example 16: Manage URI redirection in a remote
command
This example shows how to use the AllowRedirection and SessionOption parameters to
manage
URI redirection in a remote command.

PowerShell

$max = New-PSSessionOption -MaximumRedirection 1

$parameters = @{

ConnectionUri = 'https://ps.exchangelabs.com/PowerShell'

ScriptBlock = { Get-Mailbox dan }

AllowRedirection = $true

SessionOption = $max

Invoke-Command @parameters

The New-PSSessionOption cmdlet creates a PSSessionOption object that is saved in the


$max
variable. The command uses the MaximumRedirection parameter to set the

MaximumConnectionRedirectionCount property of the PSSessionOption object to 1.

The Invoke-Command cmdlet runs a Get-Mailbox command on a remote Microsoft


Exchange Server. The
AllowRedirection parameter provides explicit permission to
redirect the connection to an
alternate endpoint. The SessionOption parameter uses the
session object stored in the $max
variable.

As a result, if the remote computer specified by ConnectionURI returns a redirection


message,
PowerShell redirects 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 17: Access a network share in a remote session


This example shows how to access a network share from a remote session. Three
computers are used to
demonstrate the example. Server01 is the local computer,
Server02 is the remote computer, and Net03
contains the network share. Server01
connects to Server02, and then Server02 does a second hop to
Net03 to access the
network share. For more information about how PowerShell Remoting supports hops
between computers, see
Making the second hop in PowerShell Remoting.

The required Credential Security Support Provider (CredSSP) delegation is 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.

PowerShell

Enable-WSManCredSSP -Role Client -DelegateComputer Server02

$s = New-PSSession Server02

Invoke-Command -Session $s -ScriptBlock { Enable-WSManCredSSP -Role Server -


Force }

$parameters = @{

Session = $s

ScriptBlock = { Get-Item \\Net03\Scripts\LogFiles.ps1 }

Authentication = 'CredSSP'

Credential = 'Domain01\Admin01'

Invoke-Command @parameters

The Enable-WSManCredSSP cmdlet enables CredSSP delegation from the Server01 local
computer to the
Server02 remote computer. The Role parameter specifies Client to
configure the CredSSP
client setting on the local computer.

New-PSSession creates a PSSession object for Server02 and stores the object in the $s
variable.

The Invoke-Command cmdlet uses the $s variable to connect to the remote computer,
Server02. The
ScriptBlock parameter runs Enable-WSManCredSSP on the remote
computer. The Role parameter
specifies Server to configure the CredSSP server setting
on the remote computer.

The $parameters variable contains the parameter values to connect to the network
share. The
Invoke-Command cmdlet runs a Get-Item command in the session in $s . This
command gets a script
from the \\Net03\Scripts network share. The command uses the
Authentication parameter with a
value of CredSSP and the Credential parameter with a
value of Domain01\Admin01.

Example 18: Start scripts on many remote computers


This example runs a script on more than a hundred computers. To minimize the impact
on the local
computer, it connects to each computer, starts the script, and then
disconnects from each computer.
The script continues to run in the disconnected
sessions.

PowerShell
$parameters = @{

ComputerName = (Get-Content -Path C:\Test\Servers.txt)

InDisconnectedSession = $true

FilePath = '\\Scripts\Public\ConfigInventory.ps1'

SessionOption = @{

OutputBufferingMode = 'Drop'

IdleTimeout = [timespan]::FromHours(12)

Invoke-Command @parameters

The command uses Invoke-Command to run the script. The value of the ComputerName
parameter is
a Get-Content command that gets the names of the remote computers
from a text file. The
InDisconnectedSession parameter disconnects the sessions as soon
as it starts the command. The
value of the FilePath parameter is the script that Invoke-
Command runs on each computer.

The value of SessionOption is a hash table. The OutputBufferingMode value is set to


Drop
and the IdleTimeout value is set to 12 hours.

To get the results of commands and scripts that run in disconnected sessions, use the
Receive-PSSession cmdlet.

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, PowerShell doesn't redirect
connections, but you can use
this parameter to allow it to redirect the connection.

You can also limit the number of times the connection is redirected by changing the
MaximumConnectionRedirectionCount session option value. Use the
MaximumRedirection parameter
of the New-PSSessionOption cmdlet or set the
MaximumConnectionRedirectionCount property of the
$PSSessionOption
preference variable. The default value is 5.

Type: SwitchParameter

Position: Named
Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-ApplicationName

Specifies the application name segment of the connection URI. Use this parameter to
specify the
application name when you aren't 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 isn't 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.

Type: String

Position: Named

Default value: $PSSessionApplicationName if set on the local computer,


otherwise WSMAN

Accept pipeline input: True

Accept wildcard characters: False

-ArgumentList

Supplies the values of parameters for the scriptblock. The parameters in the script
block are
passed by position from the array value supplied to ArgumentList. This is
known as array
splatting. For more information about the behavior of ArgumentList,
see
about_Splatting.

Type: Object[]

Aliases: Args

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-AsJob

Indicates that this cmdlet runs the command as a background job on a remote
computer. Use this
parameter to run commands that take an extensive time to finish.

When you use the AsJob parameter, 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 finishes. To
manage the job, use the *-Job cmdlets. To get the
job results, use the Receive-Job cmdlet.

The AsJob parameter resembles using the Invoke-Command cmdlet to run a Start-Job
cmdlet
remotely. However, with AsJob, the job is created on the local computer,
even though the job
runs on a remote computer. The results of the remote job are
automatically returned to the local
computer.

For more information about PowerShell background jobs, see about_Jobs and
about_Remote_Jobs.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Authentication

Specifies the mechanism that's used to authenticate the user's credentials. CredSSP
authentication
is available only in Windows Vista, Windows Server 2008, and later
versions of the Windows operating
system.

The acceptable values for this parameter are as follows:

Default
Basic
Credssp
Digest
Kerberos
Negotiate
NegotiateWithImplicitCredential

The default value is Default.

For more information about the values of this parameter, see


AuthenticationMechanism Enumeration.

U Caution

Credential Security Support 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.
For more
information, see
Credential Security Support Provider.

Type: AuthenticationMechanism

Accepted values: Default, Basic, Negotiate, NegotiateWithImplicitCredential,


Credssp, Digest, Kerberos

Position: Named

Default value: Default

Accept pipeline input: False

Accept wildcard characters: False

-CertificateThumbprint

Specifies the digital public key certificate (X509) of a user account that has
permission to connect
to the disconnected session. Enter the certificate thumbprint
of the certificate.

Certificates are used in client certificate-based authentication. They can be mapped


only to local
user accounts and they don't work with domain accounts.

To get a certificate thumbprint, use a Get-Item or Get-ChildItem command in the


PowerShell Cert:
drive.

Type: String
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ComputerName

Specifies the computers on which the command runs. The default is the local
computer.

When you use the ComputerName parameter, PowerShell creates a temporary


connection that's 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 ComputerName, the command must include the
Credential
parameter. The computer must be configured for the HTTPS transport or
the IP address of the remote
computer must be included in the local computer's
WinRM TrustedHosts list. For instructions to
add a computer name to the
TrustedHosts list, see How to Add a Computer to the Trusted Host
List.

On Windows Vista and later versions of the Windows operating system, to include
the local computer
in the value of ComputerName, you must run PowerShell using
the Run as administrator option.

Type: String[]

Aliases: Cn

Position: 0

Default value: Local computer

Accept pipeline input: False

Accept wildcard characters: False

-ConfigurationName

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 doesn't 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 isn't set, the default is
Microsoft.PowerShell. For more
information, see about_Preference_Variables.

Type: String

Position: Named

Default value: $PSSessionConfigurationName if set on the local computer,


otherwise Microsoft.PowerShell

Accept pipeline input: True

Accept wildcard characters: False

-ConnectionUri

Specifies a Uniform Resource Identifier (URI) that defines the connection endpoint of
the 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:5985/WSMAN

If you don't specify a connection URI, you can use the UseSSL and Port parameters
to specify
the connection URI values.

Valid values for the Transport segment of the URI are HTTP and HTTPS. If you specify
a
connection URI with a Transport segment, but don't specify a port, the session is
created with the
standards ports: 80 for HTTP and 443 for HTTPS. To use the default
ports for PowerShell remoting,
specify port 5985 for HTTP or 5986 for HTTPS.

If the destination computer redirects the connection to a different URI, PowerShell


prevents the
redirection unless you use the AllowRedirection parameter in the
command.

Type: Uri[]

Aliases: URI, CU

Position: 0

Default value: http://localhost:5985/WSMAN

Accept pipeline input: False

Accept wildcard characters: False

-ContainerId

Specifies an array of container IDs.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Credential

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
generated by the Get-Credential cmdlet. If you type a user name, you're
prompted to enter the
password.

Credentials are stored in a PSCredential


object and the password is stored as a
SecureString.

7 Note

For more information about SecureString data protection, see


How secure is
SecureString?.

Type: PSCredential
Position: Named

Default value: Current user

Accept pipeline input: True

Accept wildcard characters: False

-EnableNetworkAccess

Indicates that this cmdlet adds an interactive security token to loopback sessions.
The interactive
token lets you run commands in the loopback session that get data
from other computers. For example,
you can run a command in the session that
copies XML files from a remote computer to the local
computer.

A loopback session is a PSSession that originates and ends on the same computer.
To create a
loopback session, omit the ComputerName parameter or set its value to
dot ( . ), localhost, or
the name of the local computer.

By default, loopback sessions are created using a network token, which might not
provide sufficient
permission to authenticate to remote computers.

The EnableNetworkAccess parameter is effective only in loopback sessions. If you


use
EnableNetworkAccess when you create a session on a remote computer, the
command succeeds, but
the parameter is ignored.

You can allow remote access in a loopback session using the CredSSP value of the
Authentication parameter, which delegates the session credentials to other
computers.

To protect the computer from malicious access, disconnected loopback sessions that
have interactive
tokens, which are those created using EnableNetworkAccess, can be
reconnected only from the
computer on which the session was created.
Disconnected sessions that use CredSSP authentication can
be reconnected from
other computers. For more information, see Disconnect-PSSession .

This parameter was introduced in PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


-FilePath

Specifies a local script that this cmdlet runs on one or more remote computers. Enter
the path and
filename of the script, or pipe a script path to Invoke-Command . The
script must exist on the
local computer or in a directory that the local computer can
access. Use ArgumentList to specify
the values of parameters in the script.

When you use this parameter, 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.

Type: String

Aliases: PSPath

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-HideComputerName

Indicates that this cmdlet 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 doesn't change the object.

Type: SwitchParameter

Aliases: HCN

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InDisconnectedSession

Indicates that this cmdlet runs a command or script in a disconnected session.


When you use the InDisconnectedSession parameter, Invoke-Command creates a
persistent session
on each remote computer, starts the command specified by the
ScriptBlock or FilePath
parameter, and then disconnects from the session. The
commands continue to run in the disconnected
sessions. InDisconnectedSession
enables you to run commands without maintaining a connection to
the remote
sessions. And, because the session is disconnected before any results are returned,
InDisconnectedSession makes sure that all command results are returned to the
reconnected
session, instead of being split between sessions.

You can't use InDisconnectedSession with the Session parameter or the AsJob
parameter.

Commands that use InDisconnectedSession return a PSSession object that


represents the
disconnected session. They don't return the command output. To
connect to the disconnected session,
use the Connect-PSSession or Receive-
PSSession cmdlets. To get the results of commands that ran
in the session, use the
Receive-PSSession cmdlet. To run commands that generate output in a
disconnected

session, set the value of the OutputBufferingMode session option to Drop. If


you
intend to connect to the disconnected session, set the idle time-out in the session so
that it
provides sufficient time for you to connect before deleting the session.

You can set the output buffering mode and idle time-out in the SessionOption
parameter or in the
$PSSessionOption preference variable. For more information
about session options, see
New-PSSessionOption and about_Preference_Variables.

For more information about the Disconnected Sessions feature, see


about_Remote_Disconnected_Sessions.

This parameter was introduced in PowerShell 3.0.

Type: SwitchParameter

Aliases: Disconnected

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-InputObject
Specifies input to the command. Enter a variable that contains the objects or type a
command or
expression that gets the objects.

When using the InputObject parameter, use the $Input automatic variable in the
value of the
ScriptBlock parameter to represent the input objects.

Type: PSObject

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-JobName

Specifies a friendly name for the background job. By default, jobs are named Job<n> ,
where <n>
is an ordinal number.

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 don't include AsJob in the

command.

For more information about PowerShell background jobs, see about_Jobs.

Type: String

Position: Named

Default value: Job<n>

Accept pipeline input: False

Accept wildcard characters: False

-NoNewScope

Indicates that this cmdlet runs the specified command in the current scope. By
default,
Invoke-Command runs commands in their own scope.

This parameter is valid only in commands that are run in the current session, that is,
commands that
omit both the ComputerName and Session parameters.

This parameter was introduced in PowerShell 3.0.


Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Port

Specifies the network port on the remote computer that is used for this command.
To connect to a
remote computer, the remote computer must be listening on the
port that the connection uses. The
default ports are 5985 (WinRM port for HTTP) and
5986 (WinRM port for HTTPS).

Before using an alternate port, configure the WinRM listener on the remote
computer to listen at
that port. To configure the listener, type the following two
commands at the PowerShell prompt:

Remove-Item -Path WSMan:\Localhost\listener\listener* -Recurse

New-Item -Path WSMan:\Localhost\listener -Transport http -Address * -Port \

<port-number\>

Don't use the Port parameter unless you must. The port that is 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.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RunAsAdministrator

Indicates that this cmdlet invokes a command as an Administrator.

Type: SwitchParameter

Position: Named
Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-ScriptBlock

Specifies the commands to run. Enclose the commands in braces ( { } ) to create a


script block. When
using Invoke-Command to run a command remotely, any variables
in the command are evaluated on the
remote computer.

7 Note

Parameters for the scriptblock can only be passed in from ArgumentList by


position. Switch
parameters cannot be passed by position. If you need a
parameter that behaves like a
SwitchParameter type, use a Boolean type
instead.

Type: ScriptBlock

Aliases: Command

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Session

Specifies an array of sessions in which this cmdlet runs the command. Enter a
variable that contains
PSSession objects or a command that creates or gets the
PSSession objects, such as a
New-PSSession or Get-PSSession command.

When you create a PSSession, 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. For more information,
see about_PSSessions.

Type: PSSession[]

Position: 0
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SessionName

Specifies a friendly name for a disconnected session. You can use the name to refer
to the session
in subsequent commands, such as a Get-PSSession command. This
parameter is valid only with the
InDisconnectedSession parameter.

This parameter was introduced in PowerShell 3.0.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SessionOption

Specifies advanced options for the session. Enter a SessionOption object, such as
one that you
create using the New-PSSessionOption cmdlet, or a hash table in which
the keys are session option
names and the values are session option values.

7 Note

If you specify a hashtable for SessionOption, PowerShell converts the hashtable


into a
System.Management.Autiomation.Remoting.PSSessionOption object.
The values for keys specified
in the hashtable are cast to the matching property
of the object. This behaves differently from
calling New-PSSessionOption . For
example, the System.TimeSpan values for the timeout
properties, like
IdleTimeout, convert an integer value into ticks instead of milliseconds.
For
more information on the PSSessionOption object and its properties, see
PSSessionOption

The default values for the options are determined by the value of the
$PSSessionOption preference
variable, if it's set. Otherwise, the default values are
established by options set in the session
configuration.
The session option values take precedence over default values for sessions set in the
$PSSessionOption preference variable and in the session configuration. However,
they don't take
precedence over maximum values, quotas, or limits set in the session
configuration.

For a description of the session options that includes the default values, see
New-
PSSessionOption . For information about the $PSSessionOption preference variable,

see
about_Preference_Variables. For more information about
session configurations,
see about_Session_Configurations.

Type: PSSessionOption

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ThrottleLimit

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.

Type: Int32

Position: Named

Default value: 32

Accept pipeline input: False

Accept wildcard characters: False

-UseSSL

Indicates that this cmdlet uses the Secure Sockets Layer (SSL) protocol to establish a
connection to
the remote computer. By default, SSL isn't used.

WS-Management encrypts all PowerShell content transmitted over the network. The
UseSSL parameter
is an additional protection that sends the data across an HTTPS,
instead of HTTP.

If you use this parameter, but SSL isn't available on the port that's used for the
command, the
command fails.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-VMId

Specifies an array of IDs of virtual machines.

Type: Guid[]

Aliases: VMGuid

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-VMName

Specifies an array of names of virtual machines.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

Inputs
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

If you use the AsJob parameter, this cmdlet returns a job object.

PSSession

If you use the InDisconnectedSession parameter, this cmdlet returns a PSSession object.

Object

By default, this cmdlet returns the output of the invoked command, which is the value of
the
ScriptBlock parameter.

Notes
Windows PowerShell includes the following aliases for Invoke-Command :

icm

On Windows Vista, and later versions of the Windows operating system, to use the
ComputerName
parameter of Invoke-Command to run a command on the local
computer, you must run PowerShell using
the Run as administrator option.

When you run commands on multiple computers, 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's
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 makes sure that
terminating errors on one computer don't close the
command on all computers on
which it's run. This practice is used even when a remote command is run
on a single
computer.

If the remote computer isn't 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\>

When you disconnect a PSSession using the InDisconnectedSession parameter, the


session
state is Disconnected and the availability is None. The value of the State
property is
relative to the current session. A value of Disconnected means that the
PSSession isn't
connected to the current session. However, it doesn't mean that the
PSSession is disconnected
from all sessions. It might be connected to a different
session. To determine whether you can
connect or reconnect to the session, use the
Availability property.

An Availability value of None indicates that you can connect to the session. A value of
Busy indicates that you can't connect to the PSSession because it's connected to
another
session. For more information about the values of the State property of
sessions, see
RunspaceState. For more
information about the values of the Availability
property of sessions, see
RunspaceAvailability.

Related Links
about_PSSessions
about_Remote
about_Remote_Disconnected_Sessions
about_Remote_Troubleshooting
about_Remote_Variables
about_Scopes
Enter-PSSession
Exit-PSSession
Get-PSSession
Invoke-Item
New-PSSession
Remove-PSSession
WSMan Provider
Invoke-History
Reference
Module: Microsoft.PowerShell.Core

Runs commands from the session history.

Syntax
PowerShell

Invoke-History

[[-Id] <String>]

[-WhatIf]

[-Confirm]

[<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
the Get-History cmdlet.

The session history is managed separately from the history maintained by the
PSReadLine module.
Both histories are available in sessions where PSReadLine is
loaded. This cmdlet only works with
the session history. For more information see,
about_PSReadLine.

Examples

Example 1: Run the most recent command in the history


This example runs the last, or most recent, command in the session history. You can
abbreviate this
command as r , the alias for Invoke-History .

PowerShell

Invoke-History
Example 2: Run the command that has a specified ID
This example 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 the following: Invoke-
History 132 ,
ihy 132 , or r 132 .

PowerShell

Invoke-History -Id 132

Example 3: Run the most recent command by using the


command text
This example 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, starting with the most recent commands.

PowerShell

Invoke-History -Id get-pr

7 Note

Pattern matching is case-insensitive, but the pattern matches the beginning of the
line.

Example 4: Run a sequence of commands from the


history
This example runs commands 16 through 24. Because you can list only one Id value, the
command
uses the ForEach-Object cmdlet to run the Invoke-History command one
time for each Id value.

PowerShell

16..24 | ForEach {Invoke-History -Id $_ }

Example 5
This example runs the seven commands in the history that end with command 255 (249
through 255). It
uses the Get-History cmdlet to retrieve the commands. Because you
can list only one Id value,
the command uses the ForEach-Object cmdlet to run the
Invoke-History command once for each
Id value.

PowerShell

Get-History -Id 255 -Count 7 | ForEach {Invoke-History -Id $_.Id}

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Id

Specifies the Id of 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, or most recent, command. To
find the Id number of a
command, use the Get-History cmdlet.

Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False


-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a history Id to this cmdlet.

Outputs
None

This cmdlet returns no output of its own, but the commands it runs may return their
own output.

Notes
Windows PowerShell includes the following aliases for Invoke-History :

ihy

The session history is a list of the commands entered during the session. The session
history
represents the order of execution, the status, and the start and end times of the
command. As you
enter each command, PowerShell adds it to the history so that you
can reuse it. For more information
about the session history, see about_History.

Related Links
Add-History
Clear-History
Get-History
New-Module
Reference
Module: Microsoft.PowerShell.Core

Creates a new dynamic module that exists only in memory.

Syntax
PowerShell

New-Module

[-ScriptBlock] <ScriptBlock>

[-Function <String[]>]

[-Cmdlet <String[]>]

[-ReturnResult]

[-AsCustomObject]

[-ArgumentList <Object[]>]

[<CommonParameters>]

PowerShell

New-Module

[-Name] <String>

[-ScriptBlock] <ScriptBlock>

[-Function <String[]>]

[-Cmdlet <String[]>]

[-ReturnResult]

[-AsCustomObject]

[-ArgumentList <Object[]>]

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

You can also use the AsCustomObject parameter of New-Module to return the dynamic
module as a
custom object. The members of the modules, such as functions, are
implemented as script methods of
the custom object instead of being imported into the
session.

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.

Examples

Example 1: Create a dynamic module


This example creates a new dynamic module with a function called Hello . The
command returns a
module object that represents the new dynamic module.

PowerShell

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 : {}

Example 2: Working with dynamic modules and Get-


Module and Get-Command
This example demonstrates that dynamic modules are not returned by the Get-Module
cmdlet. The
members that they export are returned by the Get-Command cmdlet.
PowerShell

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 : {}

Get-Module

Get-Command Hello

CommandType Name Definition


----------- ---- ----------
Function Hello "Hello!"

Example 3: Export a variable into the current session


This example uses the Export-ModuleMember cmdlet to export a variable into the current
session.
Without the Export-ModuleMember command, only the function is exported.

PowerShell

New-Module -ScriptBlock {$SayHelloHelp="Type 'SayHello', a space, and a


name."; function SayHello ($name) { "Hello, $name" }; Export-ModuleMember -
function SayHello -Variable SayHelloHelp}

$SayHelloHelp

Type 'SayHello', a space, and a name.

SayHello Jeffrey

Hello, Jeffrey

The output shows that both the variable and the function were exported into the
session.
Example 4: Make a dynamic module available to Get-
Module
This example demonstrates that you can make a dynamic module available to Get-
Module by piping the
dynamic module to Import-Module .

New-Module creates a module object that is piped to the Import-Module cmdlet. The

Name
parameter of New-Module assigns a friendly name to the module. Because Import-
Module does not
return any objects by default, there is no output from this command.

Get-Module that the


GreetingModule has been imported into the current session.

PowerShell

New-Module -ScriptBlock {function Hello {"Hello!"}} -name GreetingModule |


Import-Module

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 : {}

Get-Command hello

CommandType Name
Definition

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

Function Hello
"Hello!"

The Get-Command cmdlet shows the Hello function that the dynamic module exports.

Example 5: Generate a custom object that has exported


functions
This example shows how to use the AsCustomObject parameter of New-Module to
generate a custom
object that has script methods that represent the exported functions.

The New-Module cmdlet creates a dynamic module with two functions, Hello and
Goodbye . The
AsCustomObject parameter creates a custom object instead of the
PSModuleInfo object that
New-Module generates by default. This custom object is saved
in the $m variable.
The $m variable appears to have no assigned value.

PowerShell

$m = New-Module -ScriptBlock {

function Hello ($name) {"Hello, $name"}

function Goodbye ($name) {"Goodbye, $name"}

} -AsCustomObject

$m

$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();

$m.goodbye("Jane")

Goodbye, Jane

$m.hello("Manoj")

Hello, Manoj

Piping $m to the Get-Member cmdlet 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.
Finally, we call these script methods and display the results.

Example 6: Get the results of the script block


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

PowerShell
New-Module -ScriptBlock {function SayHello {"Hello, World!"}; SayHello} -
ReturnResult

Hello, World!

Parameters
-ArgumentList

Specifies an array of arguments which are parameter values that are passed to the
script block. For
more information about the behavior of ArgumentList, see
about_Splatting.

Type: Object[]

Aliases: Args

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-AsCustomObject

Indicates that this cmdlet returns a custom object that represents the dynamic
module. The module
members are implemented as script methods of the custom
object, but they are not imported into the
session. 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 can be accessed
from the custom object.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-Cmdlet

Specifies an array of cmdlets that this cmdlet exports 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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Function

Specifies an array of functions that this cmdlet exports 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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Name

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 starts with __DynamicModule_ and is
followed by a
GUID that specifies the path of the dynamic module.

Type: String

Position: 0

Default value: None


Accept pipeline input: True

Accept wildcard characters: False

-ReturnResult

Indicates that this cmdlet runs the script block and returns the script block results
instead of
returning a module object.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ScriptBlock

Specifies the contents of the dynamic module. Enclose the contents in braces ( {} ) to
create a
script block. This parameter is required.

Type: ScriptBlock

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a module name to this cmdlet.

Outputs
PSModuleInfo

This cmdlet generates a PSModuleInfo object by default.


PSCustomObject

If you use the AsCustomObject parameter, it generates a PSCustomObject object.

Object

If you use the ReturnResult parameter, this cmdlet returns the result of evaluating the
script
block in the dynamic module.

Notes
Windows PowerShell includes the following aliases for New-Module :

nmo

You can also refer to New-Module by its alias, nmo . For more information, see
about_Aliases.

Related Links
Export-ModuleMember
Get-Module
Import-Module
Remove-Module
about_Modules
New-ModuleManifest
Reference
Module: Microsoft.PowerShell.Core

Creates a new module manifest.

Syntax
PowerShell

New-ModuleManifest

[-Path] <string>

[-NestedModules <Object[]>]

[-Guid <guid>]

[-Author <string>]

[-CompanyName <string>]

[-Copyright <string>]

[-RootModule <string>]

[-ModuleVersion <version>]

[-Description <string>]

[-ProcessorArchitecture <ProcessorArchitecture>]

[-PowerShellVersion <version>]
[-ClrVersion <version>]

[-DotNetFrameworkVersion <version>]

[-PowerShellHostName <string>]
[-PowerShellHostVersion <version>]

[-RequiredModules <Object[]>]

[-TypesToProcess <string[]>]

[-FormatsToProcess <string[]>]
[-ScriptsToProcess <string[]>]
[-RequiredAssemblies <string[]>]

[-FileList <string[]>]

[-ModuleList <Object[]>]

[-FunctionsToExport <string[]>]

[-AliasesToExport <string[]>]

[-VariablesToExport <string[]>]

[-CmdletsToExport <string[]>]

[-DscResourcesToExport <string[]>]

[-CompatiblePSEditions <string[]>]

[-PrivateData <Object>]

[-Tags <string[]>]

[-ProjectUri <uri>]

[-LicenseUri <uri>]

[-IconUri <uri>]

[-ReleaseNotes <string>]

[-HelpInfoUri <string>]

[-PassThru]

[-DefaultCommandPrefix <string>]

[-WhatIf]

[-Confirm]

[<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 aren't required for a module.

New-ModuleManifest creates a manifest that includes all 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 doesn't add, open the resulting file in a text
editor.

Each parameter, except for Path and PassThru, creates a module manifest key and its
value.
In a module manifest, only the ModuleVersion key is required. Unless specified in
the parameter
description, if you omit a parameter from the command, New-
ModuleManifest creates a comment string
for the associated value that has no effect.

In PowerShell 2.0, New-ModuleManifest prompts you for the values of commonly used
parameters that
aren't specified in the command, in addition to required parameter
values. Beginning in PowerShell
3.0, New-ModuleManifest prompts only when required
parameter values aren't specified.

If you are planning to publish your module in the PowerShell Gallery, the manifest must
contain
values for certain properties. For more information, see
Required metadata for
items published to the PowerShell Gallery
in the Gallery documentation.

Examples

Example 1 - Create a new module manifest


This example creates a new module manifest in the file that is specified by the Path
parameter.
The PassThru parameter sends the output to the pipeline and to the file.

The output shows the default values of all keys in the manifest.
PowerShell

New-ModuleManifest -Path C:\ps-test\Test-Module\Test-Module.psd1 -PassThru

# Module manifest for module 'Test-Module'

# Generated by: ContosoAdmin

# Generated on: 1/22/2019

@{

# Script module or binary module file associated with this manifest.

# RootModule = ''

# Version number of this module.

ModuleVersion = '1.0'

# Supported PSEditions

# CompatiblePSEditions = @()

# ID used to uniquely identify this module

GUID = '47179120-0bcb-4f14-8d80-f4560107f85c'

# Author of this module

Author = 'ContosoAdmin'

# Company or vendor of this module

CompanyName = 'Unknown'

# Copyright statement for this module

Copyright = '(c) 2019 ContosoAdmin. All rights reserved.'

# Description of the functionality provided by this module

# Description = ''

# Minimum version of the Windows PowerShell engine required by this module

# PowerShellVersion = ''

# Name of the Windows PowerShell host required by this module

# PowerShellHostName = ''

# Minimum version of the Windows PowerShell host required by this module

# PowerShellHostVersion = ''

# Minimum version of Microsoft .NET Framework required by this module. This


prerequisite is valid for the PowerShell Desktop edition only.

# DotNetFrameworkVersion = ''

# Minimum version of the common language runtime (CLR) required by this


module. This prerequisite is valid for the PowerShell Desktop edition only.

# CLRVersion = ''

# Processor architecture (None, X86, Amd64) required by this module

# ProcessorArchitecture = ''

# Modules that must be imported into the global environment prior to


importing this module

# RequiredModules = @()

# Assemblies that must be loaded prior to importing this module

# RequiredAssemblies = @()

# Script files (.ps1) that are run in the caller's environment prior to
importing this module.

# ScriptsToProcess = @()

# Type files (.ps1xml) to be loaded when importing this module

# TypesToProcess = @()

# Format files (.ps1xml) to be loaded when importing this module

# FormatsToProcess = @()

# Modules to import as nested modules of the module specified in


RootModule/ModuleToProcess

# NestedModules = @()

# Functions to export from this module, for best performance, do not use
wildcards and do not delete the entry, use an empty array if there are no
functions to export.

FunctionsToExport = @()

# Cmdlets to export from this module, for best performance, do not use
wildcards and do not delete the entry, use an empty array if there are no
cmdlets to export.

CmdletsToExport = @()

# Variables to export from this module

VariablesToExport = '*'

# Aliases to export from this module, for best performance, do not use
wildcards and do not delete the entry, use an empty array if there are no
aliases to export.

AliasesToExport = @()

# DSC resources to export from this module

# DscResourcesToExport = @()

# List of all modules packaged with this module

# ModuleList = @()

# List of all files packaged with this module

# FileList = @()

# Private data to pass to the module specified in


RootModule/ModuleToProcess. This may also contain a PSData hashtable with
additional module metadata used by PowerShell.

PrivateData = @{

PSData = @{

# Tags applied to this module. These help with module discovery in


online galleries.

# Tags = @()

# A URL to the license for this module.

# LicenseUri = ''

# A URL to the main website for this project.

# ProjectUri = ''

# A URL to an icon representing this module.

# IconUri = ''

# ReleaseNotes of this module

# ReleaseNotes = ''

} # End of PSData hashtable

} # End of PrivateData hashtable

# HelpInfo URI of this module

# HelpInfoURI = ''

# Default prefix for commands exported from this module. Override the
default prefix using Import-Module -Prefix.

# DefaultCommandPrefix = ''

Example 2 - Create a new manifest with some


prepopulated settings
This example creates a new module manifest. It uses the PowerShellVersion and
AliasesToExport parameters to add values to the corresponding manifest keys.

PowerShell

$moduleSettings = @{

PowerShellVersion = 1.0

Path = 'C:\ps-test\ManifestTest.psd1'

AliasesToExport = @(

'JKBC'

'DRC'

'TAC'

New-ModuleManifest @moduleSettings
Example 3 - Create a manifest that requires other
modules
This example uses a string format to specify the name of the BitsTransfer module and
the hash
table format to specify the name, a GUID, and a version of the
PSScheduledJob module.

PowerShell

$moduleSettings = @{

RequiredModules = ("BitsTransfer", @{

ModuleName="PSScheduledJob"

ModuleVersion="1.0.0.0";

GUID="50cdb55f-5ab7-489f-9e94-4ec21ff51e59"

})

Path = 'C:\ps-test\ManifestTest.psd1'

New-ModuleManifest @moduleSettings

This example shows how to use the string and hash table formats of the ModuleList,
RequiredModules, and NestedModules parameter. You can combine strings and hash
tables in the
same parameter value.

Example 4 - Create a manifest that supports updateable


help
This example uses the HelpInfoUri parameter to create a HelpInfoUri key in the module
manifest. The value of the parameter and the key must begin with http or https. This
value
tells the Updatable Help system where to find the HelpInfo XML updatable help
information file for
the module.

PowerShell

$moduleSettings = @{

HelpInfoUri = 'http://https://go.microsoft.com/fwlink/?LinkID=603'

Path = 'C:\ps-test\ManifestTest.psd1'

New-ModuleManifest @moduleSettings

For information about Updatable Help, see about_Updatable_Help.


For information
about the HelpInfo XML file, see Supporting Updatable Help.
Example 5 - Getting module information
This example shows how to get the configuration values of a module. The values in the
module
manifest are reflected in the values of properties of the module object.

The Get-Module cmdlet is used to get the Microsoft.PowerShell.Diagnostics module


using the
List parameter. The command sends the module to the Format-List cmdlet to
display all
properties and values of the module object.

PowerShell

Get-Module Microsoft.PowerShell.Diagnostics -List | Format-List -Property *

LogPipelineExecutionDetails : False

Name : Microsoft.PowerShell.Diagnostics

Path :
C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Microsoft.PowerShell.Diag
nostics\Micro

soft.PowerShell.Diagnostics.psd1

Definition :

Description :

Guid : ca046f10-ca64-4740-8ff9-2565dba61a4f

HelpInfoUri : https://go.microsoft.com/fwlink/?LinkID=210596

ModuleBase :
C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Microsoft.PowerShell.Diag
nostics

PrivateData :

Version : 3.0.0.0

ModuleType : Manifest

Author : Microsoft Corporation

AccessMode : ReadWrite

ClrVersion : 4.0

CompanyName : Microsoft Corporation

Copyright : Microsoft Corporation. All rights reserved.

DotNetFrameworkVersion :

ExportedFunctions : {}

ExportedCmdlets : {[Get-WinEvent, Get-WinEvent], [Get-Counter,


Get-Counter], [Import-Counter,

Import-Counter], [Export-Counter, Export-


Counter]...}

ExportedCommands : {[Get-WinEvent, Get-WinEvent], [Get-Counter,


Get-Counter], [Import-Counter,

Import-Counter], [Export-Counter, Export-


Counter]...}

FileList : {}

ModuleList : {}

NestedModules : {}

PowerShellHostName :

PowerShellHostVersion :

PowerShellVersion : 3.0

ProcessorArchitecture : None

Scripts : {}

RequiredAssemblies : {}

RequiredModules : {}

RootModule :

ExportedVariables : {}

ExportedAliases : {}

ExportedWorkflows : {}

SessionState :

OnRemove :

ExportedFormatFiles :
{C:\Windows\system32\WindowsPowerShell\v1.0\Event.format.ps1xml,

C:\Windows\system32\WindowsPowerShell\v1.0\Diagnostics.format.ps1xml}

ExportedTypeFiles :
{C:\Windows\system32\WindowsPowerShell\v1.0\GetEvent.types.ps1xml}

Parameters
-AliasesToExport

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 can't 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 defined in the module are exported by the
manifest.

Type: String[]

Position: Named

Default value: * (all)

Accept pipeline input: False

Accept wildcard characters: True

-Author

Specifies the module author.

If you omit this parameter, New-ModuleManifest creates an Author key with the name
of the
current user.

Type: String
Position: Named

Default value: Name of the current user

Accept pipeline input: False

Accept wildcard characters: False

-ClrVersion

Specifies the minimum version of the Common Language Runtime (CLR) of the
Microsoft .NET Framework
that the module requires.

7 Note

This setting is valid for the PowerShell Desktop edition only, such as Windows
PowerShell 5.1,
and only applies to .NET Framework versions lower than 4.5. This
requirement has no effect for
newer versions of PowerShell or the .NET
Framework.

Type: Version

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-CmdletsToExport

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 can't 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 defined in the module are exported by
the manifest.

Type: String[]

Position: Named
Default value: * (all)

Accept pipeline input: False

Accept wildcard characters: True

-CompanyName

Identifies the company or vendor who created the module.

If you omit this parameter, New-ModuleManifest creates a CompanyName key with a


value of
"Unknown".

Type: String

Position: Named

Default value: "Unknown"

Accept pipeline input: False

Accept wildcard characters: False

-CompatiblePSEditions

Specifies the module's compatible PSEditions. For information about PSEdition, see
Modules with compatible PowerShell Editions.

Type: String[]

Accepted values: Desktop, Core

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named
Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Copyright

Specifies a copyright statement for the module.

If you omit this parameter, 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.

Type: String

Position: Named

Default value: (c) <year> <username>. All rights reserved.

Accept pipeline input: False

Accept wildcard characters: False

-DefaultCommandPrefix

Specifies a prefix that is prepended to the nouns of all commands in the module
when they're
imported into a session. Enter a prefix string. Prefixes prevent
command name conflicts in a user's
session.

Module users can override this prefix by specifying the Prefix parameter of the
Import-Module
cmdlet.

This parameter was introduced in PowerShell 3.0.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Description
Describes the contents of the module.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-DotNetFrameworkVersion

Specifies the minimum version of the Microsoft .NET Framework that the module
requires.

7 Note

This setting is valid for the PowerShell Desktop edition only, such as Windows
PowerShell 5.1,
and only applies to .NET Framework versions lower than 4.5. This
requirement has no effect for
newer versions of PowerShell or the .NET
Framework.

Type: Version

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-DscResourcesToExport

Specifies the Desired State Configuration (DSC) resources that the module exports.
Wildcards are
permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: True

-FileList

Specifies all items that are included in the module.

This key is designed to act as a module inventory. The files listed in the key are
included when the
module is published, but any functions aren't automatically
exported.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-FormatsToProcess

Specifies the formatting files ( .ps1xml ) that run when the module is imported.

When you import a module, PowerShell runs the Update-FormatData cmdlet with the
specified files.
Because formatting files aren't scoped, they affect all session states in
the session.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-FunctionsToExport

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 can't 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 defined in the module are exported
by the manifest.

Type: String[]

Position: Named

Default value: * (all)

Accept pipeline input: False

Accept wildcard characters: True

-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 PowerShell, type [guid]::NewGuid() .

Type: Guid

Position: Named

Default value: A GUID generated for the module

Accept pipeline input: False

Accept wildcard characters: False

-HelpInfoUri

Specifies the internet address of the HelpInfo XML file for the module. Enter a
Uniform Resource
Identifier (URI) that begins with http or https.

The HelpInfo XML file supports the Updatable Help feature that was introduced in
PowerShell 3.0. It
contains information about the location of downloadable help files
for the module and the version
numbers of the newest help files for each supported
locale.

For information about Updatable Help, see about_Updatable_Help.


For information
about the HelpInfo XML file, see
Supporting Updatable Help.
This parameter was introduced in PowerShell 3.0.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-IconUri

Specifies the URL of an icon for the module. The specified icon is displayed on the
gallery web page
for the module.

Type: Uri

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-LicenseUri

Specifies the URL of licensing terms for the module.

Type: Uri

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ModuleList

Lists all modules that are included in this module.

Enter each module name as a string or as a hash table with ModuleName and
ModuleVersion
keys. The hash table can also have an optional GUID key. You can
combine strings and hash tables
in the parameter value.
This key is designed to act as a module inventory. The modules that are listed in the
value of this
key aren't automatically processed.

Type: Object[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ModuleVersion

Specifies the module's version.

This parameter isn't required, 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.

Type: Version

Position: Named

Default value: 1.0

Accept pipeline input: False

Accept wildcard characters: False

-NestedModules

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're listed in
the value.

Enter each module name as a string or as a hash table with ModuleName and
ModuleVersion
keys. The hash table can also have an optional GUID key. You can
combine strings and hash tables
in the parameter 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-ModuleMember
command.
Nested modules in the module session state are available to the root module, but
they aren't
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.

Type: Object[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-PassThru

Writes the resulting module manifest to the console and creates a .psd1 file. By
default, this
cmdlet doesn't generate any output.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Path

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

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

Type: String

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-PowerShellHostName

Specifies the name of the PowerShell host program that the module requires. Enter
the name of the
host program, such as Windows PowerShell ISE Host or
ConsoleHost. Wildcards aren't
permitted.

To find the name of a host program, in the program, type $Host.Name .

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-PowerShellHostVersion

Specifies the minimum version of the PowerShell host program that works with the
module. Enter a
version number, such as 1.1.

Type: Version

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-PowerShellVersion

Specifies the minimum version of PowerShell that works with this module. For
example, you can enter
1.0, 2.0, or 3.0 as the parameter's value. It must be in an X.X
format. For example, if you submit
5 , PowerShell will throw an error.

Type: Version

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-PrivateData

Specifies data that is passed to the module when it's imported.

Type: Object

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ProcessorArchitecture

Specifies the processor architecture that the module requires. Valid values are x86,
AMD64, IA64,
MSIL, and None (unknown or unspecified).

Type: ProcessorArchitecture

Accepted values: None, MSIL, X86, IA64, Amd64, Arm

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ProjectUri
Specifies the URL of a web page about this project.

Type: Uri

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ReleaseNotes

Specifies release notes.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RequiredAssemblies

Specifies the assembly ( .dll ) files that the module requires. Enter the assembly file
names.
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 RootModule 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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-RequiredModules

Specifies modules that must be in the global session state. If the required modules
aren't in the
global session state, PowerShell imports them. If the required modules
aren't available, the
Import-Module command fails.

Enter each module name as a string or as a hash table with ModuleName and
ModuleVersion
keys. The hash table can also have an optional GUID key. You can
combine strings and hash tables
in the parameter value.

In PowerShell 2.0, Import-Module doesn't import required modules automatically. It


just verifies
that the required modules are in the global session state.

Type: Object[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RootModule

Specifies the primary or root file of the module. Enter the file name of a script ( .ps1 ),
a script
module ( .psm1 ), a module manifest( .psd1 ), an assembly ( .dll ), a cmdlet
definition XML file
( .cdxml ), or a workflow ( .xaml ). When the module is imported,
the members that are exported from
the root module file are imported into the
caller's session state.

If a module has a manifest file and no root file was designated in the RootModule
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 RootModule or
NestedModules keys in the
manifest. Otherwise, their members aren't exported.

7 Note

In PowerShell 2.0, this key was called ModuleToProcess. You can use the
RootModule
parameter name or its ModuleToProcess alias.
Type: String

Aliases: ModuleToProcess

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ScriptsToProcess

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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Tags

Specifies an array of tags.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-TypesToProcess

Specifies the type files ( .ps1xml ) that run when the module is imported.
When you import the module, PowerShell runs the Update-TypeData cmdlet with the
specified files.
Because type files aren't scoped, they affect all session states in the
session.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-VariablesToExport

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 can't 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 defined in the module are exported by
the manifest.

Type: String[]

Position: Named

Default value: * (all)

Accept pipeline input: False

Accept wildcard characters: True

-WhatIf

Shows what would happen if New-ModuleManifest runs. The cmdlet isn't run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False


Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

String

When you use the PassThru parameter, this cmdlet returns a string representing the
module
manifest.

Notes
New-ModuleManifest creates module manifest ( .psd1 ) files encoded as UTF16.

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, start PowerShell with the Run as
administrator option.

In PowerShell 2.0, many parameters of New-ModuleManifest were mandatory, even


though they weren't
required in a module manifest. Beginning in PowerShell 3.0, only
the Path parameter is
mandatory.

A session is an instance of the PowerShell execution environment. A session can have


one or more
session states. 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.
Related Links
Export-ModuleMember
Get-Module
Import-Module
New-Module
Remove-Module
Test-ModuleManifest
about_Modules
New-PSRoleCapabilityFile
Reference
Module: Microsoft.PowerShell.Core

Creates a file that defines a set of capabilities to be exposed through a session


configuration.

Syntax
PowerShell

New-PSRoleCapabilityFile

[-Path] <String>

[-Guid <Guid>]

[-Author <String>]

[-Description <String>]

[-CompanyName <String>]

[-Copyright <String>]

[-ModulesToImport <Object[]>]

[-VisibleAliases <String[]>]

[-VisibleCmdlets <Object[]>]

[-VisibleFunctions <Object[]>]
[-VisibleExternalCommands <String[]>]

[-VisibleProviders <String[]>]
[-ScriptsToProcess <String[]>]
[-AliasDefinitions <IDictionary[]>]

[-FunctionDefinitions <IDictionary[]>]

[-VariableDefinitions <Object>]

[-EnvironmentVariables <IDictionary>]

[-TypesToProcess <String[]>]

[-FormatsToProcess <String[]>]
[-AssembliesToLoad <String[]>]
[<CommonParameters>]

Description
The New-PSRoleCapabilityFile cmdlet creates a file that defines a set of user capabilities
that
can be exposed through session configuration files. This includes determining
which cmdlets,
functions, and scripts are available to users. The capability file is a
human-readable text file
that contains a hash table of session configuration properties
and values. The file has a .psrc file
name extension, and can be used by more than one
session configuration.
All the parameters of New-PSRoleCapabilityFile are optional except for the Path
parameter,
which specifies the path for the file. If you don't include a parameter when
you run the cmdlet, the
corresponding key in the session configuration file is
commented-out, except where noted in the
parameter description. For example, if you
don't include the AssembliesToLoad parameter then
that section of the session
configuration file is commented out.

To use the role capability file in a session configuration, first place the file in a
RoleCapabilities subfolder of a valid PowerShell module folder. Then reference the file
by name
in the RoleDefinitions field in a PowerShell Session Configuration (.pssc) file.

This cmdlet was introduced in Windows PowerShell 5.0.

Examples

Example 1: Create a blank role capability file


This example creates a new role capability file that uses the default (blank) values. The
file can
later be edited in a text editor to change these configuration settings.

PowerShell

New-PSRoleCapabilityFile -Path ".\ExampleFile.psrc"

Example 2: Create a role capability file allowing users to


restart services and any VDI computer
This example creates a sample role capability file that enables users to restart services
and
computers that match a specific name pattern. Name filtering is defined by setting
the
ValidatePattern parameter to the regular expression VDI\d+ .

PowerShell

$roleParameters = @{

Path = ".\Maintenance.psrc"

Author = "User01"

CompanyName = "Fabrikam Corporation"

Description = "This role enables users to restart any service and


restart any VDI computer."

ModulesToImport = "Microsoft.PowerShell.Core"

VisibleCmdlets = "Restart-Service", @{

Name = "Restart-Computer"

Parameters = @{ Name = "ComputerName"; ValidatePattern


= "VDI\d+" }

New-PSRoleCapabilityFile @roleParameters

Parameters
-AliasDefinitions

Adds the specified aliases to sessions that use the role capability file. Enter a hash
table with
the following keys:

Name. Name of the alias. This key is required.


Value. The command that the alias represents. This key is required.
Description. A text string that describes the alias. This key is optional.
Options. Alias options. This key is optional. The default value is None. The
acceptable values for
this parameter are: None, ReadOnly, Constant, Private, or
AllScope.

For example: @{Name="hlp";Value="Get-Help";Description="Gets


help";Options="ReadOnly"}

Type: IDictionary[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-AssembliesToLoad

Specifies the assemblies to load into the sessions that use the role capability file.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-Author

Specifies the user that created the role capability file.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-CompanyName

Identifies the company that created the role capability file.


The default value is
Unknown.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Copyright

Specifies a copyright for the role capability file. If you omit this parameter,
New-
PSRoleCapabilityFile generates a copyright statement using the value of the Author
parameter.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Description

Specifies a description for the role capability file.


Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-EnvironmentVariables

Specifies the environment variables for sessions that expose this role capability file.
Enter a hash
table in which the keys are the environment variable names and the
values are the environment
variable values.

For example: EnvironmentVariables=@{TestShare="\\\\Server01\TestShare"}

Type: IDictionary

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-FormatsToProcess

Specifies the formatting files ( .ps1xml ) that run in sessions that use the role
capability file.
The value of this parameter must be a full or absolute path of the
formatting files.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-FunctionDefinitions
Adds the specified functions to sessions that expose the role capability. Enter a hash
table with
the following keys:

Name. Name of the function. This key is required.


ScriptBlock. Function body. Enter a script block. This key is required.
Options. Function options. This key is optional. The default value is None. The
acceptable values
for this parameter are: are None, ReadOnly, Constant, Private,
or AllScope.

For example:

@{Name="Get-PowerShellProcess";ScriptBlock={Get-Process
PowerShell};Options="AllScope"}

Type: IDictionary[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Guid

Specifies a unique identifier for the role capability file. If you omit this parameter,
New-PSRoleCapabilityFile generates a GUID for the file. To create a new GUID in

PowerShell, type
[guid]::NewGuid() .

Type: Guid

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ModulesToImport

Specifies the modules that are automatically imported into sessions that use the role
capability
file. By default, all the commands in listed modules are visible. When used
with VisibleCmdlets
or VisibleFunctions, the commands visible from the specified
modules can be restricted.
Each module used in the value of this parameter can be represented by a string or by
a hash table. A
module string consists only of the name of the module. A module
hash table can include
ModuleName, ModuleVersion, and GUID keys. Only the
ModuleName key is required.

For example, the following value consists of a string and a hash table. Any
combination of strings
and hash tables, in any order, is valid.

"TroubleshootingPack", @{ModuleName="PSDiagnostics";
ModuleVersion="1.0.0.0";GUID="c61d6278-02a3-4618-ae37-a524d40a7f44"}

Type: Object[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Path

Specifies the path and filename of the role capability file. The file must have a .psrc
filename
extension.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ScriptsToProcess

Specifies scripts to add to sessions that use the role capability file. Enter the path and
file
names of the scripts. The value of this parameter must be a full or absolute path
of the script file
names.

Type: String[]

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-TypesToProcess

Specifies type files ( .ps1xml ) to add to sessions that use the role capability file. Enter
the
type filenames. The value of this parameter must be a full or absolute path of the
type filenames.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-VariableDefinitions

Specifies variables to add to sessions that use the role capability file. Enter a hash
table with
the following keys:

Name. Name of the variable. This key is required.


Value. Variable value. This key is required.

For example: @{Name="WarningPreference";Value="SilentlyContinue"}

Type: Object

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-VisibleAliases

Limits the aliases in the session to those aliases specified in the value of this
parameter, plus
any aliases that you define in the AliasDefinition parameter.
Wildcard characters are supported.
By default, all aliases that are defined by the
PowerShell engine and all aliases that modules
export are visible in the session.
For example, to limit the available aliases to gm and gcm use this syntax:
VisibleAliases="gcm", "gp"

When any Visible parameter is included in the role capability file, PowerShell
removes the
Import-Module cmdlet and its ipmo alias from the session.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-VisibleCmdlets

Limits the cmdlets in the session to those specified in the value of this parameter.
Wildcard
characters and Module Qualified Names are supported.

By default, all cmdlets that the modules in the session export are visible in the
session. Use the
SessionType and ModulesToImport parameters to determine which
modules and snap-ins are
imported into the session. If no modules in
ModulesToImport expose the cmdlet,
New-PSRoleCapabilityFile tries to load the
appropriate module.

When any Visible parameter is included in the session configuration file, PowerShell
removes the
Import-Module cmdlet and its ipmo alias from the session.

Type: Object[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-VisibleExternalCommands

Limits the external binaries, scripts and commands that can be executed in the
session to those
specified in the value of this parameter.

By default, no external commands are visible in this session.


When any Visible parameter is included in the session configuration file, PowerShell
removes the
Import-Module cmdlet and its ipmo alias from the session.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-VisibleFunctions

Limits the functions in the session to those specified in the value of this parameter,
plus any
functions that you define in the FunctionDefinitions parameter. Wildcard
characters are
supported.

By default, all functions exported by modules in the session are visible in that
session. Use the
SessionType and ModulesToImport parameters to determine which
modules are imported into the
session.

When any Visible parameter is included in the session configuration file, PowerShell
removes the
Import-Module cmdlet and its ipmo alias from the session.

Type: Object[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-VisibleProviders

Limits the PowerShell providers in the session to those specified in the value of this
parameter.
Wildcard characters are supported.

By default, all providers exported by a module in the session are visible in the
session. Use the
SessionType and ModulesToImport parameters to determine which
modules are imported into the
session.

When any Visible parameter is included in the session configuration file, PowerShell
removes the
Import-Module cmdlet and its ipmo alias from the session.
Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

Related Links
New-PSSessionConfigurationFile
Get-PSSessionCapability
New-PSSession
Reference
Module: Microsoft.PowerShell.Core

Creates a persistent connection to a local or remote computer.

Syntax
PowerShell

New-PSSession

[[-ComputerName] <String[]>]

[-Credential <PSCredential>]

[-Name <String[]>]

[-EnableNetworkAccess]

[-ConfigurationName <String>]

[-Port <Int32>]

[-UseSSL]

[-ApplicationName <String>]

[-ThrottleLimit <Int32>]

[-SessionOption <PSSessionOption>]

[-Authentication <AuthenticationMechanism>]

[-CertificateThumbprint <String>]

[<CommonParameters>]

PowerShell

New-PSSession

[-Credential <PSCredential>]

[-Name <String[]>]

[-EnableNetworkAccess]

[-ConfigurationName <String>]

[-ThrottleLimit <Int32>]

[-ConnectionUri] <Uri[]>

[-AllowRedirection]

[-SessionOption <PSSessionOption>]

[-Authentication <AuthenticationMechanism>]

[-CertificateThumbprint <String>]

[<CommonParameters>]

PowerShell

New-PSSession

-Credential <PSCredential>

[-Name <String[]>]

[-ConfigurationName <String>]

[-VMId] <Guid[]>

[-ThrottleLimit <Int32>]

[<CommonParameters>]

PowerShell

New-PSSession

-Credential <PSCredential>

[-Name <String[]>]

[-ConfigurationName <String>]

-VMName <String[]>

[-ThrottleLimit <Int32>]

[<CommonParameters>]

PowerShell

New-PSSession

[[-Session] <PSSession[]>]

[-Name <String[]>]

[-EnableNetworkAccess]

[-ThrottleLimit <Int32>]

[<CommonParameters>]

PowerShell

New-PSSession

[-Name <String[]>]

[-ConfigurationName <String>]

-ContainerId <String[]>

[-RunAsAdministrator]

[-ThrottleLimit <Int32>]

[<CommonParameters>]

Description
The New-PSSession cmdlet creates a PowerShell session (PSSession) on a local or remote
computer. When you create a PSSession, 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, PowerShell creates a temporary connection that is used
for the command
and is then closed.

Examples

Example 1: Create a session on the local computer


PowerShell

$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: Create a session on a remote computer


PowerShell

$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 PSSession objects, assign them to variables with useful names.
This will
help you manage the PSSession objects in subsequent commands.

Example 3: Create sessions on multiple computers


PowerShell

$s1, $s2, $s3 = New-PSSession -ComputerName Server01,Server02,Server03

This command creates three PSSession objects, one on each of the computers specified
by the
ComputerName parameter.
The command uses the assignment operator ( = ) to assign the new PSSession objects to
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 a series of variables, PowerShell assigns each object
to a
variable in the series 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: Create a session with a specified port


PowerShell

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 alternative
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: Create a session based on an existing session


PowerShell

New-PSSession -Session $s -Credential Domain01\User01

This command creates a 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: Create a session with a global scope in a


different domain
PowerShell
$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, PSSession objects created at the command line are created with local scope
and
PSSession objects 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 together
with the credentials of the user.

Example 7: Create sessions for many computers


PowerShell

$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 PSSession
objects 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: Create a session by using a URI


PowerShell

$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
that has permission to create a session on the
remote computer.

Example 9: Run a background job in a set of sessions


PowerShell

$s = New-PSSession -ComputerName (Get-Content Servers.txt) -Credential


Domain01\Admin01 -ThrottleLimit 16

Invoke-Command -Session $s -ScriptBlock {Get-Process PowerShell} -AsJob

These commands create a set of PSSession objects and then run a background job in
each of the
PSSession objects.

The first command creates a new PSSession on each of the computers listed in the
Servers.txt
file. It uses the New-PSSession cmdlet to create the PSSession. The value of
the
ComputerName parameter is a command that uses the Get-Content cmdlet to get
the list of
computer names the Servers.txt file.

The command uses the Credential parameter to create the PSSession objects that have
the
permission of a domain administrator, and it uses the ThrottleLimit parameter to
limit the
command to 16 concurrent connections. The command saves the PSSession
objects in the $s
variable.

The second command uses the AsJob parameter of the Invoke-Command cmdlet to start a
background
job that runs a Get-Process PowerShell command in each of the PSSession
objects in $s .

For more information about PowerShell background jobs, see


about_Jobs and
about_Remote_Jobs.

Example 10: Create a session for a computer by using its


URI
PowerShell

New-PSSession -ConnectionURI https://management.exchangelabs.com/Management

This command creates a PSSession objects that connects to a computer that is specified
by a URI
instead of a computer name.
Example 11: Create a session option
PowerShell

$so = New-PSSessionOption -SkipCACheck

New-PSSession -ConnectionUri https://management.exchangelabs.com/Management


-SessionOption $so -Credential Server01\Admin01

This example shows how to create a session option object and use the SessionOption
parameter.

The first command uses the New-PSSessionOption cmdlet to create a session option. It
saves the
resulting SessionOption object in the $so variable.

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.

Parameters
-AllowRedirection

Indicates that this cmdlet 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, PowerShell does not redirect
connections, but you
can use this parameter to enable it to redirect the connection.

You can also limit the number of times the connection is redirected by changing the
MaximumConnectionRedirectionCount session option value. Use the
MaximumRedirection parameter
of the New-PSSessionOption cmdlet or set the
MaximumConnectionRedirectionCount property of the
$PSSessionOption
preference variable. The default value is 5 .

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


-ApplicationName

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.

Type: String

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Authentication

Specifies the mechanism that is used to authenticate the user's credentials. The
acceptable values
for this parameter are:

Default
Basic

Credssp

Digest
Kerberos

Negotiate
NegotiateWithImplicitCredential

The default value is Default .

For more information about the values of this parameter, see


AuthenticationMechanism Enumeration.

U Caution
Credential Security Support Provider (CredSSP) authentication, in which the user
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.

Type: AuthenticationMechanism

Accepted values: Default, Basic, Negotiate, NegotiateWithImplicitCredential,


Credssp, Digest, Kerberos

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-CertificateThumbprint

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, use the Get-Item or Get-ChildItem command in the PowerShell


Cert: drive.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ComputerName

Specifies an array of names of computers. This cmdlet creates a persistent


connection
(PSSession) to the specified computer. If you enter multiple computer
names, New-PSSession
creates multiple PSSession objects, 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
quotation marks, 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.

To include the local computer in the value of the ComputerName parameter, start
Windows
PowerShell by using the Run as administrator option.

Type: String[]

Aliases: Cn

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-ConfigurationName

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.

Type: String

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-ConnectionUri

Specifies a URI that defines the connection endpoint for the 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:5985/WSMAN

If you do not specify a ConnectionURI, you can use the UseSSL, ComputerName,
Port,
and ApplicationName parameters to specify the ConnectionURI values.

Valid values for the Transport segment of the URI are HTTP and HTTPS. If you specify
a connection
URI with a Transport segment, but do not specify a port, the session is
created with standards
ports: 80 for HTTP and 443 for HTTPS. To use the default
ports for PowerShell remoting, specify
port 5985 for HTTP or 5986 for HTTPS.

If the destination computer redirects the connection to a different URI, PowerShell


prevents the
redirection unless you use the AllowRedirection parameter in the
command.

Type: Uri[]

Aliases: URI, CU

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False


-ContainerId

Specifies an array of IDs of containers. This cmdlet starts an interactive session with
each of the
specified containers. Use the docker ps command to get a list of
container IDs. For more
information, see the help for the
docker ps command.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Credential

Specifies a user account that has permission to do this action. The default is the
current user.

Type a user name, such as User01 or Domain01\User01 , or enter a PSCredential


object
generated by the Get-Credential cmdlet. If you type a user name, you're
prompted to enter the
password.

Credentials are stored in a PSCredential


object and the password is stored as a
SecureString.

7 Note

For more information about SecureString data protection, see


How secure is
SecureString?.

Type: PSCredential

Position: Named

Default value: Current user

Accept pipeline input: True

Accept wildcard characters: False

-EnableNetworkAccess
Indicates that this cmdlet adds an interactive security token to loopback sessions.
The interactive
token lets you run commands in the loopback session that get data
from other computers. For example,
you can run a command in the session that
copies XML files from a remote computer to the local
computer.

A loopback session is a PSSession that originates and ends on the same computer.
To create a
loopback session, omit the ComputerName parameter or set its value to
dot ( . ), localhost , or
the name of the local computer.

By default, this cmdlet creates loopback sessions by using a network token, which
might not provide
sufficient permission to authenticate to remote computers.

The EnableNetworkAccess parameter is effective only in loopback sessions. If you


use
EnableNetworkAccess when you create a session on a remote computer, the
command succeeds, but
the parameter is ignored.

You can also enable remote access in a loopback session by using the CredSSP value
of the
Authentication parameter, which delegates the session credentials to other
computers.

To protect the computer from malicious access, disconnected loopback sessions that
have interactive
tokens, which are those created by using the EnableNetworkAccess
parameter, can be reconnected
only from the computer on which the session was
created. Disconnected sessions that use CredSSP
authentication can be reconnected
from other computers. For more information, see
Disconnect-PSSession .

This parameter was introduced in PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Name

Specifies a friendly name for the PSSession.

You can use the name to refer to the PSSession when you use other cmdlets, such as
Get-PSSession and Enter-PSSession . The name is not required to be unique to the

computer or the
current session.
Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Port

Specifies the network port on the remote computer that is used for this connection.
To connect to a
remote computer, the remote computer must be listening on the
port that the connection uses. The
default ports are 5985 , which is the WinRM port
for HTTP, and 5986 , which is the WinRM port for
HTTPS.

Before using another 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.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RunAsAdministrator

Indicates that the PSSession runs as administrator.

Type: SwitchParameter

Position: Named
Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Session

Specifies an array of PSSession objects that this cmdlet uses as a model for the new
PSSession. This parameter creates new PSSession objects that have the same
properties as the
specified PSSession objects.

Enter a variable that contains the PSSession objects or a command that creates or
gets the
PSSession objects, such as a New-PSSession or Get-PSSession command.

The resulting PSSession objects 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).

Type: PSSession[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-SessionOption

Specifies advanced options for the session. Enter a SessionOption object, such as
one that you
create by using the New-PSSessionOption cmdlet, or a hash table in
which the keys are session
option names and the values are session option values.

The default values for the options are determined by the value of the
$PSSessionOption preference
variable, if it is set. Otherwise, the default values are
established by options set in the session
configuration.

The session option values take precedence over default values for sessions set in the
$PSSessionOption preference variable and in the session configuration. However,
they do not take
precedence over maximum values, quotas or limits set in the
session configuration.
For a description of the session options that includes the default values, see
New-
PSSessionOption . For information about the $PSSessionOption preference variable,
see
about_Preference_Variables. For more information about
session configurations,
see about_Session_Configurations.

Type: PSSessionOption

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ThrottleLimit

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.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-UseSSL

Indicates that this cmdlet uses the SSL protocol to establish a connection to the
remote computer.
By default, SSL is not used.

WS-Management encrypts all PowerShell content transmitted over the network. The
UseSSL
parameter offers 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 that is used for the
command, the
command fails.
Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-VMId

Specifies an array of virtual machine IDs. This cmdlet starts a PowerShell Direct
interactive
session with each of the specified virtual machines. For more information,
see
Virtual Machine automation and management using PowerShell.

Use Get-VM to see the virtual machines that are available on your Hyper-V host.

Type: Guid[]

Aliases: VMGuid

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-VMName

Specifies an array of names of virtual machines. This cmdlet starts a PowerShell


Direct interactive
session with each of the specified virtual machines. For more
information, see
Virtual Machine automation and management using PowerShell.

Use Get-VM to see the virtual machines that are available on your Hyper-V host.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False


Inputs
String

You can pipe a string to this cmdlet.

System.URI

You can pipe a URI to this cmdlet.

PSSession

You can pipe a session object to this cmdlet.

Outputs
PSSession

Notes
Windows PowerShell includes the following aliases for New-PSSession :

nsn

This cmdlet uses the PowerShell remoting infrastructure. To use this cmdlet, the
local
computer and any remote computers must be configured for PowerShell
remoting. For more
information, see about_Remote_Requirements.

To create a PSSession on the local computer, start 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.

Related Links
Connect-PSSession
Disconnect-PSSession
Enter-PSSession
Exit-PSSession
Get-PSSession
Invoke-Command
Receive-PSSession
Remove-PSSession
New-PSSessionConfigurationFile
Reference
Module: Microsoft.PowerShell.Core

Creates a file that defines a session configuration.

Syntax
PowerShell

New-PSSessionConfigurationFile

[-Path] <String>

[-SchemaVersion <Version>]

[-Guid <Guid>]

[-Author <String>]

[-Description <String>]

[-CompanyName <String>]

[-Copyright <String>]

[-SessionType <SessionType>]

[-TranscriptDirectory <String>]

[-RunAsVirtualAccount]

[-RunAsVirtualAccountGroups <String[]>]

[-MountUserDrive]

[-UserDriveMaximumSize <Int64>]

[-GroupManagedServiceAccount <String>]

[-ScriptsToProcess <String[]>]
[-RoleDefinitions <IDictionary>]

[-RequiredGroups <IDictionary>]

[-LanguageMode <PSLanguageMode>]

[-ExecutionPolicy <ExecutionPolicy>]

[-PowerShellVersion <Version>]
[-ModulesToImport <Object[]>]

[-VisibleAliases <String[]>]

[-VisibleCmdlets <Object[]>]

[-VisibleFunctions <Object[]>]
[-VisibleExternalCommands <String[]>]

[-VisibleProviders <String[]>]
[-AliasDefinitions <IDictionary[]>]

[-FunctionDefinitions <IDictionary[]>]

[-VariableDefinitions <Object>]

[-EnvironmentVariables <IDictionary>]

[-TypesToProcess <String[]>]

[-FormatsToProcess <String[]>]
[-AssembliesToLoad <String[]>]
[-Full]

[<CommonParameters>]
Description
The New-PSSessionConfigurationFile cmdlet creates a file of settings that define a
session
configuration and the environment of sessions that are created by using the
session configuration.
To use the file in a session configuration, use the Path parameter
of the
Register-PSSessionConfiguration or Set-PSSessionConfiguration cmdlets.

The session configuration file that New-PSSessionConfigurationFile creates is a human-


readable
text file that contains a hash table of the session configuration properties and
values. The file
has a .pssc filename extension.

All parameters of New-PSSessionConfigurationFile are optional, except for the Path


parameter.
If you omit a parameter, the corresponding key in the session configuration
file is commented-out,
except where noted in the parameter description.

A session configuration, also known as an endpoint, is a collection of settings on the


local
computer that define the environment for PowerShell sessions (PSSessions) that
connect to the
computer. All PSSessions use a session configuration. To specify a
particular session
configuration, use the ConfigurationName parameter of cmdlets that
create a session, such as the
New-PSSession cmdlet.

A session configuration file makes it easy to define a session configuration without


complex scripts
or code assemblies. The settings in the file are used with the optional
startup script and any
assemblies in the session configuration.

For more information about session configurations and session configuration files, see
about_Session_Configurations and
about_Session_Configuration_Files.

This cmdlet was introduced in PowerShell 3.0.

Examples

Example 1: Creating and using a NoLanguage session


This example show how to create and the effects of using a no-language session.

The steps include:

1. Create a new configuration file.


2. Register the configuration.
3. Create a new session that uses the configuration.
4. Run commands in that new session.
To run the commands in this example, start PowerShell by using the Run as
administrator
option. This option is required to run the Register-
PSSessionConfiguration cmdlet.

PowerShell

New-PSSessionConfigurationFile -Path .\NoLanguage.pssc -LanguageMode


NoLanguage

Register-PSSessionConfiguration -Path .\NoLanguage.pssc -Name NoLanguage -


Force

$NoLanguageSession = New-PSSession -ComputerName Srv01 -ConfigurationName


NoLanguage

Invoke-Command -Session $NoLanguageSession -ScriptBlock {

if ((Get-Date) -lt '1January2099') {'Before'} else {'After'}

The syntax is not supported by this runspace. This might be because it is in


no-language mode.

+ CategoryInfo : ParserError: (if ((Get-Date) ...') {'Before'}


:String) [], ParseException

+ FullyQualifiedErrorId : ScriptsNotAllowed

+ PSComputerName : localhost

In this example, the Invoke-Command fails because the LanguageMode is set to


NoLanguage.

Example 2: Creating and using a RestrictedLanguage


session
This example show how to create and the effects of using a no-language session.

The steps include:

1. Create a new configuration file.


2. Register the configuration.
3. Create a new session that uses the configuration.
4. Run commands in that new session.

To run the commands in this example, start PowerShell by using the Run as
administrator
option. This option is required to run the Register-
PSSessionConfiguration cmdlet.

PowerShell

New-PSSessionConfigurationFile -Path .\NoLanguage.pssc -LanguageMode


RestrictedLanguage

Register-PSSessionConfiguration -Path .\NoLanguage.pssc -Name


RestrictedLanguage -Force

$RestrictedSession = New-PSSession -ComputerName Srv01 -ConfigurationName


RestrictedLanguage

Invoke-Command -Session $RestrictedSession -ScriptBlock {

if ((Get-Date) -lt '1January2099') {'Before'} else {'After'}

Before

In this example, the Invoke-Command succeeds because the LanguageMode is set to


RestrictedLanguage.

Example 3: Changing a Session Configuration File


This example shows how to change the session configuration file that is used in an
existing session
named "ITTasks". Previously, these sessions had only the core modules
and an internal ITTasks
module. The administrator wants to add the PSScheduledJob
module to sessions created by using
the ITTasks session configuration.

PowerShell

New-PSSessionConfigurationFile -Path .\New-ITTasks.pssc -ModulesToImport


Microsoft*, ITTasks, PSScheduledJob

Set-PSSessionConfiguration -Name ITTasks -Path .\New-ITTasks.pssc

The New-PSSessionConfigurationFile cmdlet to create a session configuration file that


imports the
required modules. The Set-PSSessionConfiguration cmdlet replaces the
current configuration file
with the new one. This new configuration only affects new
sessions created after the change.
Existing "ITTasks" sessions are not affected.

Example 4: Editing a Session Configuration File


This example shows how to change a session configuration by editing the active session
configuration
copy of the configuration file. To modify the session configuration copy of
the configuration file,
you must have full control access to the file. This may require you
to change the permissions on the
file.

In this scenario, we want to add a new alias for the Select-String cmdlet by editing the
active
configuration file.

The example code below performs the following steps to make this change:

1. Get the configuration file path for the ITConfig session.


2. The user edits the configuration file using Notepad.exe to change the
AliasDefinitions
value as follows: AliasDefinitions =
@(@{Name='slst';Value='Select-String'}) .

3. Test the updated configuration file.

PowerShell

$ITConfig = Get-PSSessionConfiguration -Name ITConfig

notepad.exe $ITConfig.ConfigFilePath

Test-PSSessionConfigurationFile -Path $ITConfig.ConfigFilePath

True

Use the Verbose parameter with Test-PSSessionConfigurationFile to display any errors


that are
detected. The cmdlet returns $True if no errors are detected in the file.

Example 5: Create a sample configuration file


This example shows a New-PSSessionConfigurationFile command that uses all the
cmdlet parameters.
It is included to show the correct input format for each parameter.

The resulting SampleFile.pssc is displayed in the output.

PowerShell

$configSettings = @{

Path = '.\SampleFile.pssc'

SchemaVersion = '1.0.0.0'

Author = 'User01'

Copyright = '(c) Fabrikam Corporation. All rights reserved.'

CompanyName = 'Fabrikam Corporation'

Description = 'This is a sample file.'

ExecutionPolicy = 'AllSigned'

PowerShellVersion = '3.0'

LanguageMode = 'FullLanguage'

SessionType = 'Default'

EnvironmentVariables = @{TESTSHARE='\\Test2\Test'}

ModulesToImport = @{ModuleName='PSScheduledJob';
ModuleVersion='1.0.0.0'; GUID='50cdb55f-5ab7-489f-9e94-
4ec21ff51e59'},'PSDiagnostics'

AssembliesToLoad = 'System.Web.Services','FSharp.Compiler.CodeDom.dll'

TypesToProcess = 'Types1.ps1xml','Types2.ps1xml'

FormatsToProcess = 'CustomFormats.ps1xml'

ScriptsToProcess = 'Get-Inputs.ps1'

AliasDefinitions = @{Name='hlp';Value='Get-Help';Description='Gets
help.';Options='AllScope'},

@{Name='Update';Value='Update-Help';Description='Updates
help';Options='ReadOnly'}

FunctionDefinitions = @{Name='Get-Function';ScriptBlock={Get-Command -
CommandType Function};Options='ReadOnly'}

VariableDefinitions =
@{Name='WarningPreference';Value='SilentlyContinue'}

VisibleAliases = 'c*','g*','i*','s*'

VisibleCmdlets = 'Get*'

VisibleFunctions = 'Get*'

VisibleProviders = 'FileSystem','Function','Variable'

RunAsVirtualAccount = $true

RunAsVirtualAccountGroups = 'Backup Operators'

New-PSSessionConfigurationFile @configSettings

Get-Content SampleFile.pssc

@{

# Version number of the schema used for this document

SchemaVersion = '1.0.0.0'

# ID used to uniquely identify this document

GUID = '1caeff7f-27ca-4360-97cf-37846f594235'

# Author of this document

Author = 'User01'

# Description of the functionality provided by these settings

Description = 'This is a sample file.'

# Company associated with this document

CompanyName = 'Fabrikam Corporation'

# Copyright statement for this document

Copyright = '(c) Fabrikam Corporation. All rights reserved.'

# Session type defaults to apply for this session configuration. Can be


'RestrictedRemoteServer' (recommended), 'Empty', or 'Default'

SessionType = 'Default'

# Directory to place session transcripts for this session configuration

# TranscriptDirectory = 'C:\Transcripts\'

# Whether to run this session configuration as the machine's (virtual)


administrator account

RunAsVirtualAccount = $true

# Groups associated with machine's (virtual) administrator account

RunAsVirtualAccountGroups = 'Backup Operators'

# Scripts to run when applied to a session

ScriptsToProcess = 'Get-Inputs.ps1'

# User roles (security groups), and the role capabilities that should be
applied to them when applied to a session

# RoleDefinitions = @{ 'CONTOSO\SqlAdmins' = @{ RoleCapabilities =


'SqlAdministration' }; 'CONTOSO\SqlManaged' = @{ RoleCapabilityFiles =
'C:\RoleCapability\SqlManaged.psrc' }; 'CONTOSO\ServerMonitors' = @{
VisibleCmdlets = 'Get-Process' } }

# Language mode to apply when applied to a session. Can be 'NoLanguage'


(recommended), 'RestrictedLanguage', 'ConstrainedLanguage', or
'FullLanguage'

LanguageMode = 'FullLanguage'

# Execution policy to apply when applied to a session

ExecutionPolicy = 'AllSigned'

# Version of the PowerShell engine to use when applied to a session

PowerShellVersion = '3.0'

# Modules to import when applied to a session

ModulesToImport = @{

'GUID' = '50cdb55f-5ab7-489f-9e94-4ec21ff51e59'

'ModuleName' = 'PSScheduledJob'

'ModuleVersion' = '1.0.0.0' }, 'PSDiagnostics'

# Aliases to make visible when applied to a session

VisibleAliases = 'c*', 'g*', 'i*', 's*'

# Cmdlets to make visible when applied to a session

VisibleCmdlets = 'Get*'

# Functions to make visible when applied to a session

VisibleFunctions = 'Get*'

# Providers to make visible when applied to a session

VisibleProviders = 'FileSystem', 'Function', 'Variable'

# Aliases to be defined when applied to a session

AliasDefinitions = @{

'Description' = 'Gets help.'

'Name' = 'hlp'

'Options' = 'AllScope'

'Value' = 'Get-Help' }, @{

'Description' = 'Updates help'

'Name' = 'Update'

'Options' = 'ReadOnly'

'Value' = 'Update-Help' }

# Functions to define when applied to a session

FunctionDefinitions = @{

'Name' = 'Get-Function'

'Options' = 'ReadOnly'

'ScriptBlock' = {Get-Command -CommandType Function} }

# Variables to define when applied to a session

VariableDefinitions = @{

'Name' = 'WarningPreference'

'Value' = 'SilentlyContinue' }

# Environment variables to define when applied to a session

EnvironmentVariables = @{

'TESTSHARE' = '\\Test2\Test' }

# Type files (.ps1xml) to load when applied to a session

TypesToProcess = 'Types1.ps1xml', 'Types2.ps1xml'

# Format files (.ps1xml) to load when applied to a session

FormatsToProcess = 'CustomFormats.ps1xml'

# Assemblies to load when applied to a session

AssembliesToLoad = 'System.Web.Services', 'FSharp.Compiler.CodeDom.dll'

Parameters
-AliasDefinitions

Adds the specified aliases to sessions that use the session configuration. Enter a hash
table with
the following keys:

Name - Name of the alias. This key is required.


Value - The command that the alias represents. This key is required.
Description - A text string that describes the alias. This key is optional.
Options - Alias options. This key is optional. The default value is None. The
acceptable
values for this parameter are: None, ReadOnly, Constant, Private, or
AllScope.

For example: @{Name='hlp';Value='Get-Help';Description='Gets


help';Options='ReadOnly'}

Type: IDictionary[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-AssembliesToLoad

Specifies the assemblies to load into the sessions that use the session configuration.

Type: String[]
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Author

Specifies the author of the session configuration or the configuration file. The default
is the
current user. The value of this parameter is visible in the session configuration
file, but it is
not a property of the session configuration object.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-CompanyName

Specifies the company that created the session configuration or the configuration
file. The default
value is Unknown. The value of this parameter is visible in the
session configuration file, but
it is not a property of the session configuration object.

Type: String

Position: Named

Default value: Unknown

Accept pipeline input: False

Accept wildcard characters: False

-Copyright

Specifies a copyright the session configuration file. The value of this parameter is
visible in the
session configuration file, but it is not a property of the session
configuration object.
If you omit this parameter, New-PSSessionConfigurationFile generates a copyright
statement by
using the value of the Author parameter.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Description

Specifies a description of the session configuration or the session configuration file.


The value of
this parameter is visible in the session configuration file, but it is not a
property of the session
configuration object.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-EnvironmentVariables

Adds environment variables to the session. Enter a hash table in which the keys are
the environment
variable names and the values are the environment variable values.

For example: EnvironmentVariables=@{TestShare='\\Server01\TestShare'}

Type: IDictionary

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ExecutionPolicy
Specifies the execution policy of sessions that use the session configuration. If you
omit this
parameter, the value of the ExecutionPolicy key in the session
configuration file is
Restricted. For information about execution policies in
PowerShell, see
about_Execution_Policies.

Type: ExecutionPolicy

Accepted values: Unrestricted, RemoteSigned, AllSigned, Restricted, Default,


Bypass, Undefined

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-FormatsToProcess

Specifies the formatting files (.ps1xml) that run in sessions that use the session
configuration.
The value of this parameter must be a full or absolute path of the
formatting files.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Full

Indicates that this operation includes all possible configuration properties in the
session
configuration file.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-FunctionDefinitions

Adds the specified functions to sessions that use the session configuration. Enter a
hash table with
the following keys:

Name - Name of the function. This key is required.


ScriptBlock - Function body. Enter a script block. This key is required.
Options - Function options. This key is optional. The default value is None. The
acceptable
values for this parameter are: None, ReadOnly, Constant, Private, or
AllScope.

For example:
@{Name='Get-PowerShellProcess';ScriptBlock={Get-Process
PowerShell};Options='AllScope'}

Type: IDictionary[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-GroupManagedServiceAccount

Configures sessions using this session configuration to run under the context of the
specified Group
Managed Service Account. The machine where this session
configuration is registered must have
permission to request the gMSA password in
order for sessions to be created successfully. This field
cannot be used with the
RunAsVirtualAccount parameter.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Guid

Specifies a unique identifier for the session configuration file. If you omit this
parameter,
New-PSSessionConfigurationFile generates a GUID for the file. To create a
new GUID in PowerShell,
type New-Guid .

Type: Guid

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-LanguageMode

Determines which elements of the PowerShell language are permitted in sessions


that use this session
configuration. You can use this parameter to restrict the
commands that particular users can run on
the computer.

The acceptable values for this parameter are:

FullLanguage - All language elements are permitted.


ConstrainedLanguage - Commands that contain scripts to be evaluated are not
allowed. The
ConstrainedLanguage mode restricts user access to Microsoft
.NET Framework types, objects, or
methods.
NoLanguage - Users may run cmdlets and functions, but are not permitted to
use any language
elements, such as script blocks, variables, or operators.
RestrictedLanguage - Users may run cmdlets and functions, but are not
permitted to use script
blocks or variables except for the following permitted
variables: $PSCulture , $PSUICulture ,
$True , $False , and $Null . Users may use
only the basic comparison operators ( -eq , -gt ,
-lt ). Assignment statements,
property references, and method calls are not permitted.

The default value of the LanguageMode parameter depends on the value of the
SessionType
parameter.

Empty - NoLanguage
RestrictedRemoteServer - NoLanguage
Default - FullLanguage

Type: PSLanguageMode

Accepted values: FullLanguage, RestrictedLanguage, NoLanguage,


ConstrainedLanguage

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ModulesToImport

Specifies the modules and snap-ins that are automatically imported into sessions
that use the
session configuration.

By default, only the Microsoft.PowerShell.Core snap-in is imported into remote


sessions, but
unless the cmdlets are excluded, users can use the Import-Module and
Add-PSSnapin cmdlets to add
modules and snap-ins to the session.

Each module or snap-in in the value of this parameter can be represented by a string
or as a hash
table. A module string consists only of the name of the module or snap-
in. A module hash table can
include ModuleName, ModuleVersion, and GUID keys.
Only the ModuleName key is
required.

For example, the following value consists of a string and a hash table. Any
combination of strings
and hash tables, in any order, is valid.

'TroubleshootingPack', @{ModuleName='PSDiagnostics';
ModuleVersion='1.0.0.0';GUID='c61d6278-02a3-4618-ae37-a524d40a7f44'}

The value of the ModulesToImport parameter of the Register-


PSSessionConfiguration cmdlet takes
precedence over the value of the

ModulesToImport key in the session configuration file.

Type: Object[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-MountUserDrive

Configures sessions that use this session configuration to expose the User: PSDrive.
User drives
are unique for each connecting user and allow users to copy data to and
from PowerShell endpoints
even if the File System provider is not exposed. User
drive roots are created under
$env:LOCALAPPDATA\Microsoft\Windows\PowerShell\DriveRoots\ . For each user
connecting to the
endpoint, a folder is created with the name
${env:USERDOMAIN}_${env:USERNAME} . For computers in
workgroups, the value of
$env:USERDOMAIN is the hostname.

Contents in the user drive persist across user sessions and are not automatically
removed. By
default, users can only store up to 50MB of data in the user drive. This
can be customized with the
UserDriveMaximumSize parameter.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Path

Specifies the path and filename of the session configuration file. The file must have a
.pssc file
name extension.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-PowerShellVersion

Specifies the version of the PowerShell engine in sessions that use the session
configuration. The
acceptable values for this parameter are: 2.0 and 3.0. If you omit
this parameter, the
PowerShellVersion key is commented-out and newest version of
PowerShell runs in the session.

The value of the PSVersion parameter of the Register-PSSessionConfiguration


cmdlet takes
precedence over the value of the PowerShellVersion key in the session
configuration file.
Type: Version

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RequiredGroups

Specifies conditional access rules for users connecting to sessions that use this
session
configuration.

Enter a hashtable to compose your list of rules using only 1 key per hashtable, 'And'
or 'Or', and
set the value to an array of security group names or additional
hashtables.

Example requiring connecting users to be members of a single group: @{ And =


'MyRequiredGroup' }

Example requiring users to belong to group A, or both groups B and C, to access the
endpoint:
@{ Or = 'GroupA', @{ And = 'GroupB', 'GroupC' } }

Type: IDictionary

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RoleDefinitions

Specifies the mapping between security groups (or users) and role capabilities. Users
will be
granted access to all role capabilities which apply to their group membership
at the time the
session is created.

Enter a hash table in which the keys are the name of the security group and the
values are hash
tables that contain a list of role capabilities that should be made
available to the security group.

For example:
@{'Contoso\Level 2 Helpdesk Users' = @{ RoleCapabilities =
'Maintenance', 'ADHelpDesk' }}
Type: IDictionary

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RunAsVirtualAccount

Configures sessions using this session configuration to be run as the computer's


(virtual)
administrator account. This field cannot be used with the
GroupManagedServiceAccount parameter.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RunAsVirtualAccountGroups

Specifies the security groups to be associated with the virtual account when a
session that uses the
session configuration is run as a virtual account. If omitted, the
virtual account belongs to Domain
Admins on domain controllers and Administrators
on all other computers.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SchemaVersion

Specifies the version of the session configuration file schema. The default value is
"1.0.0.0".
Type: Version

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ScriptsToProcess

Adds the specified scripts to sessions that use the session configuration. Enter the
path and file
names of the scripts. The value of this parameter must be a full or
absolute path of script file
names.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SessionType

Specifies the type of session that is created by using the session configuration. The
default value
is Default. The acceptable values for this parameter are:

Empty - No modules are added to session by default. Use the parameters of


this cmdlet
to add modules, functions, scripts, and other features to the
session. This option is designed for
you to create custom sessions by adding
selected commands. If you do not add commands to an empty
session, the
session is limited to expressions and might not be usable.
Default - Adds the Microsoft.PowerShell.Core module to the session. This
module includes the
Import-Module cmdlet that users can use to import other
modules unless you explicitly prohibit
this cmdlet.
RestrictedRemoteServer. Includes only the following proxy functions: Exit-
PSSession ,
Get-Command , Get-FormatData , Get-Help , Measure-Object , Out-
Default , and Select-Object .
Use the parameters of this cmdlet to add modules,

functions, scripts, and other features to the


session.

Type: SessionType
Accepted values: Empty, RestrictedRemoteServer, Default

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-TranscriptDirectory

Specifies the directory to place session transcripts for sessions using this session
configuration.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-TypesToProcess

Adds the specified .ps1xml type files to sessions that use the session configuration.
Enter the
type filenames. The value of this parameter must be a full or absolute path
to type filenames.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-UserDriveMaximumSize

Specifies the maximum size for user drives exposed in sessions that use this session
configuration.
When omitted, the default size of each User: drive root is 50MB.

This parameter should be used with MountUserDrive.


Type: Int64

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-VariableDefinitions

Adds the specified variables to sessions that use the session configuration. Enter a
hash table with
the following keys:

Name - Name of the variable. This key is required.


Value - Variable value. This key is required.
Options - Variable options. This key is optional. The default value is None. The
acceptable
values for this parameter are: None, ReadOnly, Constant, Private, or
AllScope.

For example:
@{Name='WarningPreference';Value='SilentlyContinue';Options='AllScope'}

Type: Object

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-VisibleAliases

Limits the aliases in the session to those specified in the value of this parameter, plus
any
aliases that you define in the AliasDefinition parameter. Wildcard characters are
supported. By
default, all aliases that are defined by the PowerShell engine and all
aliases that modules
export are visible in the session.

For example: VisibleAliases='gcm', 'gp'

When any Visible parameter is included in the session configuration file, PowerShell
removes the Import-Module cmdlet and its ipmo alias from the session.

Type: String[]
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-VisibleCmdlets

Limits the cmdlets in the session to those specified in the value of this parameter.
Wildcard
characters and Module Qualified Names are supported.

By default, all cmdlets that modules in the session export are visible in the session.
Use the
SessionType and ModulesToImport parameters to determine which
modules and snap-ins are
imported into the session. If no modules in
ModulesToImport expose the cmdlet, the appropriate
module will attempt to be
autoloaded.

When any Visible parameter is included in the session configuration file, PowerShell
removes the Import-Module cmdlet and its ipmo alias from the session.

Type: Object[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-VisibleExternalCommands

Limits the external binaries, scripts, and commands that can be executed in the
session to those
specified in the value of this parameter. Wildcard characters are
supported.

By default, no external commands are visible in the session.

When any Visible parameter is included in the session configuration file, PowerShell,
removes the Import-Module cmdlet and its ipmo alias from the session.

Type: String[]

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-VisibleFunctions

Limits the functions in the session to those specified in the value of this parameter,
plus any
functions that you define in the FunctionDefinition parameter. Wildcard
characters are
supported.

By default, all functions that modules in the session export are visible in the session.
Use the
SessionType and ModulesToImport parameters to determine which
modules and snap-ins are
imported into the session.

When any Visible parameter is included in the session configuration file, PowerShell
removes the Import-Module cmdlet and its ipmo alias from the session.

Type: Object[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-VisibleProviders

Limits the PowerShell providers in the session to those specified in the value of this
parameter.
Wildcard characters are supported.

By default, all providers that modules in the session export are visible in the session.
Use the
SessionType and ModulesToImport parameters to determine which
modules are imported into the
session.

When any Visible parameter is included in the session configuration file, PowerShell
removes the Import-Module cmdlet and its ipmo alias from the session.

Type: String[]

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: True

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
Parameters, such as VisibleCmdlets and VisibleProviders, do not import items into
the
session. Instead, they select from among the items imported into the session.
For example, if the
value of the VisibleProviders parameter is the Certificate
provider, but the
ModulesToImport parameter does not specify the
Microsoft.PowerShell.Security module that
contains the Certificate provider, the
Certificate provider is not visible in the session.

New-PSSessionConfigurationFile creates a session configuration file that has a

.pssc file name


extension in the path that you specify in the Path parameter. When
you use the session
configuration file to create a session configuration, the
Register-PSSessionConfiguration cmdlet
copies the configuration file and saves an
active copy of the file in the SessionConfig
subdirectory of the $PSHOME directory.

The ConfigFilePath property of the session configuration contains the fully


qualified path of
the active session configuration file. You can modify the active
configuration file in the
$PSHOME directory at any time using any text editor. The
changes that you make affect all new
sessions that use the session configuration,
but not existing sessions.

Before using an edited session configuration file, use the Test-


PSSessionConfigurationFile
cmdlet to verify that the configuration file entries are
valid.
Related Links
Disable-PSSessionConfiguration
Enable-PSSessionConfiguration
Get-PSSessionConfiguration
Register-PSSessionConfiguration
Set-PSSessionConfiguration
Test-PSSessionConfigurationFile
Unregister-PSSessionConfiguration
WSMan Provider
about_Session_Configurations
about_Session_Configuration_Files
New-PSSessionOption
Reference
Module: Microsoft.PowerShell.Core

Creates an object that contains advanced options for a PSSession.

Syntax
PowerShell

New-PSSessionOption

[-MaximumRedirection <Int32>]

[-NoCompression]

[-NoMachineProfile]

[-Culture <CultureInfo>]

[-UICulture <CultureInfo>]

[-MaximumReceivedDataSizePerCommand <Int32>]

[-MaximumReceivedObjectSize <Int32>]

[-OutputBufferingMode <OutputBufferingMode>]

[-MaxConnectionRetryCount <Int32>]

[-ApplicationArguments <PSPrimitiveDictionary>]

[-OpenTimeout <Int32>]

[-CancelTimeout <Int32>]

[-IdleTimeout <Int32>]

[-ProxyAccessType <ProxyAccessType>]

[-ProxyAuthentication <AuthenticationMechanism>]

[-ProxyCredential <PSCredential>]

[-SkipCACheck]

[-SkipCNCheck]

[-SkipRevocationCheck]

[-OperationTimeout <Int32>]

[-NoEncryption]

[-UseUTF16]

[-IncludePortInSPN]

[<CommonParameters>]

Description
The New-PSSessionOption cmdlet creates an object that contains advanced options for a
user-managed session (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 every property can be edited, you can use the
resulting object as
a template and create standard option objects for your enterprise.

You can also save a SessionOption object in the $PSSessionOption preference variable.
The
values of this variable establish new default values for the session options. They are
effective
when no session options are set for the session and they take precedence over
options set in the
session configuration, but you can override them by specifying
session options or a
SessionOption object in a cmdlet that creates a session. For more
information about the
$PSSessionOption preference variable, see
about_Preference_Variables.

When you use a SessionOption object in a cmdlet that creates a session, the session
option
values take precedence over default values for sessions set in the
$PSSessionOption preference
variable and in the session configuration. However, they

do not take precedence over maximum values,


quotas or limits set in the session
configuration. For more information about session
configurations, see
about_Session_Configurations.

Examples

Example 1: Create a default session option


This command creates a SessionOption object with the default values.

PowerShell

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

Example 2: Configure a session by using a session option


object
This example shows how to use a SessionOption object to configure a session.

PowerShell

$pso = New-PSSessionOption -Culture "fr-fr" -MaximumReceivedObjectSize 10MB

New-PSSession -ComputerName Server01 -SessionOption $pso

The first command creates a new SessionOption object and saves it in the value of the
$pso
variable. The second command uses the New-PSSession cmdlet to create a session
on the Server01
remote computer. The command uses the SessionOption object in the
value of the $pso variable
as the value of the SessionOption parameter of the
command.

Example 3: Start an interactive session


This command uses the Enter-PSSession cmdlet to start an interactive session with the
Server01
computer.

PowerShell

Enter-PSSession -ComputerName Server01 -SessionOption (New-PSSessionOption -


NoEncryption -NoCompression)

The value of the SessionOption parameter is a New-PSSessionOption command that has


the
NoEncryption and NoCompression parameters.

The New-PSSessionOption command is enclosed in parentheses to make sure that it runs


before the
Enter-PSSession command.

Example 4: Modify a session option object


This example demonstrates that you can modify the SessionOption object. All
properties have
read/write values.
PowerShell

$a = New-PSSessionOption

$a.OpenTimeout

Days : 0

Hours : 0

Minutes : 3

Seconds : 0

Milliseconds : 0

Ticks : 1800000000

TotalDays : 0.00208333333333333

TotalHours : 0.05

TotalMinutes : 3

TotalSeconds : 180

TotalMilliseconds : 180000

$a.UICulture = (Get-UICulture)

$a.OpenTimeout = (New-Timespan -Minutes 4)

$a.MaximumConnectionRedirectionCount = 1

$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

Use this method to create a standard session object for your enterprise, and then create
customized
versions of it for particular uses.

Example 5: Create a preference variable


This command creates a $PSSessionOption preference variable.

PowerShell
$PSSessionOption = New-PSSessionOption -OpenTimeOut 120000

When the $PSSessionOption preference variable is set in the session, it establishes


default values
for options in the sessions that are created with the New-PSSession ,
Enter-PSSession , and
Invoke-Command cmdlets.

To make the $PSSessionOption variable available in all sessions, add it to your


PowerShell session
and to your PowerShell profile.

For more information about the $PSSessionOption preference variable, see


about_Preference_Variables.
For more information about profiles, see about_Profiles.

Example 6: Fulfill the requirements for a remote session


configuration
This example shows how to use a SessionOption object to fulfill the requirements for a
remote
session configuration.

PowerShell

$skipCN = New-PSSessionOption -SkipCNCheck

New-PSSession -ComputerName 171.09.21.207 -UseSSL -Credential


Domain01\User01 -SessionOption $SkipCN

The first command uses the New-PSSessionOption cmdlet to create a SessionOption


object that
has 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 session 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 that is used for
Secure Sockets Layer
(SSL). As a result, the SkipCNCheck option is required.

Example 7: Make arguments available to a remote session


This example shows how to use the ApplicationArguments parameter of the New-
PSSessionOption
cmdlet to make additional data available to the remote session.
PowerShell

$team = @{Team="IT"; Use="Testing"}

$TeamOption = New-PSSessionOption -ApplicationArguments $team

$s = New-PSSession -ComputerName Server01 -SessionOption $TeamOption

Invoke-Command -Session $s {$PSSenderInfo.ApplicationArguments}

Name Value

---- -----

Team IT

Use Testing

PSVersionTable {CLRVersion, BuildVersion, PSVersion,


WSManStackVersion...}

Invoke-Command -Session $s {

if ($PSSenderInfo.ApplicationArguments.Use -ne "Testing") {

.\logFiles.ps1

else {

"Just testing."

Just testing.

The first command creates a hash table with two keys, Team and Use. The command
saves the
hash table in the $team variable. For more information about hash tables, see
about_Hash_Tables.

Next, the New-PSSessionOption cmdlet, using the ApplicationArguments parameter,


creates a
SessionOption object saved in the $team variable. When New-PSSessionOption
creates the
session option object, it automatically converts the hash table in the value of
the
ApplicationArguments parameter to a PrimitiveDictionary so the data can be
reliably
transmitted to the remote session.

The New-PSSession cmdlet starts a session on the Server01 computer. It uses the
SessionOption
parameter to include the options in the $teamOption variable.

The Invoke-Command cmdlet demonstrates that the data in the $team variable is available
to
commands in the remote session. The data appears in the ApplicationArguments
property of the
$PSSenderInfo automatic variable.

The final Invoke-Command shows how the data might be used.

Parameters
-ApplicationArguments

Specifies a PrimitiveDictionary that is sent to the remote session. Commands and


scripts in the
remote session, including startup scripts in the session configuration,
can find this dictionary in
the ApplicationArguments property of the $PSSenderInfo
automatic variable. You can use this
parameter to send data to the remote session.

For more information, see about_Hash_Tables,


about_Session_Configurations, and
about_Automatic_Variables.

Type: PSPrimitiveDictionary

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-CancelTimeout

Determines how long PowerShell waits for a cancel operation ( CTRL + C ) to finish
before ending it. Enter a value in milliseconds.

The default value is 60000 (one minute). A value of 0 (zero) means no time-out; the
command
continues indefinitely.

Type: Int32

Aliases: CancelTimeoutMSec

Position: Named

Default value: 60000

Accept pipeline input: False

Accept wildcard characters: False

-Culture

Specifies the culture to use for the session. Enter a culture name in
<languagecode2>-
<country/regioncode2> format (like ja-JP ), a variable that contains a
CultureInfo

object, or a command that gets a CultureInfo object.


The default value is $Null , and the culture that is set in the operating system is used
in the
session.

Type: CultureInfo

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-IdleTimeout

Determines how long the session stays open if the remote computer does not
receive any communication
from the local computer. This includes the heartbeat
signal. When the interval expires, the session
closes.

The idle time-out value is of significant importance if you intend to disconnect and
reconnect to a
session. You can reconnect only if the session has not timed out.

Enter a value in milliseconds. The minimum value is 60000 (1 minute). The maximum
is the value of
the MaxIdleTimeoutms property of the session configuration. The
default value, -1 , does not
set an idle time-out.

The session uses the idle time-out that is set in the session options, if any. If none is
set
( -1 ), the session uses the value of the IdleTimeoutMs property of the session
configuration or
the WSMan shell time-out value ( WSMan:\
<ComputerName>\Shell\IdleTimeout ), whichever is shortest.

If the idle time-out set in the session options exceeds the value of the
MaxIdleTimeoutMs
property of the session configuration, the command to create a
session fails.

The IdleTimeoutMs value of the default Microsoft.PowerShell session configuration


is
7200000 milliseconds (2 hours). Its MaxIdleTimeoutMs value is 2147483647
milliseconds (>24
days). The default value of the WSMan shell idle time-out
( WSMan:\
<ComputerName>\Shell\IdleTimeout ) is 7200000 milliseconds (2 hours).

The idle time-out value of a session can also be changed when disconnecting from a
session or
reconnecting to a session. For more information, see Disconnect-
PSSession and Connect-PSSession .
In Windows PowerShell 2.0, the default value of the IdleTimeout parameter is 240000
(4
minutes).

Type: Int32

Aliases: IdleTimeoutMSec

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-IncludePortInSPN

Includes the port number in the Service Principal Name (SPN) used for Kerberos
authentication, for
example, HTTP://<ComputerName>:5985 . This option allows a client
that uses a non-default SPN to
authenticate against a remote computer that uses
Kerberos authentication.

The option is designed for enterprises where multiple services that support Kerberos
authentication
are running under different user accounts. For example, an IIS
application that allows for Kerberos
authentication can require the default SPN to be
registered to a user account that differs from the
computer account. In such cases,
PowerShell remoting cannot use Kerberos to authenticate because it
requires an SPN
that is registered to the computer account. To resolve this problem, administrators
can create different SPNs, such as by using Setspn.exe , that are registered to
different user
accounts and can distinguish between them by including the port
number in the SPN.

For more information, see


Setspn Overview.

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-MaxConnectionRetryCount

Specifies the number of times that PowerShell attempts to make a connection to a


target machine if
the current attempt fails due to network issues. The default value is
5.

This parameter was added for PowerShell version 5.0.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-MaximumReceivedDataSizePerCommand

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.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-MaximumReceivedObjectSize

Specifies the maximum size of an object that the local computer can receive from the
remote
computer. This option is designed to protect the resources on the client
computer. Enter a value in
bytes.

In Windows PowerShell 2.0, if you omit this parameter, there is no object size limit.
Beginning in
Windows PowerShell 3.0, if you omit this parameter, the default value is
209715200 bytes (or
200MB ).

Type: Int32
Position: Named

Default value: 209715200

Accept pipeline input: False

Accept wildcard characters: False

-MaximumRedirection

Determines how many times 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 session only when the AllowRedirection parameter is used
in the
command that creates the session.

Type: Int32

Position: Named

Default value: 5

Accept pipeline input: False

Accept wildcard characters: False

-NoCompression

Turns off packet compression in the session. Compression uses more processor
cycles, but it makes
transmission faster.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-NoEncryption

Turns off data encryption.

Type: SwitchParameter
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-NoMachineProfile

Prevents loading the user's Windows user profile. As a result, the session might be
created faster,
but user-specific registry settings, items such as environment
variables, and certificates are not
available in the session.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-OpenTimeout

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.

Type: Int32

Aliases: OpenTimeoutMSec

Position: Named

Default value: 180000 (3 minutes)

Accept pipeline input: False

Accept wildcard characters: False

-OperationTimeout
Determines the maximum time WinRM waits for positive connection tests from a live
connection
before initiating a connection time-out. For more information on WinRM,
see the
Windows Remote Management Documentation.

OperationTimeout does not impose a time limit on commands or processes running


in a remote
session and does not affect other remoting protocols like SSH.

The default value is 180000 (3 minutes). A value of 0 (zero) means no time-out.

Type: Int32

Aliases: OperationTimeoutMSec

Position: Named

Default value: 180000 (3 minutes)

Accept pipeline input: False

Accept wildcard characters: False

-OutputBufferingMode

Determines how command output is managed in disconnected sessions when the


output buffer becomes
full.

If the output buffering mode is not set in the session or in the session configuration,
the default
value is Block . Users can also change the output buffering mode when
disconnecting the session.

If you omit this parameter, the value of the OutputBufferingMode of the


SessionOption object
is None . A value of Block or Drop overrides the output
buffering mode transport option set in
the session configuration. The acceptable
values for this parameter are:

Block . When the output buffer is full, execution is suspended until the buffer is
clear.
Drop . When the output buffer is full, execution continues. As new output is
saved, the oldest
output is discarded.
None . No output buffering mode is specified.

For more information about the output buffering mode transport option, see New-
PSTransportOption .

This parameter was introduced in Windows PowerShell 3.0.


Type: OutputBufferingMode

Accepted values: None, Drop, Block

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ProxyAccessType

Determines which mechanism is used to resolve the hostname. The acceptable


values for this parameter
are:

IEConfig

WinHttpConfig

AutoDetect
NoProxyServer

None

The default value is None .

For information about the values of this parameter, see


ProxyAccessType
Enumeration.

Type: ProxyAccessType

Accepted values: None, IEConfig, WinHttpConfig, AutoDetect, NoProxyServer

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ProxyAuthentication

Specifies the authentication method that is used for proxy resolution. The acceptable
values for
this parameter are:

Basic

Digest
Negotiate

The default value is Negotiate .

For more information about the values of this parameter, see


AuthenticationMechanism Enumeration.

Type: AuthenticationMechanism

Accepted values: Default, Basic, Negotiate, NegotiateWithImplicitCredential,


Credssp, Digest, Kerberos

Position: Named

Default value: Negotiate

Accept pipeline input: False

Accept wildcard characters: False

-ProxyCredential

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 a Get-Credential
command. If this option is not set, no credentials are specified.

Type: PSCredential

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SkipCACheck

Specifies that when it connects over HTTPS, the client does not validate that the
server certificate
is signed by a trusted certification 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 when the remote
computer is listed as a trusted host in a
WinRM configuration.

Type: SwitchParameter
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 have 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.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-SkipRevocationCheck

Does not validate the revocation status of the server certificate.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-UICulture

Specifies the UI culture to use for the session.

Valid values include:

A culture name in <languagecode2>-<country/regioncode2> format, such as ja-


JP
A variable that contains a CultureInfo object
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
session is created.

Type: CultureInfo

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-UseUTF16

Indicates that this cmdlet encodes the request in UTF16 format instead of UTF8
format.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

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

The properties of a session configuration object vary with the options set for the session
configuration and the values of those options. Also, session configurations that use a
session
configuration file have additional properties.

Related Links
Enter-PSSession
Invoke-Command
New-PSSession
New-PSTransportOption
Reference
Module: Microsoft.PowerShell.Core

Creates an object that contains advanced options for a session configuration.

Syntax
PowerShell

New-PSTransportOption

[-MaxIdleTimeoutSec <Int32>]

[-ProcessIdleTimeoutSec <Int32>]

[-MaxSessions <Int32>]

[-MaxConcurrentCommandsPerSession <Int32>]

[-MaxSessionsPerUser <Int32>]

[-MaxMemoryPerSessionMB <Int32>]

[-MaxProcessesPerSession <Int32>]

[-MaxConcurrentUsers <Int32>]

[-IdleTimeoutSec <Int32>]

[-OutputBufferingMode <OutputBufferingMode>]

[<CommonParameters>]

Description
The New-PSTransportOption cmdlet creates an object that contains transport options for
session
configurations. You can use the object as the value of the TransportOption
parameter of cmdlets
that create or change a session configuration, such as the
Register-PSSessionConfiguration and
Set-PSSessionConfiguration cmdlets.

You can also change the transport option settings by editing the values of the session
configuration
properties in the WSMan: drive. For more information, see WSMan
Provider.

The session configuration options represent the session values set on the server-side, or
receiving
end of a remote connection. The client-side, or sending end of the connection,
can set session
option values when the session is created, or when the client disconnects
from or reconnects to the
session. Unless stated otherwise, when the setting values
conflict, the client-side values take
precedence. However, the client-side values cannot
violate maximum values and quotas set in the
session configuration.
Without parameters, New-PSTransportOption generates a transport option object that
has null values
for all of the options. If you omit a parameter, the object has a null value
for the property that
the parameter represents. A null value does not affect the session
configuration.

For more information about session options, see New-PSSessionOption . For more
information about
session configurations, see about_Session_Configurations.

This cmdlet was introduced in Windows PowerShell 3.0.

Examples

Example 1: Generate a default transport option


PowerShell

New-PSTransportOption

ProcessIdleTimeoutSec :
MaxIdleTimeoutSec :
MaxSessions :
MaxConcurrentCommandsPerSession :
MaxSessionsPerUser :
MaxMemoryPerSessionMB :
MaxProcessesPerSession :
MaxConcurrentUsers :
IdleTimeoutSec :
OutputBufferingMode :

This command runs the New-PSTransportOption without parameters. The output shows
that the cmdlet
generates a transport option object that has null values for all
properties.

Example 2: Get session configuration options


This example shows how to use a transport options object to set session configuration
options.

PowerShell

$t = New-PSTransportOption -MaxSessions 40

Register-PSSessionConfiguration -Name ITTasks -TransportOption $t

Get-PSSessionConfiguration -Name ITTasks | Format-List -Property *

Architecture : 64

Filename : %windir%\system32\pwrshplugin.dll

ResourceUri :
http://schemas.microsoft.com/powershell/ITTasks

MaxConcurrentCommandsPerShell : 1000

UseSharedProcess : false

ProcessIdleTimeoutSec : 0
xmlns :
http://schemas.microsoft.com/wbem/wsman/1/config/PluginConfiguration

MaxConcurrentUsers : 5
lang : en-US

SupportsOptions : true

ExactMatch : true

RunAsUser :

IdleTimeoutms : 7200000

PSVersion : 3.0

OutputBufferingMode : Block

AutoRestart : false

MaxShells : 40

MaxMemoryPerShellMB : 1024

MaxIdleTimeoutms : 43200000

SDKVersion : 2
Name : ITTasks

XmlRenderingType : text

Capability : {Shell}

RunAsPassword :

MaxProcessesPerShell : 15

Enabled : True

MaxShellsPerUser : 25

Permission :

The first command uses the New-PSTransportOption cmdlet to create a transport options
object,
which it saves in the $t variable. The command uses the MaxSessions parameter
to increase the
maximum number of sessions to 40.

The second command uses the Register-PSSessionConfiguration cmdlet create the


ITTasks session
configuration. The command uses the TransportOption parameter to
specify the transport options
object in the $t variable.

The third command uses the Get-PSSessionConfiguration cmdlet to get the ITTasks
session
configurations and the Format-List cmdlet to display all of the properties of the
session
configuration object in a list. The output shows that the value of the MaxShells
property of the
session configuration is 40.

Example 3: Setting a transport option


This command shows the effect of setting a transport option in a session configuration
on the sessions that use the session configuration.
PowerShell

$t = New-PSTransportOption -IdleTimeoutSec 3600

Set-PSSessionConfiguration -Name ITTasks -TransportOption $t

$s = New-PSSession -Name MyITTasks -ConfigurationName ITTasks

$s | Format-List -Property *

State : Opened

IdleTimeout : 3600000

OutputBufferingMode : Block

ComputerName : localhost

ConfigurationName : ITTasks

InstanceId : 4110c3f5-68ea-40fa-9bbf-04a433dbb02d

Id : 1

Name : MyITTasks

Availability : Available

ApplicationPrivateData : {PSVersionTable}

Runspace : System.Management.Automation.RemoteRunspace

The first command uses the New-PSTransportOption cmdlet to create a transport option
object. The
command uses the IdleTimeoutSec parameter to set the IdleTimeoutSec
property value of the
object to one hour (3600 seconds). The command saves the
transport objects object in the $t
variable.

The second command uses the Set-PSSessionConfiguration cmdlet to change the


transport options of
the ITTasks session configuration. The command uses the
TransportOption parameter to specify the
transport options object in the $t variable.

The third command uses the New-PSSession cmdlet to create the MyITTasks session on
the local
computer. The command uses the ConfigurationName property to specify the
ITTasks session
configuration. The command saves the session in the $s variable.Notice
that the command does not use
the SessionOption parameter of New-PSSession to set a
custom idle time-out for the session. If
it did, the idle time-out value set in the session
option would take precedence over the idle
time-out set in the session configuration.

The fourth command uses the Format-List cmdlet to display all properties of the
session in the
$s variable in a list. The output shows that the session has an idle time-
out of one hour (360,000
milliseconds).

Parameters
-IdleTimeoutSec

Determines how long each session stays open if the remote computer does not
receive any
communication from the local computer. This includes the heartbeat
signal. When the interval
expires, the session closes.

The idle time-out value is of significant importance when the user intends to
disconnect and
reconnect to a session. The user can reconnect only if the session has
not timed out.

The IdleTimeoutSec parameter corresponds to the IdleTimeoutMs property of a


session
configuration.

Enter a value in seconds. The default value is 7200 (2 hours). The minimum value is
60 (1 minute).
The maximum is the value of the IdleTimeout property of Shell
objects in the WSMan configuration
( WSMan:\\\<ComputerName\>\Shell\IdleTimeout ).
The default value is 7200000 milliseconds (2 hours).

If an idle time-out value is set in the session options and in the session configuration,
value set
in the session options takes precedence, but it cannot exceed the value of
the MaxIdleTimeoutMs
property of the session configuration. To set the value of the
MaxIdleTimeoutMs property, use
the MaxIdleTimeoutSec parameter.

Type: Nullable<T>[Int32]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-MaxConcurrentCommandsPerSession

Limits the number of commands that can run at the same time in each session to the
specified value.
The default value is 1000.

The MaxConcurrentCommandsPerSession parameter corresponds to the


MaxConcurrentCommandsPerShell property of a session configuration.

Type: Nullable<T>[Int32]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False


-MaxConcurrentUsers

Limits the number of users who can run commands at the same time in each session
to the specified
value. The default value is 5.

Type: Nullable<T>[Int32]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-MaxIdleTimeoutSec

Limits the idle time-out set for each session to the specified value. The default value
is [Int]::MaxValue
(~25 days).

The idle time-out value is of significant importance when the user intends to
disconnect and
reconnect to a session. The user can reconnect only if the session has
not timed out.

The MaxIdleTimeoutSec parameter corresponds to the MaxIdleTimeoutMs property


of a session
configuration.

Type: Nullable<T>[Int32]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-MaxMemoryPerSessionMB

Limits the memory used by each session to the specified value. Enter a value in
megabytes. The
default value is 1024 megabytes (1 GB).

The MaxMemoryPerSessionMB parameter corresponds to the


MaxMemoryPerShellMB property of a
session configuration.

Type: Nullable<T>[Int32]

Position: Named
Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-MaxProcessesPerSession

Limits the number of processes running in each session to the specified value. The
default value is
15.

The MaxProcessesPerSession parameter corresponds to the MaxProcessesPerShell


property of a
session configuration.

Type: Nullable<T>[Int32]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-MaxSessions

Limits the number of sessions that use the session configuration. The default value is
25.

The MaxSessions parameter corresponds to the MaxShells property of a session


configuration.

Type: Nullable<T>[Int32]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-MaxSessionsPerUser

Limits the number of sessions that use the session configuration and run with the
credentials of a
given user to the specified value. The default value is 25.
When you specify this value, consider that many users might be using the credentials
of a run as
user.

The MaxSessionsPerUser parameter corresponds to the MaxShellsPerUser property


of a session
configuration.

Type: Nullable<T>[Int32]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-OutputBufferingMode

Determines how command output is managed in disconnected sessions when the


output buffer becomes
full. The acceptable values for this parameter are:

Block
When the output buffer is full, execution is suspended until the buffer is

clear.
Drop
When the output buffer is full, execution continues.
As new output is
saved, the oldest output is discarded.
None
No output buffering mode is specified.

The default value of the OutputBufferingMode property of sessions is Block.

Type: Nullable<T>[OutputBufferingMode]

Accepted values: None, Drop, Block

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-ProcessIdleTimeoutSec

Limits the time-out for each host process to the specified value. The default value, 0,
means that
there is no time-out value for the process.
Other session configurations have per-process time-out values. For example, the
Microsoft.PowerShell.Workflow session configuration has a per-process time-out
value of 28800
seconds (8 hours).

Type: Nullable<T>[Int32]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
WSManConfigurationOption

Notes
The properties of a session configuration object vary with the options set for the
session
configuration and the values of those options. Also, session configurations
that use a session
configuration file have additional properties.

Related Links
New-PSSession
New-PSSessionOption
Register-PSSessionConfiguration
Set-PSSessionConfiguration
Out-Default
Reference
Module: Microsoft.PowerShell.Core

Sends the output to the default formatter and to the default output cmdlet.

Syntax
PowerShell

Out-Default

[-Transcript]

[-InputObject <PSObject>]

[<CommonParameters>]

Description
PowerShell automatically adds Out-Default to the end of every pipeline. Out-Default
decides how
to format and output the object stream. If the object stream is a stream of
strings, Out-Default
pipes these directly to Out-Host which calls the appropriate APIs
provided by the host. If the
object stream does not contain strings, Out-Default inspects
the object to determine what to do.
First it looks at the object type and determines
whether there is a registered view for this
object type.

PowerShell defines an XML schema and a mechanism (the Update-FormatData cmdlet)


where anyone can
register views for an object type. You can specify wide, list, table, or
custom
views for any object type. The views specify which properties to display and how
they should be
displayed. If a view is registered, it defines which formatter to use. So if
the registered view is
a table view, Out-Default streams the objects to Format-Table |
Out-Host . Format-Table
transforms the objects into a stream of Formatting records

(driven by the data in the view


definition) and Out-Host transforms the formatting
records into calls on the Host interface.

This cmdlet isn't intended to be used by the end user. Other cmdlets are recommended
for controlling
output like Out-Host or using Format-* cmdlets and the Format.ps1xml
file to control formatting.

Examples
Example 1
While this cmdlet is not intended to be run directly by the end user, it can be.

PowerShell

Get-Process | Select-Object -First 5 | Out-Default

NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName

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

12 2.56 5.20 0.00 7376 0 aesm_service

48 34.32 18.10 26.64 9320 13 AlertusDesktopAlert

24 13.97 12.74 0.77 12656 13 ApplicationFrameHost

8 1.79 4.41 0.00 8180 0 AppVShNotify

9 1.99 5.07 0.19 19320 13 AppVShNotify

No error is thrown when using Out-Default but the output isn't changed if it's not
explicitly
called.

Parameters
-InputObject

Accepts input to the cmdlet.

Type: PSObject

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Transcript

Determines whether the output should be sent to PowerShell's transcription services.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

Related Links
Format-Custom
Format-List
Format-Table
Format-Wide
about_Format.ps1xml
How PowerShell Formatting and Outputting REALLY works
Out-Host
Reference
Module: Microsoft.PowerShell.Core

Sends output to the command line.

Syntax
PowerShell

Out-Host

[-Paging]

[-InputObject <PSObject>]

[<CommonParameters>]

Description
The Out-Host cmdlet sends output to the PowerShell host for display. The host displays
the output
at the command line. Because Out-Host is the default, you don't have to
specify it unless you want
to use its parameters.

Out-Host is automatically appended to every command that is executed. It passes the


output of the
pipeline to the host executing the command. Out-Host ignores ANSI
escape sequences. The escape
sequences are handled by the host. Out-Host passes
ANSI escape sequences to the host without
trying to interpret or change them.

Examples

Example 1: Display output one page at a time


This example displays the system processes one page at a time.

PowerShell

Get-Process | Out-Host -Paging

NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName

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

30 24.12 36.95 15.86 21004 14 ApplicationFrameHost

55 24.33 60.48 10.80 12904 14 BCompare

<SPACE> next page; <CR> next line; Q quit

9 4.71 8.94 0.00 16864 14 explorer

<SPACE> next page; <CR> next line; Q quit

Get-Process gets the system processes and sends the objects down the pipeline. Out-

Host uses the


Paging parameter to display one page of data at a time.

Example 2: Use a variable as input


This example uses objects stored in a variable as the input for Out-Host .

PowerShell

$io = Get-History

Out-Host -InputObject $io

Get-History gets the PowerShell session's history, and stores the objects in the $io
variable.
Out-Host uses the InputObject parameter to specify the $io variable and
displays the
history.

Parameters
-InputObject

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.

Type: PSObject

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Paging

Indicates that Out-Host displays one page of output at a time, and waits for user
input before the
remaining pages are displayed. By default, all the output is
displayed on a single page. The page
size is determined by the characteristics of the
host.
Press the Space bar to display the next page of output or the Enter key to
view the
next line of output. Press Q to quit.

Paging is similar to the more command.

7 Note

The Paging parameter isn't supported by the PowerShell ISE host.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSObject

You can pipe any object to this cmdlet.

Outputs
None

This cmdlet returns no output. It sends objects to the host for display.

Notes
Windows PowerShell includes the following aliases for Out-Host :

oh

The Paging parameter isn't supported by all PowerShell hosts. For example, if you use
the
Paging parameter in the PowerShell ISE, the following error is displayed:
out-
lineoutput : The method or operation is not implemented.

The cmdlets that contain the Out verb, Out- , don't format objects. They render objects
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 don't have parameters for names or file paths. To send data to an
Out- cmdlet,
use the pipeline to send a PowerShell command's output to the cmdlet.

Or, you can store data in a


variable and use the InputObject parameter to pass the data
to the cmdlet.

Out-Host sends data, but it doesn't produce any output objects. If you pipeline the

output of
Out-Host to the Get-Member cmdlet, Get-Member reports that no objects have
been specified.

Related Links
Clear-Host
Out-Default
Out-File
Out-Null
Out-Printer
Out-String
Write-Host
Out-Null
Reference
Module: Microsoft.PowerShell.Core

Hides the output instead of sending it down the pipeline or displaying it.

Syntax
PowerShell

Out-Null

[-InputObject <PSObject>]

[<CommonParameters>]

Description
The Out-Null cmdlet sends its output to NULL, in effect, removing it from the pipeline
and
preventing the output from being displayed on screen. This only affects the
standard output stream.
Other output streams, like the Error stream are not affected.
Exceptions will be displayed. This
makes it easier to test your command for any errors.

Examples

Example 1: Delete output


PowerShell

Get-ChildItem | Out-Null

This command gets items in the current location/directory, but its output is not passed
through the
pipeline nor displayed at the command line. This is useful for hiding output
that you do not need.

Parameters
-InputObject
Specifies the object to be sent to NULL (removed from pipeline). Enter a variable that
contains the
objects, or type a command or expression that gets the objects.

Type: PSObject

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

Inputs
PSObject

You can pipe any object to this cmdlet.

Outputs
None

This cmdlet returns no 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

the
Get-Member cmdlet, Get-Member reports that no objects have been specified.

Related Links
Out-Default
Out-Host
Receive-Job
Reference
Module: Microsoft.PowerShell.Core

Gets the results of the PowerShell background jobs in the current session.

Syntax
PowerShell

Receive-Job

[-Job] <Job[]>

[[-Location] <String[]>]

[-Keep]

[-NoRecurse]

[-Force]

[-Wait]

[-AutoRemoveJob]

[-WriteEvents]

[-WriteJobInResults]

[<CommonParameters>]

PowerShell

Receive-Job

[-Job] <Job[]>

[[-Session] <PSSession[]>]
[-Keep]

[-NoRecurse]

[-Force]

[-Wait]

[-AutoRemoveJob]

[-WriteEvents]

[-WriteJobInResults]

[<CommonParameters>]

PowerShell

Receive-Job

[-Job] <Job[]>

[[-ComputerName] <String[]>]

[-Keep]

[-NoRecurse]

[-Force]

[-Wait]

[-AutoRemoveJob]

[-WriteEvents]

[-WriteJobInResults]

[<CommonParameters>]

PowerShell

Receive-Job

[-Keep]

[-NoRecurse]

[-Force]

[-Wait]

[-AutoRemoveJob]

[-WriteEvents]

[-WriteJobInResults]

[-Name] <String[]>

[<CommonParameters>]

PowerShell

Receive-Job

[-Keep]

[-NoRecurse]

[-Force]

[-Wait]

[-AutoRemoveJob]

[-WriteEvents]

[-WriteJobInResults]

[-InstanceId] <Guid[]>

[<CommonParameters>]

PowerShell

Receive-Job

[-Keep]

[-NoRecurse]

[-Force]

[-Wait]

[-AutoRemoveJob]

[-WriteEvents]

[-WriteJobInResults]

[-Id] <Int32[]>

[<CommonParameters>]

Description
The Receive-Job cmdlet gets the results of PowerShell background jobs, such as those
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 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 lets you continue to work in the session while the
job runs.
For more information about background jobs in PowerShell, see about_Jobs.

The Receive-Job cmdlet 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, run the Receive-Job command again without the Keep parameter, close
the session, or use the Remove-Job cmdlet to delete the job from the session.

Starting in Windows PowerShell 3.0, Receive-Job also gets the results of custom job
types, such as
workflow jobs and instances of scheduled jobs.
To enable Receive-Job to
get the results a custom job type, import the module that supports the
custom job type
into the session before it runs a Receive-Job command, either by using the
Import-
Module cmdlet or by using or getting a cmdlet in the module.
For information about a
particular custom job type, see the documentation of the custom job type
feature.

Examples

Example 1: Get results for a particular job


PowerShell

$job = Start-Job -ScriptBlock {Get-Process}

Receive-Job -Job $job

These commands use the Job parameter of Receive-Job to get the results of a particular
job.

The first command starts a job with Start-Job and stores the 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: Use the Keep parameter


PowerShell

$job = Start-Job -ScriptBlock {Get-Service dhcp, fakeservice}

$job | Receive-Job -Keep

Cannot find any service with service name 'fakeservice'.

+ CategoryInfo : ObjectNotFound: (fakeservice:String) [Get-


Service], ServiceCommandException
+ FullyQualifiedErrorId :
NoServiceFoundForGivenName,Microsoft.PowerShell.Commands.GetServiceCommand

+ PSComputerName : localhost

Status Name DisplayName

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

Running dhcp DHCP Client

$job | Receive-Job -Keep

Cannot find any service with service name 'fakeservice'.

+ CategoryInfo : ObjectNotFound: (fakeservice:String) [Get-


Service], ServiceCommandException
+ FullyQualifiedErrorId :
NoServiceFoundForGivenName,Microsoft.PowerShell.Commands.GetServiceCommand

+ PSComputerName : localhost

Status Name DisplayName

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

Running dhcp DHCP Client

This example stores a job in the $job variable, and pipes the job to the Receive-Job
cmdlet. The
-Keep parameter is also used to allow all aggregated stream data to be
retrieved again
after first view.

Example 3: Get results of several background jobs


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

# Use the Invoke-Command cmdlet with the -AsJob parameter to start a


background job that runs a Get-Service command on three remote computers.

# Store the resulting job object in the $j variable

$j = Invoke-Command -ComputerName Server01, Server02, Server03 -ScriptBlock


{Get-Service} -AsJob

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

# You could also use the -IncludeChildJobs parameter of the Get-Job cmdlet.

$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

# Use the Receive-Job cmdlet to get the results of just the Job3 child job
that ran on the Server02 computer.

# Use the *Keep* parameter to allow you to view the aggregated stream data
more than once.

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

Example 4: Get results of background jobs on multiple


remote computers
PowerShell

# Use the New-PSSession cmdlet to create three user-managed PSSessions on


three servers, and save the sessions in the $s variable.

$s = New-PSSession -ComputerName Server01, Server02, Server03

# Use Invoke-Command run a Start-Job command in each of the PSSessions in


the $s variable.

# The creates a new job with a custom name to each server

# The job outputs the datetime from each server

# Save the job objects in the $j variable.

$j = Invoke-Command -Session $s -ScriptBlock {​


Start-Job -Name $('MyJob-'
+$env:COMPUTERNAME) -ScriptBlock {(Get-Date).ToString()​
}}

# To confirm that these job objects are from the remote machines, run Get-
Job to show no local jobs running.

Get-Job​


# Display the three job objects in $j.

# Note that the Localhost location is not the local computer, but instead
localhost as it relates to the job on each Server.

$j

Id Name State HasMoreData Location Command

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

1 MyJob-Server01 Completed True Localhost (Get-


Date).ToString()

2 MyJob-Server02 Completed True Localhost (Get-


Date).ToString()

3 MyJob-Server03 Completed True Localhost (Get-


Date).ToString()

# Use Invoke-Command to run a Receive-Job command in each of the sessions in


the $s variable and save the results in the $results variable.

# The Receive-Job command must be run in each session because the jobs were
run locally on each server.

$results = Invoke-Command -Session $s -ScriptBlock {​


Receive-Job -Name
$('MyJob-' +$env:COMPUTERNAME)}

3/22/2021 7:41:47 PM

3/22/2021 7:41:47 PM

3/22/2021 9:41:47 PM

This example shows how to get the results of background jobs run on three remote
computers.
Unlike the previous example, using Invoke-Command to run the Start-Job
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.

Example 5: Access child jobs


The -Keep parameter preserves the state of the aggregated streams of a job so that it
can be viewed again. Without this parameter all aggregated stream data is erased when
the job
is received. For more information, see about_Job_Details

7 Note

The aggregated streams include the streams of all child jobs. You can still reach the
individual
streams of data through the job object and child job objects.

PowerShell
Start-Job -Name TestJob -ScriptBlock {dir C:\, Z:\}

# Without the Keep parameter, aggregated child job data is displayed once.

# Then destroyed.

Receive-Job -Name TestJob

Directory: C:\

Mode LastWriteTime Length Name

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

d-r--- 1/24/2019 7:11 AM Program Files

d-r--- 2/13/2019 8:32 AM Program Files (x86)

d-r--- 10/3/2018 11:47 AM Users

d----- 2/7/2019 1:52 AM Windows

Cannot find drive. A drive with the name 'Z' does not exist.

+ CategoryInfo : ObjectNotFound: (Z:String) [Get-ChildItem],


DriveNotFoundException

+ FullyQualifiedErrorId :
DriveNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

+ PSComputerName : localhost

# It would seem that the child job data is gone.

Receive-Job -Name TestJob

# Using the object model, you can still retrieve child job data and streams.

$job = Get-Job -Name TestJob

$job.ChildJobs[0].Error

Cannot find drive. A drive with the name 'Z' does not exist.

+ CategoryInfo : ObjectNotFound: (Z:String) [Get-ChildItem],


DriveNotFoundException

+ FullyQualifiedErrorId :
DriveNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

+ PSComputerName : localhost

Parameters
-AutoRemoveJob

Indicates that this cmdlet deletes the job after it returns the job results.
If the job has
more results, the job is still deleted, but Receive-Job displays a message.

This parameter works only on custom job types.


It is designed for instances of job
types that save the job or the type outside of the session, such
as instances of
scheduled jobs.

This parameter cannot be used without the Wait parameter.


This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-ComputerName

Specifies an array of names of computers.

This parameter selects from among the job results that are stored on the local
computer.
It does not get data for jobs run on remote computers.
To get job results
that are stored on remote computers, use the Invoke-Command cmdlet to run a
Receive-Job command remotely.

Type: String[]

Aliases: Cn

Position: 1

Default value: All computers available

Accept pipeline input: True

Accept wildcard characters: True

-Force

Indicates that this cmdlet continues waiting if jobs are in the Suspended or
Disconnected
state. By default, the Wait parameter of Receive-Job returns, or
terminates the wait, when
jobs are in one of the following states:

Completed
Failed
Stopped
Suspended
Disconnected.

The Force parameter is valid only when the Wait parameter is also used in the
command.
This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Id

Specifies an array of IDs.


This cmdlet gets the results of jobs with the specified IDs.

The ID is an integer that uniquely identifies the job in the current session.
It is easier
to remember and type than the instance ID, but it is unique only in the current
session. You can type one or more IDs separated by commas.
To find the ID of a job,
use Get-Job .

Type: Int32[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-InstanceId

Specifies an array of instance IDs.


This cmdlet gets the results of 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 the Get-Job cmdlet.

Type: Guid[]

Position: 0

Default value: All instances

Accept pipeline input: True

Accept wildcard characters: False


-Job

Specifies the job for which results are being retrieved.

Enter a variable that contains the job or a command that gets the job.
You can also
pipe a job object to Receive-Job .

Type: Job[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Keep

Indicates that this cmdlet saves the aggregated stream data in the system, even after
you have
received them. By default, aggregated stream data is erased after viewed
with Receive-Job .

Closing the session, or removing the job with the Remove-Job cmdlet also deletes
aggregated
stream data.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Location

Specifies an array of locations.


This cmdlet gets only the results of jobs in the
specified locations.

Type: String[]

Position: 1

Default value: All locations

Accept pipeline input: False


Accept wildcard characters: False

-Name

Specifies an array of friendly names.


This cmdlet gets the results of jobs that have the
specified names.
Wildcard characters are supported.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-NoRecurse

Indicates that this cmdlet gets results only from the specified job.
By default,
Receive-Job also gets the results of all child jobs of the specified job.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Session

Specifies an array of sessions.


This cmdlet gets the results of jobs that were run in the
specified PowerShell session
(PSSession).
Enter a variable that contains the
PSSession or a command that gets the PSSession, such as a
Get-PSSession
command.

Type: PSSession[]

Position: 1

Default value: All sessions

Accept pipeline input: True

Accept wildcard characters: False


-Wait

Indicates that this cmdlet suppresses the command prompt until all job results are
received.
By default, Receive-Job immediately returns the available results.

By default, the Wait parameter waits until the job is in one of the following states:

Completed
Failed
Stopped
Suspended
Disconnected.

To direct the Wait parameter to continue waiting if the job state is Suspended or
Disconnected,
use the Force parameter together with the Wait parameter.

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WriteEvents

Indicates that this cmdlet reports changes in the job state while it waits for the job to
finish.

This parameter is valid only when the Wait parameter is used in the command and
the Keep
parameter is omitted.

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


-WriteJobInResults

Indicates that this cmdlet returns the job object followed by the results.

This parameter is valid only when the Wait parameter is used in the command and
the Keep
parameter is omitted.

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
Job

You can pipe job objects to this cmdlet.

Outputs
PSObject

This cmdlet returns the results of the commands in the job.

Notes
Windows PowerShell includes the following aliases for Receive-Job :

rcjb

Related Links
Get-Job
Invoke-Command
Remove-Job
Resume-Job
Start-Job
Stop-Job
Suspend-Job
Wait-Job
Receive-PSSession
Reference
Module: Microsoft.PowerShell.Core

Gets results of commands in disconnected sessions

Syntax
PowerShell

Receive-PSSession

[-Session] <PSSession>

[-OutTarget <OutTarget>]

[-JobName <String>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Receive-PSSession

[-Id] <Int32>

[-OutTarget <OutTarget>]

[-JobName <String>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Receive-PSSession

[-ComputerName] <String>

[-ApplicationName <String>]

[-ConfigurationName <String>]

-Name <String>

[-OutTarget <OutTarget>]

[-JobName <String>]

[-Credential <PSCredential>]

[-Authentication <AuthenticationMechanism>]

[-CertificateThumbprint <String>]

[-Port <Int32>]

[-UseSSL]

[-SessionOption <PSSessionOption>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]
PowerShell

Receive-PSSession

[-ComputerName] <String>

[-ApplicationName <String>]

[-ConfigurationName <String>]

-InstanceId <Guid>

[-OutTarget <OutTarget>]

[-JobName <String>]

[-Credential <PSCredential>]

[-Authentication <AuthenticationMechanism>]

[-CertificateThumbprint <String>]

[-Port <Int32>]

[-UseSSL]

[-SessionOption <PSSessionOption>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Receive-PSSession

[-ConfigurationName <String>]

[-ConnectionUri] <Uri>

[-AllowRedirection]

-Name <String>

[-OutTarget <OutTarget>]

[-JobName <String>]

[-Credential <PSCredential>]

[-Authentication <AuthenticationMechanism>]

[-CertificateThumbprint <String>]

[-SessionOption <PSSessionOption>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Receive-PSSession

[-ConfigurationName <String>]

[-ConnectionUri] <Uri>

[-AllowRedirection]

-InstanceId <Guid>

[-OutTarget <OutTarget>]

[-JobName <String>]

[-Credential <PSCredential>]

[-Authentication <AuthenticationMechanism>]

[-CertificateThumbprint <String>]

[-SessionOption <PSSessionOption>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Receive-PSSession

[-InstanceId] <Guid>

[-OutTarget <OutTarget>]

[-JobName <String>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Receive-PSSession

[-Name] <String>

[-OutTarget <OutTarget>]

[-JobName <String>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Receive-PSSession cmdlet gets the results of commands running in PowerShell
sessions
(PSSession) that were disconnected. If the session is currently connected,
Receive-PSSession
gets the results of commands that were running when the session

was disconnected. If the session is


still disconnected, Receive-PSSession connects to the
session, resumes any commands that were
suspended, and gets the results of
commands running in the session.

This cmdlet was introduced in PowerShell 3.0.

You can use a Receive-PSSession in addition to or instead of a Connect-PSSession


command.
Receive-PSSession can connect to any disconnected or reconnected session
that was started in other
sessions or on other computers.

Receive-PSSession works on PSSessions that were disconnected intentionally using the

Disconnect-PSSession cmdlet or the Invoke-Command InDisconnectedSession parameter.


Or
disconnected unintentionally by a network interruption.

If you use the Receive-PSSession cmdlet to connect to a session in which no commands


are running
or suspended, Receive-PSSession connects to the session, but returns no
output or errors.

For more information about the Disconnected Sessions feature, see


about_Remote_Disconnected_Sessions.

Some examples use splatting to reduce the line length and improve readability. For
more information,
see about_Splatting.

Examples

Example 1: Connect to a PSSession


This example connects to a session on a remote computer and gets the results of
commands that are
running in a session.

PowerShell

Receive-PSSession -ComputerName Server01 -Name ITTask

The Receive-PSSession specifies the remote computer with the ComputerName


parameter. The
Name parameter identifies the ITTask session on the Server01 computer.
The example gets the
results of commands that were running in the ITTask session.

Because the command doesn't use the OutTarget parameter, the results appear on the
command line.

Example 2: Get results of all commands on disconnected


sessions
This example gets the results of all commands running in all disconnected sessions on
two remote
computers.

If any session wasn't disconnected or isn't running commands, Receive-PSSession


doesn't connect to
the session and doesn't return any output or errors.

PowerShell

Get-PSSession -ComputerName Server01, Server02 | Receive-PSSession

Get-PSSession uses the ComputerName parameter to specify the remote computers.


The objects are
sent down the pipeline to Receive-PSSession .
Example 3: Get the results of a script running in a session
This example uses the Receive-PSSession cmdlet to get the results of a script that was
running in
a remote computer's session.

PowerShell

$parms = @{

ComputerName = "Server01"

Name = "ITTask"

OutTarget = "Job"

JobName = "ITTaskJob01"

Credential = "Domain01\Admin01"
}

Receive-PSSession @parms

Id Name State HasMoreData Location

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

16 ITTaskJob01 Running True Server01

The command uses the ComputerName and Name parameters to identify the
disconnected session.
It uses the OutTarget parameter with a value of Job to direct
Receive-PSSession to return the
results as a job. The JobName parameter specifies a

name for the job in the reconnected session.


The Credential parameter runs the
Receive-PSSession command using the permissions of a domain
administrator.

The output shows that Receive-PSSession returned the results as a job in the current
session. To
get the job results, use a Receive-Job command

Example 4: Get results after a network outage


This example uses the Receive-PSSession cmdlet to get the results of a job after a
network outage
disrupts a session connection. PowerShell automatically attempts to
reconnect the session once per
second for the next four minutes and abandons the
effort only if all attempts in the four-minute
interval fail.

PowerShell

PS> $s = New-PSSession -ComputerName Server01 -Name AD -ConfigurationName


ADEndpoint

PS> $s

Id Name ComputerName State ConfigurationName Availability

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

8 AD Server01 Opened ADEndpoint Available

PS> Invoke-Command -Session $s -FilePath


\\Server12\Scripts\SharedScripts\New-ADResolve.ps1

Running "New-ADResolve.ps1"

# Network outage

# Restart local computer

# Network access is not re-established within 4 minutes

PS> Get-PSSession -ComputerName Server01

Id Name ComputerName State ConfigurationName


Availability

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


-

1 Backup Server01 Disconnected Microsoft.PowerShell


None

8 AD Server01 Disconnected ADEndpoint


None

PS> Receive-PSSession -ComputerName Server01 -Name AD -OutTarget Job -


JobName AD

Job Id Name State HasMoreData Location

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

16 ADJob Running True Server01

PS> Get-PSSession -ComputerName Server01

Id Name ComputerName State ConfigurationName Availability

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

1 Backup Server01 Disconnected Microsoft.PowerShell Busy

8 AD Server01 Opened ADEndpoint Available

The New-PSSession cmdlet creates a session on the Server01 computer and saves the
session in the
$s variable. The $s variable displays that the State is Opened and the
Availability is
Available. These values indicate that you're connected to the session and
can run commands in the
session.

The Invoke-Command cmdlet runs a script in the session in the $s variable. The script
begins to
run and return data, but a network outage occurs that interrupts the session.
The user has to exit
the session and restart the local computer.

When the computer restarts, the user starts PowerShell and runs a Get-PSSession
command to get
sessions on the Server01 computer. The output shows that the AD
session still exists on the
Server01 computer. The State indicates that the AD session is
disconnected. The
Availability value of None, indicates that the session isn't connected
to any client sessions.

The Receive-PSSession cmdlet reconnects to the AD session and gets the results of the
script
that ran in the session. The command uses the OutTarget parameter to request
the results in a
job named ADJob. The command returns a job object and the output
indicates that the script is
still running.

The Get-PSSession cmdlet is used to check the job state. The output confirms that the
Receive-PSSession cmdlet reconnected to the AD session, which is now open and

available for
commands. And, the script resumed execution and is getting the script
results.

Example 5: Reconnect to disconnected sessions


This example uses the Receive-PSSession cmdlet to reconnect to sessions that were
intentionally
disconnected and get the results of jobs that were running in the sessions.

PowerShell

PS> $parms = @{

InDisconnectedSession = $True

ComputerName = "Server01", "Server02", "Server30"

FilePath = "\\Server12\Scripts\SharedScripts\Get-BugStatus.ps1"

Name = "BugStatus"

SessionOption = @{IdleTimeout = 86400000}

ConfigurationName = "ITTasks"

PS> Invoke-Command @parms

PS> Exit

PS> $s = Get-PSSession -ComputerName Server01, Server02, Server30 -Name


BugStatus

PS> $s

Id Name ComputerName State ConfigurationName Availability

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

1 ITTask Server01 Disconnected ITTasks None

8 ITTask Server02 Disconnected ITTasks None

2 ITTask Server30 Disconnected ITTasks None

PS> $Results = Receive-PSSession -Session $s

PS> $s

Id Name ComputerName State ConfigurationName Availability

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

1 ITTask Server01 Opened ITTasks Available

8 ITTask Server02 Opened ITTasks Available

2 ITTask Server30 Opened ITTasks Available

PS> $Results

Bug Report - Domain 01

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

ComputerName BugCount LastUpdated

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

Server01 121 Friday, December 30, 2011 5:03:34 PM

The Invoke-Command cmdlet runs a script on three remote computers. Because the script
gathers and
summarizes data from multiple databases, it often takes the script an
extended time to finish. The
command uses the InDisconnectedSession parameter that
starts the scripts and then immediately
disconnects the sessions. The SessionOption
parameter extends the IdleTimeout value of the
disconnected session. Disconnected
sessions are considered idle from the moment they're
disconnected. It's important to set
the idle time-out for long enough so that the commands can
complete and you can
reconnect to the session. You can set the IdleTimeout only when you create
the
PSSession and change it only when you disconnect from it. You can't change the
IdleTimeout value when you connect to a PSSession or receiving its results. After
running
the command, the user exits PowerShell and closes the computer.

The next day, the user resumes Windows, starts PowerShell, and uses Get-PSSession to
get the
sessions in which the scripts were running. The command identifies the sessions
by the computer
name, session name, and the name of the session configuration and
saves the sessions in the $s
variable. The value of the $s variable is displayed and
shows that the sessions are disconnected,
but aren't busy.

The Receive-PSSession cmdlet connects to the sessions in the $s variable and gets their
results.
The command saves the results in the $Results variable. The $s variable is
displayed and shows
that the sessions are connected and available for commands.

The script results in the $Results variable are displayed in the PowerShell console. If any
of the
results are unexpected, the user can run commands in the sessions to investigate
the root cause.

Example 6: Running a job in a disconnected session


This example shows what happens to a job that's running in a disconnected session.

PowerShell
PS> $s = New-PSSession -ComputerName Server01 -Name Test

PS> $j = Invoke-Command -Session $s { 1..1500 | Foreach-Object {"Return $_";


sleep 30}} -AsJob

PS> $j

Id Name State HasMoreData Location

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

16 Job1 Running True Server01

PS> $s | Disconnect-PSSession

Id Name ComputerName State ConfigurationName Availability

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

1 Test Server01 Disconnected Microsoft.PowerShell None

PS> $j

Id Name State HasMoreData Location

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

16 Job1 Disconnected True Server01

PS> Receive-Job $j -Keep

Return 1

Return 2

PS> $s2 = Connect-PSSession -ComputerName Server01 -Name Test

PS> $j2 = Receive-PSSession -ComputerName Server01 -Name Test

PS> Receive-Job $j

Return 3

Return 4

The New-PSSession cmdlet creates the Test session on the Server01 computer. The
command saves the
session in the $s variable.

The Invoke-Command cmdlet runs a command in the session in the $s variable. The
command uses the
AsJob parameter to run the command as a job and creates the job
object in the current session.
The command returns a job object that's saved in the $j
variable. The $j variable displays the
job object.

The session object in the $s variable is sent down the pipeline to Disconnect-PSSession
and the
session is disconnected.
The $j variable is displayed and shows the effect of disconnecting the job object in the
$j
variable. The job state is now Disconnected.

The Receive-Job is run on the job in the $j variable. The output shows that the job
began to
return output before the session and the job were disconnected.

The Connect-PSSession cmdlet is run in the same client session. The command
reconnects to the Test
session on the Server01 computer and saves the session in the
$s2 variable.

The Receive-PSSession cmdlet gets the results of the job that was running in the
session. Because
the command is run in the same session, Receive-PSSession returns
the results as a job by default
and reuses the same job object. The command saves the
job in the $j2 variable. The Receive-Job
cmdlet gets the results of the job in the $j
variable.

Parameters
-AllowRedirection

Indicates that this cmdlet 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, PowerShell doesn't redirect
connections, but you can use
this parameter to enable it to redirect the connection.

You can also limit the number of times the connection is redirected by changing the
MaximumConnectionRedirectionCount session option value. Use the
MaximumRedirection parameter
of the New-PSSessionOption cmdlet or set the
MaximumConnectionRedirectionCount property of the
$PSSessionOption
preference variable. The default value is 5.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


-ApplicationName

Specifies an application. This cmdlet connects only to sessions that use the specified
application.

Enter the application name segment of the connection URI. For example, in the
following connection
URI, WSMan is the application name:
http://localhost:5985/WSMAN .

The application name of a session is stored in the


Runspace.ConnectionInfo.AppName property of
the session.

The parameter's value is used to select and filter sessions. It doesn't change the
application that
the session uses.

Type: String

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Authentication

Specifies the mechanism that's used to authenticate the user credentials in the
command to reconnect
to a disconnected session. The acceptable values for this
parameter are:

Default
Basic
Credssp
Digest
Kerberos
Negotiate
NegotiateWithImplicitCredential

The default value is Default.

For more information about the values of this parameter, see


AuthenticationMechanism Enumeration.

U Caution
Credential Security Support Provider (CredSSP) authentication, in which the user
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.

Type: AuthenticationMechanism

Accepted values: Default, Basic, Negotiate, NegotiateWithImplicitCredential,


Credssp, Digest, Kerberos

Position: Named

Default value: Default

Accept pipeline input: False

Accept wildcard characters: False

-CertificateThumbprint

Specifies the digital public key certificate (X509) of a user account that has
permission to connect
to the disconnected session. Enter the certificate thumbprint
of the certificate.

Certificates are used in client certificate-based authentication. Certificates can be


mapped only to
local user accounts, and don't work with domain accounts.

To get a certificate thumbprint, use a Get-Item or Get-ChildItem command in the


PowerShell
Cert: drive.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ComputerName

Specifies the computer on which the disconnected session is stored. Sessions are
stored on the
computer that's at the server-side, or receiving end of a connection.
The default is the local
computer.

Type the NetBIOS name, an IP address, or a fully qualified domain name (FQDN) of
one computer.
Wildcard characters aren't permitted. To specify the local computer,
type the computer name, a dot
( . ), $env:COMPUTERNAME , or localhost.

Type: String

Aliases: Cn

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-ConfigurationName

Specifies the name of a session configuration. This cmdlet connects only to sessions
that use the
specified session configuration.

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 configuration name of a session is stored in the ConfigurationName property of


the session.

The parameter's value is used to select and filter sessions. It doesn't change the
session
configuration that the session uses.

For more information about session configurations, see


about_Session_Configurations.

Type: String

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False


-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-ConnectionUri

Specifies a URI that defines the connection endpoint that is used to reconnect to the
disconnected
session.

The URI must be fully qualified. The string's format is as follows:

<Transport>://<ComputerName>:<Port>/<ApplicationName>

The default value is as follows:

http://localhost:5985/WSMAN

If you don't specify a connection URI, you can use the UseSSL, ComputerName, Port,
and
ApplicationName parameters to specify the connection URI values.

Valid values for the Transport segment of the URI are HTTP and HTTPS. If you specify
a
connection URI with a Transport segment, but don't specify a port, the session is
created with
standard ports: 80 for HTTP and 443 for HTTPS. To use the default ports
for PowerShell remoting,
specify port 5985 for HTTP or 5986 for HTTPS.

If the destination computer redirects the connection to a different URI, PowerShell


prevents the
redirection unless you use the AllowRedirection parameter in the
command.

Type: Uri

Aliases: URI, CU

Position: 0

Default value: http://localhost:5985/WSMAN


Accept pipeline input: True

Accept wildcard characters: False

-Credential

Specifies a user account that has permission to connect to the disconnected session.
The default is
the current user.

Type a user name, such as User01 or Domain01\User01, or enter a PSCredential


object
generated by the Get-Credential cmdlet. If you type a user name, you're
prompted to enter the
password.

Credentials are stored in a PSCredential


object and the password is stored as a
SecureString.

7 Note

For more information about SecureString data protection, see


How secure is
SecureString?.

Type: PSCredential

Position: Named

Default value: Current user

Accept pipeline input: False

Accept wildcard characters: False

-Id

Specifies the ID of a disconnected session. The Id parameter works only when the
disconnected
session was previously connected to the current session.

This parameter is valid, but not effective, when the session is stored on the local
computer, but
wasn't connected to the current session.

Type: Int32

Position: 0

Default value: None

Accept pipeline input: True


Accept wildcard characters: False

-InstanceId

Specifies the instance ID of the disconnected session. The instance ID is a GUID that
uniquely
identifies a PSSession on a local or remote computer. The instance ID is
stored in the
InstanceID property of the PSSession.

Type: Guid

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-JobName

Specifies a friendly name for the job that Receive-PSSession returns.

Receive-PSSession returns a job when the value of the OutTarget parameter is Job

or the job
that's running in the disconnected session was started in the current
session.

If the job that's running in the disconnected session was started in the current
session, PowerShell
reuses the original job object in the session and ignores the
value of the JobName parameter.

If the job that's running in the disconnected session was started in a different
session, PowerShell
creates a new job object. It uses a default name, but you can use
this parameter to change the name.

If the default value or explicit value of the OutTarget parameter isn't Job, the
command
succeeds, but the JobName parameter has no effect.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-Name

Specifies the friendly name of the disconnected session.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-OutTarget

Determines how the session results are returned. The acceptable values for this
parameter are:

Job. Returns the results asynchronously in a job object. You can use the
JobName parameter
to specify a name or new name for the job.
Host. Returns the results to the command line (synchronously). If the command
is being resumed
or the results consist of a large number of objects, the
response might be delayed.

The default value of the OutTarget parameter is Host. If the command that's being
received in a
disconnected session was started in the current session, the default
value of the OutTarget
parameter is the form in which the command was started. If
the command was started as a job, by
default, it's returned as a job. Otherwise, it's
returned to the host program by default.

Typically, the host program displays returned objects at the command line without
delay, but this
behavior can vary.

Type: OutTarget

Accepted values: Default, Host, Job

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Port
Specifies the remote computer's network port that's used to reconnect to the
session. To connect to
a remote computer, it must be listening on the port that the
connection uses. The default ports are
5985, which is the WinRM port for HTTP, and
5986, which is the WinRM port for HTTPS.

Before using an alternate port, you must configure the WinRM listener on the
remote computer to
listen on that port. To configure the listener, type the following
two commands at the PowerShell
prompt:

Remove-Item -Path WSMan:\Localhost\listener\listener* -Recurse

New-Item -Path WSMan:\Localhost\listener -Transport http -Address * -Port \


<port-number\>

Don't use the Port parameter unless it's necessary. The port that's 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.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Session

Specifies the disconnected session. Enter a variable that contains the PSSession or a
command
that creates or gets the PSSession, such as a Get-PSSession command.

Type: PSSession

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-SessionOption
Specifies advanced options for the session. Enter a SessionOption object, such as
one that you
create by using the New-PSSessionOption cmdlet, or a hash table in
which the keys are session
option names and the values are session option values.

The default values for the options are determined by the value of the
$PSSessionOption preference
variable, if it's set. Otherwise, the default values are

established by options set in the session


configuration.

The session option values take precedence over default values for sessions set in the
$PSSessionOption preference variable and in the session configuration. However,

they don't take


precedence over maximum values, quotas, or limits set in the session
configuration.

For a description of the session options that includes the default values, see
New-
PSSessionOption . For information about the $PSSessionOption preference variable,
see
about_Preference_Variables. For more information about
session configurations,
see
about_Session_Configurations.

Type: PSSessionOption

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-UseSSL

Indicates that this cmdlet uses the Secure Sockets Layer (SSL) protocol to connect to
the
disconnected session. By default, SSL isn't used.

WS-Management encrypts all 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 and SSL isn't available on the port that's used for the
command, the
command fails.

Type: SwitchParameter

Position: Named

Default value: False


Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet isn't run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSSession

You can pipe session objects to this cmdlet, such as objects returned by the Get-
PSSession cmdlet.

Int32

You can pipe session Ids to this cmdlet.

Guid

You can pipe the instance Ids of sessions this cmdlet.

String

You can pipe session names to this cmdlet.

Outputs
Job

If the value or default value of the OutTarget parameter is Job , Receive-PSSession


returns a
job object.
PSObject

This cmdlet returns the results of commands that ran in the disconnected session, if any.

Notes
Windows PowerShell includes the following aliases for Receive-PSSession :

rcsn

Receive-PSSession gets results only from sessions that were disconnected. Only sessions
that are
connected to, or terminate at, computers that run PowerShell 3.0 or later
versions can be
disconnected and reconnected.

If the commands that were running in the disconnected session didn't generate results
or if the
results were already returned to another session, Receive-PSSession doesn't
generate any output.

A session's output buffering mode determines how commands in the session manage
output when the
session is disconnected. When the value of the OutputBufferingMode
option of the session is Drop
and the output buffer is full, the command starts to delete
output. Receive-PSSession can't
recover this output. For more information about the
output buffering mode option, see the help
articles for the New-PSSessionOption and
New-PSTransportOption cmdlets.

You can't change the idle time-out value of a PSSession when you connect to the
PSSession or
receive results. The SessionOption parameter of Receive-PSSession takes
a SessionOption
object that has an IdleTimeout value. However, the IdleTimeout value
of the
SessionOption object and the IdleTimeout value of the $PSSessionOption
variable are
ignored when it connects to a PSSession or receiving results.

You can set and change the idle time-out of a PSSession when you create the
PSSession, by
using the New-PSSession or Invoke-Command cmdlets, and when you
disconnect from the
PSSession.
The IdleTimeout property of a PSSession is critical to disconnected sessions
because it
determines how long a disconnected session is maintained on the
remote computer. Disconnected
sessions are considered to be idle from the
moment that they are disconnected, even if commands
are running in the
disconnected session.

If you start a start a job in a remote session by using the AsJob parameter of the
Invoke-Command cmdlet, the job object is created in the current session, even though the
job runs
in the remote session. If you disconnect the remote session, the job object in
the current session
is disconnected from the job. The job object contains any results that
were returned to it, but
doesn't receive new results from the job in the disconnected
session.

If a different client connects to the session that contains the running job, the results that
were
delivered to the original job object in the original session aren't available in the
newly connected
session. Only results that were not delivered to the original job object
are available in the
reconnected session.

Similarly, if you start a script in a session and then disconnect from the session, any
results that
the script delivers to the session before disconnecting aren't available to
another client that
connects to the session.

To prevent data loss in sessions that you intend to disconnect, use the
InDisconnectedSession
parameter of the Invoke-Command cmdlet. Because this
parameter prevents results from being
returned to the current session, all results are
available when the session is reconnected.

You can also prevent data loss by using the Invoke-Command cmdlet to run a Start-Job
command in
the remote session. In this case, the job object is created in the remote
session. You can't use the
Receive-PSSession cmdlet to get the job results. Instead, use
the Connect-PSSession cmdlet to
connect to the session and then use the Invoke-
Command cmdlet to run a Receive-Job command in
the session.

When a session that contains a running job is disconnected and then reconnected, the
original job
object is reused only if the job is disconnected and reconnected to the same
session, and the
command to reconnect doesn't specify a new job name. If the session is
reconnected to a different
client session or a new job name is specified, PowerShell
creates a new job object for the new
session.

When you disconnect a PSSession, the session state is Disconnected and the availability
is None.

The value of the State property is relative to the current session. A value of
Disconnected
means that the PSSession isn't connected to the current session.
However, it doesn't mean that
the PSSession is disconnected from all sessions. It
might be connected to a different session.
To determine whether you can connect
or reconnect to the session, use the Availability
property.
An Availability value of None indicates that you can connect to the session. A
value of Busy
indicates that you can't connect to the PSSession because it's
connected to another session.
For more information about the values of the State property of sessions, see
RunspaceState.
For more information about the values of the Availability property of sessions, see
RunspaceAvailability.

Related Links
about_PSSessions
about_Remote
about_Remote_Disconnected_Sessions
about_Session_Configurations
Connect-PSSession
Enter-PSSession
Exit-PSSession
Get-PSSession
Invoke-Command
New-PSSession
New-PSSessionOption
New-PSTransportOption
Remove-PSSession
Register-ArgumentCompleter
Reference
Module: Microsoft.PowerShell.Core

Registers a custom argument completer.

Syntax
PowerShell

Register-ArgumentCompleter

-CommandName <String[]>

-ScriptBlock <ScriptBlock>

[-Native]

[<CommonParameters>]

PowerShell

Register-ArgumentCompleter

[-CommandName <String[]>]
-ParameterName <String>

-ScriptBlock <ScriptBlock>

[<CommonParameters>]

Description
The Register-ArgumentCompleter cmdlet registers a custom argument completer. An
argument
completer allows you to provide dynamic tab completion, at run time for any
command that you
specify.

Examples

Example 1: Register a custom argument completer


The following example registers an argument completer for the Id parameter of the
Set-TimeZone
cmdlet.

PowerShell
$scriptBlock = {

param($commandName, $parameterName, $wordToComplete, $commandAst,


$fakeBoundParameters)

(Get-TimeZone -ListAvailable).Id | Where-Object {

$_ -like "$wordToComplete*"

} | ForEach-Object {

"'$_'"

Register-ArgumentCompleter -CommandName Set-TimeZone -ParameterName Id -


ScriptBlock $scriptBlock

The first command creates a script block which takes the required parameters which are
passed in
when the user presses Tab . For more information, see the ScriptBlock
parameter
description.

Within the script block, the available values for Id are retrieved using the Get-TimeZone
cmdlet. The Id property for each Time Zone is piped to the Where-Object cmdlet. The
Where-Object cmdlet filters out any ids that do not start with the value provided by
$wordToComplete , which represents the text the user typed before they pressed Tab . The

filtered ids are piped to the ForEach-Object cmdlet which encloses each value in quotes,
should
the value contain spaces.

The second command registers the argument completer by passing the scriptblock, the
ParameterName Id and the CommandName Set-TimeZone .

Example 2: Add details to your tab completion values


The following example overwrites tab completion for the Name parameter of the Stop-
Service
cmdlet and only returns running services.

PowerShell

$s = {

param($commandName, $parameterName, $wordToComplete, $commandAst,


$fakeBoundParameters)

$services = Get-Service | Where-Object {$_.Status -eq "Running" -and


$_.Name -like "$wordToComplete*"}

$services | ForEach-Object {

New-Object -Type System.Management.Automation.CompletionResult -


ArgumentList $_.Name,

$_.Name,

"ParameterValue",

$_.Name

Register-ArgumentCompleter -CommandName Stop-Service -ParameterName Name -


ScriptBlock $s

The first command creates a script block which takes the required parameters which are
passed in
when the user presses Tab . For more information, see the ScriptBlock
parameter
description.

Within the script block, the first command retrieves all running services using the Where-
Object
cmdlet. The services are piped to the ForEach-Object cmdlet. The ForEach-

Object cmdlet creates


a new
[System.Management.Automation.CompletionResult]

object
and populates it with the values of the current service (represented by the
pipeline variable $_ ).

The CompletionResult object allows you to provide additional details to each returned
value:

completionText (String) - The text to be used as the auto completion result. This is
the value
sent to the command.
listItemText (String) - The text to be displayed in a list, such as when the user
presses
Ctrl + Space . This is used for display only and is not passed to the
command
when selected.
resultType (CompletionResultType) - The type of completion result.
toolTip (String) - The text for the tooltip with details to be displayed about the
object.
This is visible when the user selects an item after pressing Ctrl + Space .

The last command demonstrates that stopped services can still be passed in manually to
the
Stop-Service cmdlet. The tab completion is the only aspect affected.

Example 3: Register a custom Native argument completer


You can use the Native parameter to provide tab-completion for a native command. The
following
example adds tab-completion for the dotnet Command Line Interface (CLI).

7 Note

The dotnet complete command is only available in version 2.0 and greater of the
dotnet cli.

PowerShell
$scriptblock = {

param($wordToComplete, $commandAst, $cursorPosition)

dotnet complete --position $cursorPosition $commandAst.ToString() |


ForEach-Object {

[System.Management.Automation.CompletionResult]::new($_, $_,
'ParameterValue', $_)

Register-ArgumentCompleter -Native -CommandName dotnet -ScriptBlock


$scriptblock

The first command creates a script block which takes the required parameters which are
passed in
when the user presses Tab . For more information, see the ScriptBlock
parameter
description.

Within the script block, the dotnet complete command is used to perform the tab
completion.
The results are piped to the ForEach-Object cmdlet which use the new
static method of the
System.Management.Automation.CompletionResult class
to create
a new CompletionResult object for each value.

Parameters
-CommandName

Specifies the name of the commands as an array.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Native

Indicates that the argument completer is for a native command where PowerShell
cannot complete
parameter names.

Type: SwitchParameter

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-ParameterName

Specifies the name of the parameter whose argument is being completed. The
parameter name specified
cannot be an enumerated value, such as the
ForegroundColor parameter of the Write-Host cmdlet.

For more information on enums, see about_Enum.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ScriptBlock

Specifies the commands to run to perform tab completion. The script block you
provide should return
the values that complete the input. The script block must
unroll the values using the pipeline
( ForEach-Object , Where-Object , etc.), or another
suitable method. Returning an array of values
causes PowerShell to treat the entire
array as one tab completion value.

The script block must accept the following parameters in the order specified below.
The names of the
parameters aren't important because PowerShell passes in the
values by position.

$commandName (Position 0) - This parameter is set to the name of the


command
for which the script block is providing tab completion.
$parameterName (Position 1) - This parameter is set to the parameter
whose
value requires tab completion.
$wordToComplete (Position 2) - This parameter is set to value the user has

provided before they


pressed Tab . Your script block should use this value to
determine tab completion
values.
$commandAst (Position 3) - This parameter is set to the Abstract Syntax
Tree
(AST) for the current input line. For more information, see
Ast Class.
$fakeBoundParameters (Position 4) - This parameter is set to a hashtable

containing the
$PSBoundParameters for the cmdlet, before the user pressed Tab

. For more information,


see about_Automatic_Variables.

When you specify the Native parameter, the script block must take the following
parameters in
the specified order. The names of the parameters aren't important
because PowerShell passes in the
values by position.

$wordToComplete (Position 0) - This parameter is set to value the user has


provided before they
pressed Tab . Your script block should use this value to
determine tab completion
values.
$commandAst (Position 1) - This parameter is set to the Abstract Syntax
Tree

(AST) for the current input line. For more information, see
Ast Class.
$cursorPosition (Position 2) - This parameter is set to the position of the
cursor when the user
pressed Tab .

You can also provide an ArgumentCompleter as a parameter attribute. For more


information, see
about_Functions_Advanced_Parameters.

Type: ScriptBlock

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

This cmdlet returns no output.


Register-PSSessionConfiguration
Reference
Module: Microsoft.PowerShell.Core

Creates and registers a new session configuration.

Syntax
PowerShell

Register-PSSessionConfiguration

[-ProcessorArchitecture <String>]

[-SessionType <PSSessionType>]

[-Name] <String>

[-ApplicationBase <String>]

[-RunAsCredential <PSCredential>]

[-ThreadApartmentState <ApartmentState>]

[-ThreadOptions <PSThreadOptions>]

[-AccessMode <PSSessionConfigurationAccessMode>]

[-UseSharedProcess]

[-StartupScript <String>]
[-MaximumReceivedDataSizePerCommandMB <Double>]

[-MaximumReceivedObjectSizeMB <Double>]

[-SecurityDescriptorSddl <String>]

[-ShowSecurityDescriptorUI]

[-Force]

[-NoServiceRestart]

[-PSVersion <Version>]

[-SessionTypeOption <PSSessionTypeOption>]

[-TransportOption <PSTransportOption>]

[-ModulesToImport <Object[]>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Register-PSSessionConfiguration

[-ProcessorArchitecture <String>]

[-Name] <String>

[-AssemblyName] <String>

[-ApplicationBase <String>]

[-ConfigurationTypeName] <String>

[-RunAsCredential <PSCredential>]

[-ThreadApartmentState <ApartmentState>]

[-ThreadOptions <PSThreadOptions>]

[-AccessMode <PSSessionConfigurationAccessMode>]

[-UseSharedProcess]

[-StartupScript <String>]
[-MaximumReceivedDataSizePerCommandMB <Double>]

[-MaximumReceivedObjectSizeMB <Double>]

[-SecurityDescriptorSddl <String>]

[-ShowSecurityDescriptorUI]

[-Force]

[-NoServiceRestart]

[-PSVersion <Version>]

[-SessionTypeOption <PSSessionTypeOption>]

[-TransportOption <PSTransportOption>]

[-ModulesToImport <Object[]>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Register-PSSessionConfiguration

[-ProcessorArchitecture <String>]

[-Name] <String>

[-RunAsCredential <PSCredential>]

[-ThreadApartmentState <ApartmentState>]

[-ThreadOptions <PSThreadOptions>]

[-AccessMode <PSSessionConfigurationAccessMode>]

[-UseSharedProcess]

[-StartupScript <String>]
[-MaximumReceivedDataSizePerCommandMB <Double>]

[-MaximumReceivedObjectSizeMB <Double>]

[-SecurityDescriptorSddl <String>]

[-ShowSecurityDescriptorUI]

[-Force]

[-NoServiceRestart]

[-TransportOption <PSTransportOption>]

-Path <String>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Register-PSSessionConfiguration cmdlet creates and registers a new session
configuration on
the local computer. This is an advanced cmdlet that you can use to
create custom sessions for remote
users.

Every PowerShell session (PSSession) uses a session configuration, also known as an


endpoint.
When users create a session that connects to the computer, they can select a
session configuration
or use the default session configuration that is registered when
you enable PowerShell remoting.
Users can also set the $PSSessionConfigurationName
preference variable, which specifies a default
configuration for remote sessions created
in the current session.

The session configuration defines the environment for the remote session. The
configuration can
determine which commands and language elements 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. The security descriptor of the session configuration
determines which users
have permission to use the session configuration.

You can define the elements of configuration by using an assembly that implements a
new
configuration class and by using a script that runs in the session. Beginning in
PowerShell
3.0, you can also use a session configuration file to define the session
configuration.

For information about session configurations, see about_Session_Configurations.


For
information about session configuration files, see about_Session_Configuration_Files.

Examples

Example 1: Register a NewShell session configuration


In this example, we register the NewShell session configuration. The AssemblyName
and
ApplicationBase parameters specify the location of the MyShell.dll file, which
specifies
the cmdlets and providers in the session configuration. The
ConfigurationTypeName
parameter specifies the configuration class to use from the
assembly.

PowerShell

$sessionConfiguration = @{

Name='NewShell'

ApplicationBase='c:\MyShells\'

AssemblyName='MyShell.dll'

ConfigurationTypeName='MyClass'

Register-PSSessionConfiguration @sessionConfiguration

To use this configuration, type New-PSSession -ConfigurationName newshell .

Example 2: Register a MaintenanceShell session


configuration
This example registers the MaintenanceShell session configuration on the local
computer. The
StartupScript parameter specifies the Maintenance.ps1 script.

PowerShell

Register-PSSessionConfiguration -Name MaintenanceShell -StartupScript C:\ps-


test\Maintenance.ps1

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. This
includes importing modules 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: Register a session configuration


This example registers the AdminShell session configuration.

The $sessionParams variable is a hashtable containing all the parameter values. This
hashtable is
passed to the cmdlet using PowerShell splatting. The Register-
PSSessionConfiguration 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.

PowerShell

$sddl = "O:NSG:BAD:P(A;;GA;;;BA)S:P(AU;FA;GA;;;WD)(AU;FASA;GWGX;;;WD)"

$sessionParams = @{

Name="AdminShell"

SecurityDescriptorSDDL=$sddl

MaximumReceivedObjectSizeMB=20

StartupScript="C:\scripts\AdminShell.ps1"

Register-PSSessionConfiguration @sessionParams

Example 4: Return a configuration container element


This example shows how to register the MaintenanceShell configuration.
Register-
PSSessionConfiguration returns a WSManConfigContainerElement object stored in the
$s variable. Format-List displays all the properties of the returned object. The PSPath

property shows that the object is stored in a directory of the WSMan: drive. Get-
ChildItem (alias
dir ) displays the items in the WSMan:\LocalHost\PlugIn path. These

include the new


MaintenanceShell configuration and the two default configurations
that come with PowerShell.

PowerShell

$s = Register-PSSessionConfiguration -Name MaintenanceShell -StartupScript


C:\ps-test\Maintenance.ps1

$s | Format-List -Property *

dir WSMan:\LocalHost\Plugin

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

Name Type Keys

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

MaintenanceShell Container {Name=MaintenanceShell}

microsoft.powershell Container {Name=microsoft.powershell}

microsoft.powershell32 Container {Name=microsoft.powershell32}

Example 5: Register a session configuration with a startup


script
In this example we create and register the WithProfile session configuration. The
StartupScript parameter directs PowerShell to run the specified script for any session
that uses
the session configuration.

PowerShell

Register-PSSessionConfiguration -Name WithProfile -StartupScript Add-


Profile.ps1

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

Enables and disables the session configuration and determines whether it can be
used for remote or
local sessions on the computer. The acceptable values for this
parameter are:

Disabled. Disables the session configuration. It cannot be used for remote or


local access to the
computer.
Local. Allows users of the local computer to use the session configuration to
create a local
loopback session on the same computer, but denies access to
remote users.
Remote. Allows local and remote users to use the session configuration to
create sessions and run
commands on this computer.

The default value is Remote.

Other cmdlets can override the value of this parameter later. For example, the
Enable-PSRemoting
cmdlet allows for remote access to all session configurations, the

Enable-PSSessionConfiguration
cmdlet enables session configurations, and the

Disable-PSRemoting cmdlet prevents remote access to


all session configurations.

This parameter was introduced in PowerShell 3.0.

Type: PSSessionConfigurationAccessMode

Accepted values: Disabled, Local, Remote

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ApplicationBase

Specifies the path of 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.

Type: String
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-AssemblyName

Specifies the name of an assembly file (*.dll) in which the configuration type is
defined. You can
specify the path of the .dll in this parameter or in the value of the
ApplicationBase parameter.

This parameter is required when you specify the ConfigurationTypeName


parameter.

Type: String

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ConfigurationTypeName

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, specify the
AssemblyName and ApplicationBase parameters.

Creating a type lets you 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.

Type: String

Position: 2
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

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, specify the NoServiceRestart
parameter.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-MaximumReceivedDataSizePerCommandMB

Specifies a limit for 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.

Type: Nullable<T>[Double]

Position: Named

Default value: 50

Accept pipeline input: False

Accept wildcard characters: False

-MaximumReceivedObjectSizeMB

Specifies a limit for the amount of data that can be sent to this computer in any
single object.
Enter the data size in megabytes. 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.

Type: Nullable<T>[Double]

Position: Named

Default value: 10

Accept pipeline input: False

Accept wildcard characters: False

-ModulesToImport

Specifies the modules that are automatically imported into sessions that use the
session
configuration.

By default, only Microsoft.PowerShell.Core is imported into sessions. Unless the


cmdlets are
excluded, you can use Import-Module to add modules to the session.

The modules specified in this parameter value are imported in additions to modules
that are
specified by the SessionType parameter and those listed in the
ModulesToImport key in the
session configuration file ( New-
PSSessionConfigurationFile ). However, settings in the session
configuration file can

hide the commands exported by modules or prevent users from using them.

This parameter was introduced in PowerShell 3.0.


Type: Object[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Name

Specifies a name for the session configuration. This parameter is required.

Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-NoServiceRestart

Does not restart the WinRM service, and suppresses the prompt to restart the
service.

By default, when you run 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, specify the Force parameter. To
restart the
WinRM service manually, use the Restart-Service cmdlet.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Path
Specifies the path and filename of a session configuration file (.pssc), such as one
created by
New-PSSessionConfigurationFile . If you omit the path, the default is the
current directory.

This parameter was introduced in PowerShell 3.0.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ProcessorArchitecture

Determines whether a 32-bit or 64-bit version of the PowerShell process is started in


sessions that
use this session configuration. The acceptable values for this parameter
are: x86 (32-bit) and AMD64
(64-bit). The default value is determined by the
processor architecture of the computer that hosts
the session configuration.

You can use this parameter to create a 32-bit session on a 64-bit computer. Attempts
to create a
64-bit process on a 32-bit computer fail.

Type: String

Aliases: PA

Accepted values: x86, amd64

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-PSVersion

Specifies the version of PowerShell in sessions that use this session configuration.

The value of this parameter takes precedence over the value of the
PowerShellVersion key in the
session configuration file.

This parameter was introduced in PowerShell 3.0.


Type: Version

Aliases: PowerShellVersion

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RunAsCredential

Specifies credentials for commands in the session. By default, commands run with
the permissions of
the current user.

This parameter was introduced in PowerShell 3.0.

Type: PSCredential

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SecurityDescriptorSddl

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 WSMan provider. For
example
Get-Item wsman:\localhost\service\rootSDDL . For more information about
the WSMan provider, type
Get-Help wsman .
Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SessionType

Specifies the type of session that is created by using the session configuration. The
acceptable
values for this parameter are:

Empty. No modules are added to session by default. Use the parameters of this
cmdlet to add
modules, functions, scripts, and other features to the session.
Default. Adds Microsoft.PowerShell.Core to the session. This module includes
the Import-Module
cmdlet that users can use to import other modules unless
you explicitly prohibit the cmdlet.
RestrictedRemoteServer. Includes only the following cmdlets: Exit-PSSession ,
Get-Command ,
Get-FormatData , Get-Help , Measure-Object , Out-Default , and

Select-Object . Use a script


or assembly, or the keys in the session
configuration file, to add modules, functions, scripts,
and other features to the
session.

The default value is Default.

The value of this parameter takes precedence over the value of the SessionType key
in the
session configuration file.

This parameter was introduced in PowerShell 3.0.

Type: PSSessionType

Accepted values: DefaultRemoteShell, Workflow

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SessionTypeOption
Specifies type-specific options for the session configuration. Enter a session type
options object,
such as the PSWorkflowExecutionOption object that the New-
PSWorkflowExecutionOption cmdlet
returns.

The options of sessions that use the session configuration are determined by the
values of session
options and the session configuration options. Unless specified,
options set in the session, such as
by using the New-PSSessionOption cmdlet, take
precedence over options set in the session
configuration. However, session option
values cannot exceed maximum values set in the session
configuration.

This parameter was introduced in PowerShell 3.0.

Type: PSSessionTypeOption

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ShowSecurityDescriptorUI

Indicates that this cmdlet displays a property sheet that helps you 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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-StartupScript
Specifies the fully qualified path of a PowerShell script. The specified script runs in
the new
session that uses the session configuration.

You can use the script to additionally configure the session. If the script generates an
error, even
a non-terminating error, the session is not created and the New-PSSession
command fails.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ThreadApartmentState

Specifies the apartment state of the threads in the session.


The acceptable values for
this parameter are: STA, MTA, and Unknown.
The default value is Unknown.

Type: ApartmentState

Accepted values: STA, MTA, Unknown

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ThreadOptions

Specifies how threads are created and used when a command runs in the session.
The acceptable values
for this parameter are:

Default
ReuseThread
UseCurrentThread
UseNewThread

The default value is UseCurrentThread.

For more information, see PSThreadOptions Enumeration.


Type: PSThreadOptions

Accepted values: Default, UseNewThread, ReuseThread, UseCurrentThread

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-TransportOption

Specifies the transport option.

This parameter was introduced in PowerShell 3.0.

Type: PSTransportOption

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-UseSharedProcess

Use only one process to host all sessions that are started by the same user and use
the same session
configuration. By default, each session is hosted in its own process.

This parameter was introduced in PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
Microsoft.WSMan.Management.WSManConfigContainerElement

Notes
To run this cmdlet you must start PowerShell by using 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 ).

The properties of a session configuration object vary with the options set for the session
configuration and the values of those options. Also, session configurations that use a
session
configuration file have additional properties.

Related Links
Disable-PSSessionConfiguration
Enable-PSSessionConfiguration
Get-PSSessionConfiguration
New-PSSessionConfigurationFile
New-PSSessionOption
Register-PSSessionConfiguration
Set-PSSessionConfiguration
Test-PSSessionConfigurationFile
Unregister-PSSessionConfiguration
WSMan Provider
about_Session_Configurations
about_Session_Configuration_Files
Remove-Job
Reference
Module: Microsoft.PowerShell.Core

Deletes a PowerShell background job.

Syntax
PowerShell

Remove-Job

[-Id] <Int32[]>

[-Force]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-Job

[-Job] <Job[]>

[-Force]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-Job

[-Name] <String[]>

[-Force]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-Job

[-InstanceId] <Guid[]>

[-Force]

[-WhatIf]

[-Confirm]

[<CommonParameters>]
PowerShell

Remove-Job

[-Filter] <Hashtable>

[-Force]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-Job

[-State] <JobState>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-Job

[-Command <String[]>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Remove-Job cmdlet deletes PowerShell background jobs that were started by the
Start-Job
cmdlet or by cmdlets such as Invoke-Command that support the AsJob

parameter.

You can use Remove-Job to delete all jobs or delete selected jobs. The jobs are identified
by
their Name, ID, Instance ID, Command, or State. Or, a job object can be sent
down
the pipeline to Remove-Job . Without parameters or parameter values, Remove-Job has no
effect.

Since PowerShell 3.0, Remove-Job can delete custom job types, such as scheduled jobs
and workflow
jobs. For example, Remove-Job deletes the scheduled job, all instances of
the scheduled job on
disk, and the results of all triggered job instances.

If you try to delete a running job, Remove-Job fails. Use the Stop-Job cmdlet to stop a
running
job. Or, use Remove-Job with the Force parameter to delete a running job.
Jobs remain in the global job cache until you delete the background job or close the
PowerShell
session.

Examples

Example 1: Delete a job by using its name


This example uses a variable and the pipeline to delete a job by name.

PowerShell

$batch = Get-Job -Name BatchJob

$batch | Remove-Job

Get-Job uses the Name parameter to specify the job, BatchJob. The job object is stored

in
the $batch variable. The object in $batch is sent down the pipeline to Remove-Job .

An alternative is to use the Job parameter, such as Remove-Job -Job $batch .

Example 2: Delete all jobs in a session


In this example, all the jobs in the current PowerShell session are deleted.

PowerShell

Get-job | Remove-Job

Get-Job gets all the jobs in the current PowerShell session. The job objects are sent

down the
pipeline to Remove-Job .

Example 3: Delete NotStarted jobs


This example deletes all jobs from the current PowerShell session that haven't started.

PowerShell

Remove-Job -State NotStarted

Remove-Job uses the State parameter to specify the job status.


Example 4: Delete jobs by using a friendly name
This example deletes all jobs from the current session with friendly names that end with
batch*,
including jobs that are running.

PowerShell

Remove-Job -Name *batch -Force

Remove-Job uses the Name parameter to specify a job name pattern. The pattern

includes the
asterisk ( * ) wildcard to find all job names that end with batch. The Force
parameter
deletes jobs that running.

Example 5: Delete a job that was created by Invoke-


Command
This example removes a job that was started on a remote computer using Invoke-
Command with the
AsJob parameter.

Because the example uses the AsJob parameter, the job object is created on the local
computer.
But, the job runs on a remote computer. As a result, you use local commands
to manage the job.

PowerShell

$job = Invoke-Command -ComputerName Server01 -ScriptBlock {Get-Process} -


AsJob

$job | Remove-Job

Invoke-Command runs a job on the Server01 computer. The AsJob parameter runs the
ScriptBlock as a background job. The job object is stored in the $job variable. The $job
variable object is sent down the pipeline to Remove-Job .

Example 6: Delete a job that was created by Invoke-


Command and Start-Job
This example shows how to remove a job on a remote computer that was started by
using
Invoke-Command to run Start-Job . The job object is created on the remote
computer and remote
commands are used to manage the job. A persistent connection
is required when running a remote
Start-Job command.
PowerShell

$S = New-PSSession -ComputerName Server01

Invoke-Command -Session $S -ScriptBlock {Start-Job -ScriptBlock {Get-


Process} -Name MyJob}

Invoke-Command -Session $S -ScriptBlock {Remove-Job -Name MyJob}

New-PSSession creates a PSSession, a persistent connection, to the Server01 computer.


The
connection is saved in the $S variable.

Invoke-Command connects to the session saved in $S . The ScriptBlock uses Start-Job to


start a remote job. The job runs a Get-Process command and uses the Name parameter
to specify
a friendly job name, MyJob.

Invoke-Command uses the $S session and runs Remove-Job . The Name parameter
specifies that
the job named MyJob is deleted.

Example 7: Delete a job by using its InstanceId


This example removes a job based on its InstanceId.

PowerShell

$job = Start-Job -ScriptBlock {Get-Process PowerShell}

$job | Format-List -Property *

Remove-Job -InstanceId ad02b942-8007-4407-87f3-d23e71955872

State : Completed

HasMoreData : True

StatusMessage :

Location : localhost

Command : Get-Process PowerShell

JobStateInfo : Completed

Finished : System.Threading.ManualResetEvent

InstanceId : ad02b942-8007-4407-87f3-d23e71955872

Id : 3

Name : Job3

ChildJobs : {Job4}

PSBeginTime : 7/26/2019 11:36:56

PSEndTime : 7/26/2019 11:36:57

PSJobTypeName : BackgroundJob

Output : {}

Error : {}

Progress : {}

Verbose : {}

Debug : {}

Warning : {}

Information : {}
Start-Job starts a background job and the job object is saved in the $job variable.

The object in $job is sent down the pipeline to Format-List . The Property parameter
uses an
asterisk ( * ) to specify that all the object's properties are displayed in a list.

Remove-Job uses the InstanceId parameter to specify the job to delete.

Parameters
-Command

Deletes jobs that include the specified words in the command. You can enter a
comma-separated array.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before Remove-Job is run.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Filter

Deletes jobs that satisfy all the conditions established in the associated hash table.
Enter a hash
table where the keys are job properties and the values are job property
values.
This parameter works only on custom job types, such as workflow jobs and
scheduled jobs. It doesn't
work on standard background jobs, such as those created
by using the Start-Job .

This parameter is introduced in PowerShell 3.0.

Type: Hashtable

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Force

Deletes a job even if the job's state is Running. If the Force parameter isn't specified,
Remove-Job doesn't delete running jobs.

Type: SwitchParameter

Aliases: F

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Id

Deletes background jobs with the specified Id. You can enter a comma-separated
array. The job's
Id is a unique integer that identifies a job within the current session.

To find a job's Id, use Get-Job without parameters.

Type: Int32[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False


-InstanceId

Deletes jobs with the specified InstanceId. You can enter a comma-separated array.
An
InstanceId is a unique GUID that identifies a job.

To find a job's InstanceId, use Get-Job .

Type: Guid[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Job

Specifies the jobs to be deleted. Enter a variable that contains the jobs or a
command that gets the
jobs. You can enter a comma-separated array.

You can send job objects down the pipeline to Remove-Job .

Type: Job[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Only deletes jobs with the specified friendly name. Wildcards are permitted. You can
enter a
comma-separated array.

Friendly names for jobs aren't guaranteed to be unique, even within a PowerShell
session. Use the
WhatIf and Confirm parameters when you delete files by name.

Type: String[]

Position: 0

Default value: None


Accept pipeline input: True

Accept wildcard characters: True

-State

Only deletes jobs with the specified state. To delete jobs with a state of Running, use
the
Force parameter.

Accepted values:

AtBreakpoint
Blocked
Completed
Disconnected
Failed
NotStarted
Running
Stopped
Stopping
Suspended
Suspending

Type: JobState

Accepted values: AtBreakpoint, Blocked, Completed, Disconnected, Failed,


NotStarted, Running, Stopped, Stopping, Suspended,
Suspending

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf

Shows what would happen if Remove-Job runs. The cmdlet isn't run.

Type: SwitchParameter

Aliases: wi

Position: Named
Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
Job

You can pipe a Job object to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
Windows PowerShell includes the following aliases for Remove-Job :

rjb

A PowerShell job creates a new process. When the job completes, the process exits.
When Remove-Job
is run, the job's state is removed.

If a job stops before completion and its process hasn't exited, the process is forcibly
terminated.

Related Links
about_Jobs
about_Job_Details
about_Remote_Jobs
Get-Job
Invoke-Command
Receive-Job
Resume-Job
Start-Job
Stop-Job
Suspend-Job
Wait-Job
Remove-Module
Reference
Module: Microsoft.PowerShell.Core

Removes modules from the current session.

Syntax
PowerShell

Remove-Module

[-Name] <String[]>

[-Force]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-Module

[-FullyQualifiedName] <ModuleSpecification[]>

[-Force]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-Module

[-ModuleInfo] <PSModuleInfo[]>

[-Force]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Remove-Module cmdlet removes the members of a module, such as cmdlets and
functions, 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.
This cmdlet does not uninstall the module or delete it from the computer. It affects only
the
current PowerShell session.

Examples

Example 1: Remove a module


PowerShell

Remove-Module -Name "BitsTransfer"

This command removes the BitsTransfer module from the current session.

Example 2: Remove all modules


PowerShell

Get-Module | Remove-Module

This command removes all modules from the current session.

Example 3: Remove modules by using the pipeline


PowerShell

"FileTransfer", "PSDiagnostics" | Remove-Module -Verbose

VERBOSE: Performing operation "Remove-Module" on Target "filetransfer (Path:


'C:\Windows\system32\WindowsPowerShell\v1.0\Modules\filetransfer\filetransfe
r.psd1')".

VERBOSE: Performing operation "Remove-Module" on Target


"Microsoft.BackgroundIntelligentTransfer.Management (Path:
'C:\Windows\assembly\GAC_MSIL\Microsoft.BackgroundIntelligentTransfer.Manage
ment\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\psdiagnost
ics.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\PSDiagnost
ics.psm1')".

This command removes the BitsTransfer 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: Remove a module by using ModuleInfo


PowerShell

$a = Get-Module BitsTransfer

Remove-Module -ModuleInfo $a

This command uses the ModuleInfo parameter to remove the BitsTransfer module.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False


Accept wildcard characters: False

-Force

Indicates that this cmdlet removes read-only modules. By default, Remove-Module


removes only
read-write modules.

The ReadOnly and ReadWrite values are stored in AccessMode property of a


module.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-FullyQualifiedName

The value can be a module name, a full module specification, or a path to a module
file.

When the value is a path, the path can be fully qualified or relative. A relative path is
resolved
relative to the script that contains the using statement.

When the value is a name or module specification, PowerShell searches the


PSModulePath for the
specified module.

A module specification is a hashtable that has the following keys.

ModuleName - Required Specifies the module name.


GUID - Optional Specifies the GUID of the module.

It's also Required to specify at least one of the three below keys.
ModuleVersion - Specifies a minimum acceptable version of the module.

MaximumVersion - Specifies the maximum acceptable version of the module.

RequiredVersion - Specifies an exact, required version of the module. This


can't be used with
the other Version keys.

Type: ModuleSpecification[]

Position: 0
Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-ModuleInfo

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 .

Type: PSModuleInfo[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies the names of modules to remove. Wildcard characters are permitted. You
can also pipe name
strings to Remove-Module .

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False


Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a module name to this cmdlet.

PSModuleInfo

You can pipe a module object to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
Windows PowerShell includes the following aliases for Remove-Module :

rmo

Related Links
Get-Module
Import-Module
about_Modules
Remove-PSSession
Reference
Module: Microsoft.PowerShell.Core

Closes one or more PowerShell sessions (PSSessions).

Syntax
PowerShell

Remove-PSSession

[-Id] <Int32[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-PSSession

[-Session] <PSSession[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-PSSession

-ContainerId <String[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-PSSession

-VMId <Guid[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-PSSession

-VMName <String[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-PSSession

-InstanceId <Guid[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-PSSession

-Name <String[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-PSSession

[-ComputerName] <String[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Remove-PSSession cmdlet closes 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,
this cmdlet 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.

Examples
Example 1: Remove sessions by ID
PowerShell

Remove-PSSession -Id 1, 2

This command removes the PSSessions that have IDs 1 and 2 .

Example 2: Remove all the sessions in the current session


PowerShell

Get-PSSession | Remove-PSSession

Remove-PSSession -Session (Get-PSSession)

$s = Get-PSSession

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: Close sessions by name


PowerShell

$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: Close sessions connected to a port


PowerShell

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: Close a session by instance ID


PowerShell

Get-PSSession | Format-Table ComputerName, InstanceID -AutoSize

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

Remove-PSSession -InstanceID fc4e9dfa-f246-452d-9fa3-1adbdd64ae85

These commands show how to close a PSSession based on its instance ID, or
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, which
formats their ComputerName and InstanceID properties in a table. The
AutoSize parameter
compresses the columns for display.

From the resulting display, you 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: Create a function that deletes all sessions in


the current session
PowerShell

Function EndPSS { Get-PSSession | Remove-PSSession }

This function closes every PSSession in the current session. After you add this function
to your
PowerShell profile, to delete all sessions, type EndPSS .

Parameters
-ComputerName
Specifies an array of names of computers. This cmdlet closes the PSSessions that are
connected
to the specified computers. Wildcard characters 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 ( . ).

Type: String[]

Aliases: Cn

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-ContainerId

Specifies an array of IDs of containers. This cmdlet removes sessions for each of the
specified
containers. Use the docker ps command to get a list of container IDs. For
more information, see
the help for the docker ps command.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: True


Accept wildcard characters: False

-Id

Specifies an array of IDs of sessions. This cmdlet 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 in the current
session. To find
the ID of a PSSession, run the Get-PSSession cmdlet without
parameters.

Type: Int32[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-InstanceId

Specifies an array of instance IDs. This cmdlet closes the PSSessions that have the
specified
instance IDs.

The instance ID is a GUID that uniquely identifies a PSSession in the current session.
The
instance ID is unique, even when you have multiple sessions running on a single
computer.

The instance ID 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 .

Type: Guid[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False


-Name

Specifies an array of friendly names of sessions. This cmdlet closes the PSSessions
that have
the specified friendly names. Wildcard characters are permitted.

Because the friendly name of a PSSession might not be unique, when you use the
Name
parameter, consider also using the WhatIf or Confirm parameter in the
Remove-PSSession
command.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-Session

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 .

Type: PSSession[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-VMId

Specifies an array of ID of virtual machines. This cmdlet starts an interactive session


with each of
the specified virtual machines. To see the virtual machines that are
available to you, use the
following command:

Get-VM | Select-Object -Property Name, ID

Type: Guid[]

Aliases: VMGuid
Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-VMName

Specifies an array of names of virtual machines. This cmdlet starts an interactive


session with each
of the specified virtual machines. To see the virtual machines that
are available to you, use the
Get-VM cmdlet.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSSession

You can pipe a session object to this cmdlet.


Outputs
None

This cmdlet returns no output.

Notes
Windows PowerShell includes the following aliases for Remove-PSSession :

rsn

The Id parameter is mandatory. 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, type
Get-Help 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.

Related Links
Connect-PSSession
Disconnect-PSSession
Enter-PSSession
Exit-PSSession
Get-PSSession
Invoke-Command
New-PSSession
Receive-PSSession
about_PSSessions
about_Remote
Remove-PSSnapin
Reference
Module: Microsoft.PowerShell.Core

Removes Windows PowerShell snap-ins from the current session.

Syntax
PowerShell

Remove-PSSnapin

[-Name] <String[]>

[-PassThru]

[-WhatIf]

[-Confirm]

[<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
You cannot use this cmdlet to
remove the snap-ins that are installed with Windows
PowerShell.

After you remove a snap-in from the current session, the snap-in is still loaded, but the
cmdlets
and providers in the snap-in are no longer available in the session.

Examples

Example 1: Remove a snap-in


PowerShell

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: Remove snap-ins by using names with the
pipeline
PowerShell

Get-PSSnapIn smp* | Remove-PSSnapIn

This command removes the Windows PowerShell snap-ins that have names that start
with smp from the
current session.

The command uses the Get-PSSnapin cmdlet to get objects that represent 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: Remove snap-ins by using names


PowerShell

Remove-PSSnapin -Name *event*

This command removes all Windows PowerShell snap-ins that have names that include
event.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False


Accept wildcard characters: False

-Name

Specifies the names of Windows PowerShell snap-ins to remove from the current
session.
Wildcard characters ( * ) are permitted.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-PassThru

Returns an object that represents the snap-in. By default, this cmdlet does not
generate any output.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


Inputs
PSSnapInInfo

You can pipe a snap-in object to this cmdlet.

Outputs
None, System.Management.Automation.PSSnapInInfo

This cmdlet generates a System.Management.Automation.PSSnapInInfo object that


represents the
snap-in, if you specify the PassThru parameter. By default, Remove-
PSSnapin does not generate
any output.

Notes
Windows PowerShell includes the following aliases for Remove-PSSnapin :

rsnp

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, type Get-
Help about_Profiles .

Related Links
Add-PSSnapin
Get-PSSnapin
Resume-Job
Reference
Module: Microsoft.PowerShell.Core

Restarts a suspended job.

Syntax
PowerShell

Resume-Job

[-Wait]

[-Id] <Int32[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Resume-Job

[-Job] <Job[]>

[-Wait]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Resume-Job

[-Wait]

[-Name] <String[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Resume-Job

[-Wait]

[-InstanceId] <Guid[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]
PowerShell

Resume-Job

[-Wait]

[-State] <JobState>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Resume-Job

[-Wait]

[-Filter] <Hashtable>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Resume-Job cmdlet resumes a workflow job that was suspended, such as by using
the
Suspend-Job cmdlet or the about_Suspend-Workflow
activity. When a workflow job
resumes, the job engine reconstructs the state, metadata, and output
from saved
resources, such as checkpoints. The job is restarted without any loss of state or data.
The
job state is changed from Suspended to Running.

Use the parameters of Resume-Job to select jobs by name, ID, instance ID or pipe a job
object,
such as one returned by the Get-Job cmdlet, to Resume-Job . You can also use a
property filter to
select a job to be resumed.

By default, Resume-Job returns immediately, even though all jobs might not yet be
resumed. To
suppress the command prompt until all specified jobs are resumed, use the
Wait parameter.

The Resume-Job cmdlet works only on custom job types, such as workflow jobs. It does
not work on
standard background jobs, such as those that are started by using the
Start-Job cmdlet. If you
submit a job of an unsupported type, Resume-Job generates a
terminating error and stops running.

To identify a workflow job, look for a value of PSWorkflowJob in the PSJobTypeName


property
of the job. To determine whether a particular custom job type supports the
Resume-Job cmdlet, see
the help topics for the custom job type.
Before using a Job cmdlet on a custom job type, import the module that supports the
custom job type,
either by using the Import-Module cmdlet or getting or using a cmdlet
in the module.

This cmdlet was introduced in Windows PowerShell 3.0.

Examples

Example 1: Resume a job by ID


The commands in this example verify that the job is a suspended workflow job and then
resume the
job. The first command uses the Get-Job cmdlet to get the job. The output
shows that the job is a
suspended workflow job. The second command uses the Id
parameter of the Resume-Job cmdlet to
resume the job with an Id value of 4.

PowerShell

PS C:\> Get-Job EventJob

Id Name PSJobTypeName State HasMoreData


Location Command

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


- -------

4 EventJob PSWorkflowJob Suspended True


Server01 \\Script\Share\Event.ps1

PS C:\> Resume-Job -Id 4

Example 2: Resume a job by name


This command uses the Name parameter to resume several workflow jobs on the local
computer.

PowerShell

PS C:\> Resume-Job -Name WorkflowJob, InventoryWorkflow, WFTest*

Example 3: Use custom property values


This command uses the value of a custom property to identify the workflow job to
resume. It uses the
Filter parameter to identify the workflow job by its CustomID
property. It also uses the
State parameter to verify that the workflow job is suspended,
before it tries to resume it.
PowerShell

PS C:\> Resume-Job -Filter @{CustomID="T091291"} -State Suspended

Example 4: Resume all suspended jobs on a remote


computer
This command resumes all suspended jobs on the Srv01 remote computer.

PowerShell

PS C:\> Invoke-Command -ComputerName Srv01 -ScriptBlock {Get-Job -State


Suspended | Resume-Job}

The command uses the Invoke-Command cmdlet to run a command on the Srv01
computer. The remote
command uses the State parameter of the Get-Job cmdlet to get
all suspended jobs on the
computer. A pipeline operator ( | ) sends the suspended jobs
to the Resume-Job cmdlet, which
resumes them.

Example 5: Wait for jobs to resume


This command uses the Wait parameter to direct Resume-Job to return only after all
specified
jobs are resumed. The Wait parameter is especially useful in scripts that
assume that jobs are
resumed before the script continues.

PowerShell

PS C:\> Resume-Job -Name WorkflowJob, InventoryWorkflow, WFTest* -Wait

Example 6: Resume a workflow that suspends itself


This code sample shows the Suspend-Workflow activity in a workflow.

The Test-Suspend workflow on the Server01 computer. When you run the workflow, the
workflow runs
the Get-Date activity and stores the result in the $a variable. Then it runs
the
Suspend-Workflow activity. In response, it takes a checkpoint, suspends the workflow,
and returns
a workflow job object. Suspend-Workflow returns a workflow job object even
if the workflow is not
explicitly run as a job.
Resume-Job resumes the Test-Suspend workflow in Job8. It uses the Wait parameter to

hold the
command prompt until the job is resumed.

The Receive-Job cmdlet gets the results of the Test-Suspend workflow. The final
command in the
workflow returns a TimeSpan object that represents the elapsed time
between the current date and
time and the date and time that was saved in the $a
variable before the workflow was suspended.

PowerShell

#SampleWorkflow

Workflow Test-Suspend

$a = Get-Date

Suspend-Workflow

(Get-Date)- $a

PS C:\> Test-Suspend -PSComputerName Server01

Id Name PSJobTypeName State HasMoreData


Location Command

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


- -------

8 Job8 PSWorkflowJob Suspended True


Server01 Test-Suspend

PS C:\> Resume-Job -Name "Job8" -Wait

Id Name PSJobTypeName State HasMoreData


Location Command

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


- -------

8 Job8 PSWorkflowJob Running True


Server01 Test-Suspend

PS C:\> Receive-Job -Name Job8

Days : 0

Hours : 0

Minutes : 0

Seconds : 19

Milliseconds : 823

Ticks : 198230041

TotalDays : 0.000229432917824074

TotalHours : 0.00550639002777778

TotalMinutes : 0.330383401666667

TotalSeconds : 19.8230041

TotalMilliseconds : 19823.0041

PSComputerName : Server01

The Resume-Job cmdlet lets you resume a workflow job that was suspend by using the
Suspend-Workflow activity. This activity suspends a workflow from within a workflow. It is
valid
only in workflows.

For information about the Suspend-Workflow , see


about_Suspend-Workflow]
(../PSWorkflow/about/about_Suspend-Workflow.md).

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Filter

Specifies a hash table of conditions. This cmdlet resumes jobs that satisfy all of the
conditions in
the hash table. Enter a hash table where the keys are job properties and
the values are job property
values.

Type: Hashtable

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Id

Specifies an array of IDs for jobs that this cmdlet resumes.

The ID is an integer that uniquely identifies the job in the current session. It is easier
to
remember and to type than the instance ID, but it is unique only in the current
session. You can
type one or more IDs, separated by commas. To find the ID of a job,
run Get-Job .

Type: Int32[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-InstanceId

Specifies an array of instance IDs of jobs that this cmdlet resumes. 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, run Get-Job .

Type: Guid[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Job

Specifies the jobs to be resumed. Enter a variable that contains the jobs or a
command that gets the
jobs. You can also pipe jobs to the Resume-Job cmdlet.

Type: Job[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name
Specifies an array of friendly names of jobs that this cmdlet resumes. Enter one or
more job names.
Wildcard characters are permitted.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-State

Specifies the state of jobs to resume. The acceptable values for this parameter are:

NotStarted
Running
Completed
Failed
Stopped
Blocked
Suspended
Disconnected
Suspending
Stopping

This cmdlet resumes only jobs in the Suspended state.

For more information about job states, see


JobState Enumeration.

Type: JobState

Accepted values: NotStarted, Running, Completed, Failed, Stopped, Blocked,


Suspended, Disconnected, Suspending, Stopping,
AtBreakpoint

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Wait
Indicates that this cmdlet suppresses the command prompt until all job results are
restarted. By
default, this cmdlet immediately returns the available results.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
Job

You can pipe all types of jobs to this cmdlet. If Resume-Job gets a job of an unsupported
type, it
returns a terminating error.

Outputs
None, System.Management.Automation.Job

This cmdlet returns the jobs that it tries to resume, if you use the PassThru parameter.
Otherwise, this cmdlet does not generate any output.

Notes
Windows PowerShell includes the following aliases for Resume-Job :

rujb

Resume-Job can only resume jobs that are suspended. If you submit a job in a

different state,
Resume-Job runs the resume operation on the job, but generates a
warning to notify you that the
job could not be resumed. To suppress the warning,
use the WarningAction common parameter with
a value of SilentlyContinue.

If a job is not of a type that supports resuming, such as a workflow job


(PSWorkflowJob),
Resume-Job returns a terminating error.

The mechanism and location for saving a suspended job might vary depending on
the job type. For
example, suspended workflow jobs are saved in a flat file store by
default, but can also be saved
in a SQL database.

When you resume a job, the job state changes from Suspended to Running. To
find the jobs
that are running, including those that were resumed by this cmdlet,
use the State parameter of
the Get-Job cmdlet to get jobs in the Running state.

Some job types have options or properties that prevent Windows PowerShell from
suspending the job.
If attempts to suspend the job fail, verify that the job options
and properties allow for
suspending.

Related Links
Get-Job
Receive-Job
Remove-Job
Start-Job
Stop-Job
Suspend-Job
Wait-Job
Save-Help
Reference
Module: Microsoft.PowerShell.Core

Downloads and saves the newest help files to a file system directory.

Syntax
PowerShell

Save-Help

[-DestinationPath] <String[]>
[[-Module] <PSModuleInfo[]>]

[-FullyQualifiedModule <ModuleSpecification[]>]

[[-UICulture] <CultureInfo[]>]

[-Credential <PSCredential>]

[-UseDefaultCredentials]

[-Force]

[<CommonParameters>]

PowerShell

Save-Help

-LiteralPath <String[]>

[[-Module] <PSModuleInfo[]>]

[-FullyQualifiedModule <ModuleSpecification[]>]

[[-UICulture] <CultureInfo[]>]

[-Credential <PSCredential>]

[-UseDefaultCredentials]

[-Force]

[<CommonParameters>]

Description
The Save-Help cmdlet downloads the newest help files for PowerShell modules and
saves them to a
directory that you specify. This feature lets you update the help files on
computers that do not
have access to the Internet, and makes it easier to update the
help files on multiple computers.

In Windows PowerShell 3.0, Save-Help worked only for modules that are installed on the
local
computer. Although it was possible to import a module from a remote computer,
or obtain a reference
to a PSModuleInfo object from a remote computer by using
PowerShell remoting, the
HelpInfoUri property was not preserved, and Save-Help would
not work for remote module Help.

In Windows PowerShell 4.0, the HelpInfoUri property is preserved over PowerShell


remoting, which
enables Save-Help to work for modules that are installed on remote
computers. It is also possible
to save a PSModuleInfo object to disk or removable media
by running Export-Clixml on a
computer that does not have Internet access, import the
object on a computer that does have Internet
access, and then run Save-Help on the
PSModuleInfo object. The saved help can be transported
to the remote computer by
using removable storage media, such as a USB drive. The help can be
installed on the
remote computer by running Update-Help . This process can be used to install help
on
computers that do not have any kind of network access.

To install saved help files, run the Update-Help cmdlet. Add its SourcePath parameter to
specify the folder in which you saved the Help files.

Without parameters, a Save-Help command downloads the newest help for all modules
in the session
and for modules that are installed on the computer in a location listed in
the PSModulePath
environment variable. This action skips modules that do not support
Updatable Help without warning.

The Save-Help cmdlet checks the version of any help files in the destination folder. If
newer help
files are available, this cmdlet downloads the newest help files from the
Internet, and then saves
them in the folder. The Save-Help cmdlet works just like the
Update-Help cmdlet, except that it
saves the downloaded cabinet (.cab) files, instead of
extracting the help files from the cabinet
files and installing them on the computer.

The saved help for each module consists of one help information (HelpInfo XML) file
and one cabinet
(.cab) file for the help files each UI culture. You do not have to extract
the help files from the
cabinet file. The Update-Help cmdlet extracts the help files,
validates the XML for safety, and
then installs the help files and the help information file
in a language-specific subfolder of the
module folder.

To save the help files for modules in the PowerShell installation folder ( $pshome\Modules ),
start
PowerShell by using the Run as administrator option. You must be a member of the
Administrators
group on the computer to download the help files for these modules.

This cmdlet was introduced in Windows PowerShell 3.0.

Examples
Example 1: Save the help for the DhcpServer module
PowerShell

# Option 1: Run Invoke-Command to get the PSModuleInfo object for the remote
DHCP Server module,

# save the PSModuleInfo object in the variable $m, and then run Save-Help.

$m = Invoke-Command -ComputerName RemoteServer -ScriptBlock { Get-Module -


Name DhcpServer -ListAvailable }

Save-Help -Module $m -DestinationPath "C:\SavedHelp"

# Option 2: Open a PSSession--targeted at the remote computer that is


running the DhcpServer

# module--to get the PSModuleInfo object for the remote module, and then run
Save-Help.

$s = New-PSSession -ComputerName "RemoteServer"

$m = Get-Module -PSSession $s -Name "DhcpServer" -ListAvailable

Save-Help -Module $m -DestinationPath "C:\SavedHelp"

# Option 3: Open a CIM session--targeted at the remote computer that is


running the DhcpServer

# module--to get the PSModuleInfo object for the remote module, and then run
Save-Help.

$c = New-CimSession -ComputerName "RemoteServer"

$m = Get-Module -CimSession $c -Name "DhcpServer" -ListAvailable

Save-Help -Module $m -DestinationPath "C:\SavedHelp"

This example shows three different ways to use Save-Help to save the help for the
DhcpServer
module from an Internet-connected client computer, without installing the
DhcpServer module or
the DHCP Server role on the local computer.

Example 2: Install help for the DhcpServer module


PowerShell

# First, run Export-CliXml to export the PSModuleInfo object to a shared


folder or to removable media.

$m = Get-Module -Name "DhcpServer" -ListAvailable

Export-CliXml -Path "E:\UsbFlashDrive\DhcpModule.xml" -InputObject $m

# Next, transport the removable media to a computer that has Internet


access, and then import the

# PSModuleInfo object with Import-CliXml. Run Save-Help to save the Help for
the imported DhcpServer

# module PSModuleInfo object.

$deserialized_m = Import-CliXml "E:\UsbFlashDrive\DhcpModule.xml"

Save-Help -Module $deserialized_m -DestinationPath


"E:\UsbFlashDrive\SavedHelp"

# Finally, transport the removable media back to the computer that does not
have network access, and

# then install the help by running Update-Help.

Update-Help -Module DhcpServer -SourcePath "E:\UsbFlashDrive\SavedHelp"

This example shows how to install help that you saved in Example 1 for the DhcpServer
module on
a computer that does not have Internet access.

Example 3: Save help for all modules


PowerShell

Save-Help -DestinationPath "\\Server01\FileShare01"

This command downloads the newest help files for all modules in the UI culture set for
Windows on
the local computer. It saves the help files in the \\Server01\Fileshare01
folder.

Example 4: Save help for a module on the computer


PowerShell

Save-Help -Module ServerManager -DestinationPath "\\Server01\FileShare01" -


Credential Domain01/Admin01

This command downloads the newest help files for the ServerManager module, and
then saves them
in the \\Server01\Fileshare01 folder.

When a module is installed on the computer, you can type the module name as the
value of the
Module parameter, even if the module is not imported into the current
session.

The command uses the Credential parameter to supply the credentials of a user who
has permission
to write to the file share.
Example 5: Save help for a module on a different
computer
PowerShell

Invoke-Command -ComputerName Server02 {Get-Module -Name CustomSQL -


ListAvailable} | Save-Help -DestinationPath \\Server01\FileShare01 -
Credential Domain01\Admin01

These commands download the newest help files for the CustomSQL module and save
them in the
\\Server01\Fileshare01 folder.

Because the CustomSQL module is not installed on the computer, the sequence
includes an
Invoke-Command command that gets the module object for the CustomSQL
module from the Server02
computer and then pipes the module object to the Save-
Help cmdlet.

When a module is not installed on the computer, Save-Help needs the module object,
which includes
information about the location of the newest help files.

Example 6: Save help for a module in multiple languages


PowerShell

Save-Help -Module Microsoft.PowerShell* -UICulture de-DE, en-US, fr-FR, ja-


JP -DestinationPath "D:\Help"

This command saves help for the core PowerShell modules in four different UI cultures.
The language
packs for these locales do not have to be installed on the computer.

Save-Help can download help files for modules in different UI cultures only when the

module owner
makes the translated files available on the Internet.

Example 7: Save help more than one time each day


PowerShell

Save-Help -Force -DestinationPath "\\Server3\AdminShare\Help"

This command saves help for all modules that are installed on the computer. The
command specifies
the Force parameter to override the rule that prevents the Save-
Help cmdlet from downloading
help more than once in each 24-hour period.
The Force parameter also overrides the 1 GB restriction and circumvents version
checking.
Therefore, you can download files even if the version is not later than the
version in the
destination folder.

The command uses the Save-Help cmdlet to download and save the help files to the
specified folder.
The Force parameter is required when you have to run a Save-Help
command more than one time
each day.

Parameters
-Credential

Specifies a user credential. This cmdlet runs the command by using credentials of a
user who has
permission to access the file system location specified by the
DestinationPath parameter. This
parameter is valid only when the DestinationPath
or LiteralPath parameter is used in the
command.

This parameter enables you to run Save-Help commands that use the
DestinationPath parameter on
remote computers. By providing explicit credentials,
you can run the command on a remote computer
and access a file share on a third
computer without encountering an access denied error or using
CredSSP
authentication to delegate credentials.

Type a user name, such as User01 or Domain01\User01, or enter a PSCredential


object
generated by the Get-Credential cmdlet. If you type a user name, you're
prompted to enter the
password.

Credentials are stored in a PSCredential


object and the password is stored as a
SecureString.

7 Note

For more information about SecureString data protection, see


How secure is
SecureString?.

Type: PSCredential

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-DestinationPath

Specifies the path of the folder in which the help files are saved. Do not specify a file
name or
file name extension.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Force

Indicates that this cmdlet does not follow the once-per-day limitation, skips version
checking, and
downloads files that exceed the 1 GB limit.

Without this parameter, only one Save-Help command for each module is permitted
in each 24-hour
period, downloads are limited to 1 GB of uncompressed content per
module, and help files for a
module are installed only when they are newer than the
files on the computer.

The once-per-day limit protects the servers that host the help files, and makes it
practical for you
to add a Save-Help command to your PowerShell profile.

To save help for a module in multiple UI cultures without the Force parameter,
include all UI
cultures in the same command, such as:
Save-Help -Module
PSScheduledJobs -UICulture en-US, fr-FR, pt-BR

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-FullyQualifiedModule
The value can be a module name, a full module specification, or a path to a module
file.

When the value is a path, the path can be fully qualified or relative. A relative path is
resolved
relative to the script that contains the using statement.

When the value is a name or module specification, PowerShell searches the


PSModulePath for the
specified module.

A module specification is a hashtable that has the following keys.

ModuleName - Required Specifies the module name.

GUID - Optional Specifies the GUID of the module.


It's also Required to specify at least one of the three below keys.
ModuleVersion - Specifies a minimum acceptable version of the module.

MaximumVersion - Specifies the maximum acceptable version of the module.


RequiredVersion - Specifies an exact, required version of the module. This

can't be used with


the other Version keys.

You can't specify the FullyQualifiedModule parameter in the same command as a


Module
parameter. the two parameters are mutually exclusive.

Type: ModuleSpecification[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-LiteralPath

Specifies a path of the destination folder. Unlike the value of the DestinationPath
parameter,
the value of the LiteralPath parameter is used exactly as it is typed. No
characters are
interpreted as wildcard characters. If the path includes escape
characters, enclose it in single
quotation marks. Single quotation marks tell
PowerShell not to interpret any characters as escape
sequences.

Type: String[]

Aliases: PSPath

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Module

Specifies modules for which this cmdlet downloads help. Enter one or more module
names or name
patters in a comma-separated list or in a file that has one module
name on each line. Wildcard
characters are permitted. You can also pipe module
objects from the Get-Module cmdlet to
Save-Help .

By default, Save-Help downloads help for all modules that support Updatable Help
and are installed
on the local computer in a location listed in the PSModulePath
environment variable.

To save help for modules that are not installed on the computer, run a Get-Module
command on a
remote computer. Then pipe the resulting module objects to the
Save-Help cmdlet or submit the
module objects as the value of the Module or

InputObject parameters.

If the module that you specify is installed on the computer, you can enter the
module name or a
module object. If the module is not installed on the computer,
you must enter a module object, such
as one returned by the Get-Module cmdlet.

The Module parameter of the Save-Help cmdlet does not accept the full path of a
module file or
module manifest file. To save help for a module that is not in a
PSModulePath location, import
the module into the current session before you run
the Save-Help command.

A value of "*" (all) attempts to update help for all modules that are installed on the
computer.
This includes modules that do not support Updatable Help. This value
might generate errors when the
command encounters modules that do not support
Updatable Help.

Type: PSModuleInfo[]

Aliases: Name

Position: 1

Default value: None

Accept pipeline input: True


Accept wildcard characters: True

-UICulture

Specifies UI culture values for which this cmdlet gets updated help files. Enter one or
more
language codes, such as es-ES , a variable that contains culture objects, or a
command that gets
culture objects, such as a Get-Culture or Get-UICulture
command.

Wildcard characters are not permitted. Do not specify a partial language code, such
as "de".

By default, Save-Help gets help files in the UI culture set for Windows or its fallback
culture.
If you specify the UICulture parameter, Save-Help looks for help only for the
specified UI
culture, not in any fallback culture.

Type: CultureInfo[]

Position: 2

Default value: Current UI culture

Accept pipeline input: False

Accept wildcard characters: False

-UseDefaultCredentials

Indicates that this cmdlet runs the command, including the web download, with the
credentials of the
current user. By default, the command runs without explicit
credentials.

This parameter is effective only when the web download uses NTLM, negotiate, or
Kerberos-based
authentication.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


Inputs
PSModuleInfo

You can pipe a module object to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
To save help for modules in the $pshome\Modules folder, start PowerShell by
using the Run as
administrator option. Only members of the Administrators group
on the computer can download help
for modules in the $pshome\Modules folder.
The saved help for each module consists of one help information (HelpInfo XML)
file and one
cabinet (.cab) file for the help files each UI culture. You do not have to
extract the help files
from the cabinet file. The Update-Help cmdlet extracts the
help files, validates the XML, and
then installs the help files and the help
information file in a language-specific subfolder of the
module folder.
The Save-Help cmdlet can save help for modules that are not installed on the
computer. However,
because help files are installed in the module folder, the
Update-Help cmdlet can install
updated help file only for modules that are installed
on the computer.
If Save-Help cannot find updated help files for a module, or cannot find updated
help files in
the specified language, it continues silently without displaying an error
message. To see which
files were saved by the command, specify the Verbose
parameter.
Modules are the smallest unit of updatable help. You cannot save help for a
particular cmdlet,
only for all cmdlets in module. To find the module that contains
a particular cmdlet, use the
ModuleName property together with the Get-Command
cmdlet, for example,
(Get-Command \<cmdlet-name\>).ModuleName
Save-Help supports all modules and the core PowerShell snap-ins. It does not
support any other
snap-ins.
The Update-Help and Save-Help cmdlets use the following ports to download help
files: Port 80
for HTTP and port 443 for HTTPS.
The Update-Help and Save-Help cmdlets are not supported on Windows
Preinstallation Environment
(Windows PE).
Related Links
Get-Help
Get-Module
Update-Help
Set-PSDebug
Reference
Module: Microsoft.PowerShell.Core

Turns script debugging features on and off, sets the trace level, and toggles strict mode.

Syntax
PowerShell

Set-PSDebug

[-Trace <Int32>]

[-Step]

[-Strict]

[<CommonParameters>]

PowerShell

Set-PSDebug

[-Off]

[<CommonParameters>]

Description
The Set-PSDebug cmdlet turns script debugging features on and off, sets the trace level,
and
toggles strict mode. By default, the PowerShell debug features are off.

When the Trace parameter has a value of 1 , each line of script is traced as it runs. When
the
parameter has a value of 2 , variable assignments, function calls, and script calls are
also
traced. If the Step parameter is specified, you're prompted before each line of the
script runs.

Examples

Example 1: Set the trace level


This example sets the trace level to 2 , and then runs a script that displays the numbers
1, 2, and
3.
PowerShell

Set-PSDebug -Trace 2; foreach ($i in 1..3) {$i}

DEBUG: 1+ Set-PSDebug -Trace 2; foreach ($i in >>>> 1..3) {$i}

DEBUG: ! SET $foreach = 'IEnumerator'.

DEBUG: 1+ Set-PSDebug -Trace 2; foreach ( >>>> $i in 1..3) {$i}

DEBUG: ! SET $i = '1'.

DEBUG: 1+ Set-PSDebug -Trace 2; foreach ($i in 1..3) { >>>> $i}

DEBUG: 1+ Set-PSDebug -Trace 2; foreach ( >>>> $i in 1..3) {$i}

DEBUG: ! SET $i = '2'.

DEBUG: 1+ Set-PSDebug -Trace 2; foreach ($i in 1..3) { >>>> $i}

DEBUG: 1+ Set-PSDebug -Trace 2; foreach ( >>>> $i in 1..3) {$i}

DEBUG: ! SET $i = '3'.

DEBUG: 1+ Set-PSDebug -Trace 2; foreach ($i in 1..3) { >>>> $i}

DEBUG: 1+ Set-PSDebug -Trace 2; foreach ( >>>> $i in 1..3) {$i}

DEBUG: ! SET $foreach = ''.

Example 2: Turn on stepping


This example turns on stepping, and then runs a script that displays the numbers 1, 2,
and 3.

PowerShell

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}

Example 3: Use strict mode


This example puts PowerShell in strict mode and attempts to access a variable that
doesn't have an
assigned value.

PowerShell

Set-PSDebug -Strict; $NewVar

The variable '$NewVar' cannot be retrieved because it has not been set.

At line:1 char:22

+ Set-PSDebug -Strict; $NewVar

Example 4: Turn off debug features


This example turns off all debugging features, and then runs a script that displays the
numbers 1,
2, and 3.

PowerShell

Set-PSDebug -Off; foreach ($i in 1..3) {$i}

Parameters
-Off

Turns off all script debugging features.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Step

Turns on script stepping. Before each line runs, PowerShell prompts you to stop,
continue, or enter
a new interpreter level to inspect the state of the script.

Specifying the Step parameter automatically sets a trace level of 1 .

Type: SwitchParameter

Position: Named

Default value: False


Accept pipeline input: False

Accept wildcard characters: False

-Strict

Specifies that variables must be assigned a value before being referenced in a script.
If a variable
is referenced before a value is assigned, PowerShell returns an exception
error. This is equivalent
to Set-StrictMode -Version 1 . For more information, see
Set-StrictMode.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Trace

Specifies the trace level for each line in a script. Each line is traced as it's run.

The acceptable values for this parameter are as follows:

0: Turn script tracing off.


1: Trace script lines as they run.
2: Trace script lines, variable assignments, function calls, and scripts.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.


Outputs
None

This cmdlet returns no output.

Related Links
about_Debuggers
Debug-Process
Set-PSBreakpoint
Set-StrictMode
Write-Debug
Set-PSSessionConfiguration
Reference
Module: Microsoft.PowerShell.Core

Changes the properties of a registered session configuration.

Syntax
PowerShell

Set-PSSessionConfiguration

[-Name] <String>

[-ApplicationBase <String>]

[-RunAsCredential <PSCredential>]

[-ThreadApartmentState <ApartmentState>]

[-ThreadOptions <PSThreadOptions>]

[-AccessMode <PSSessionConfigurationAccessMode>]

[-UseSharedProcess]

[-StartupScript <String>]

[-MaximumReceivedDataSizePerCommandMB <Double>]

[-MaximumReceivedObjectSizeMB <Double>]

[-SecurityDescriptorSddl <String>]

[-ShowSecurityDescriptorUI]

[-Force]

[-NoServiceRestart]

[-PSVersion <Version>]

[-SessionTypeOption <PSSessionTypeOption>]

[-TransportOption <PSTransportOption>]

[-ModulesToImport <Object[]>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Set-PSSessionConfiguration

[-Name] <String>

[-AssemblyName] <String>

[-ApplicationBase <String>]

[-ConfigurationTypeName] <String>

[-RunAsCredential <PSCredential>]

[-ThreadApartmentState <ApartmentState>]

[-ThreadOptions <PSThreadOptions>]

[-AccessMode <PSSessionConfigurationAccessMode>]

[-UseSharedProcess]

[-StartupScript <String>]

[-MaximumReceivedDataSizePerCommandMB <Double>]

[-MaximumReceivedObjectSizeMB <Double>]

[-SecurityDescriptorSddl <String>]

[-ShowSecurityDescriptorUI]

[-Force]

[-NoServiceRestart]

[-PSVersion <Version>]

[-SessionTypeOption <PSSessionTypeOption>]

[-TransportOption <PSTransportOption>]

[-ModulesToImport <Object[]>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Set-PSSessionConfiguration

[-Name] <String>

[-RunAsCredential <PSCredential>]

[-ThreadApartmentState <ApartmentState>]

[-ThreadOptions <PSThreadOptions>]

[-AccessMode <PSSessionConfigurationAccessMode>]

[-UseSharedProcess]

[-StartupScript <String>]

[-MaximumReceivedDataSizePerCommandMB <Double>]

[-MaximumReceivedObjectSizeMB <Double>]

[-SecurityDescriptorSddl <String>]

[-ShowSecurityDescriptorUI]

[-Force]

[-NoServiceRestart]

[-TransportOption <PSTransportOption>]

-Path <String>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Set-PSSessionConfiguration cmdlet changes the properties of the session
configurations on the
local computer.

Use the Name parameter to identify the session 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.

Starting in PowerShell 3.0, you can use a session configuration file to define a session
configuration. This feature provides a simple and discoverable method for setting and
changing the
properties of sessions that use the session configuration. To specify a
session configuration file,
use the Path parameter of Set-PSSessionConfiguration . For
information about session
configuration files, see
about_Session_Configuration_Files. For
information
about how to create and modify a session configuration file, see the
New-
PSSessionConfigurationFile cmdlet.

Session configurations define the environment of remote sessions (PSSessions) that


connect to
the local computer. Every PSSession uses a session configuration. The
session configuration
determines the features of the PSSession, such as the modules
that are available in the session,
the cmdlets that are permitted to run, the language
mode, quotas, and timeouts. The security
descriptor of the session configuration
determines who can use the session configuration to connect
to the local computer. For
more information about session configurations, see
about_Session_Configurations.

To see the properties of a session configuration, use the Get-PSSessionConfiguration


cmdlet or the
WSMan Provider. For more information about the WSMan Provider, type
Get-Help WSMan .

Examples

Example 1: Change the thread apartment state


PowerShell

PS C:\> 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: Create and change a session configuration


This example shows how to add and remove a startup script from a configuration.

The first command creates the AdminShell configuration. The second command adds
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.

PowerShell
Register-PSSessionConfiguration -Name "AdminShell" -AssemblyName
"C:\Shells\AdminShell.dll" -ConfigurationTypeName "AdminClass"

Set-PSSessionConfiguration -Name "AdminShell" -StartupScript


"AdminConfig.ps1"

Set-PSSessionConfiguration -Name "AdminShell" -StartupScript $Null

Example 3: Display results


This example increases the value of the MaximumReceivedObjectSizeMB property to
20 . This
command also prompts you to restart the WinRM service. The change is not

effective until the


WinRM service is restarted.

PowerShell

Set-PSSessionConfiguration -Name "IncObj" -MaximumReceivedObjectSizeMB 20

WSManConfig:
Microsoft.WSMan.Management\WSMan::localhost\Plugin\IncObj\InitializationPara
meters

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

Example 3: Display results in different ways


In this example, Set-PSSessionConfiguration changes the startup script in the
MaintenanceShell
session configuration to Maintenance.ps1 . The output shows the
change and prompts you to restart
the WinRM service. The response is y (yes).

Get-PSSessionConfiguration gets the MaintenanceShell session configuration. The

pipeline
operator ( | ) sends the results of the command to Format-List , which displays
all the properties
of the configuration object in a list. Next, using the WSMan provider,
we view the initialization
parameters for the MaintenanceShell configuration. Get-
ChildItem gets the child items in the
InitializationParameters node for the

MaintenanceShell plug-in. For more information about


the WSMan provider, type Get-
Help wsman .
PowerShell

Set-PSSessionConfiguration -Name "MaintenanceShell" -StartupScript "C:\ps-


test\Maintenance.ps1"

WSManConfig:
Microsoft.WSMan.Management\WSMan::localhost\Plugin\MaintenanceShell\Initiali
zationParameters

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

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 :

Get-ChildItem
WSMan:\localhost\Plugin\MaintenanceShell\InitializationParameters

ParamName ParamValue

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

PSVersion 2.0

startupscript c:\ps-test\Maintenance.ps1

Parameters
-AccessMode

Enables and disables the session configuration and determines whether it can be
used for remote or
local sessions on the computer. The acceptable values for this
parameter are:

Disabled . Disables the session configuration. It cannot be used for remote or


local access to
the computer. This value sets the Enabled property of the
session configuration
( WSMan:\<ComputerName>\PlugIn\
<SessionConfigurationName>\Enabled ) to False .

Local . Adds a Network_Deny_All entry to security descriptor of the session

configuration.
Users of the local computer can use the session configuration to
create a local loopback session
on the same computer, but remote users are
denied access.
Remote . Removes Deny_All and Network_Deny_All entries from the security

descriptors of
the session configuration. Users of local and remote computers
can use the session configuration
to create sessions and run commands on this
computer.

The default value is Remote.

Other cmdlets can override the value of this parameter later. For example, the
Enable-PSRemoting
cmdlet enables all session configurations on the computer and

permits remote access to them, and the


Disable-PSRemoting cmdlet permits only
local access to all session configurations on the computer.

This parameter was introduced in PowerShell 3.0.

Type: PSSessionConfigurationAccessMode

Accepted values: Disabled, Local, Remote

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ApplicationBase

Specifies the path of the assembly file ( *.dll ) that is specified in the value of the
AssemblyName parameter.

Type: String

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-AssemblyName

Specifies the assembly name. This cmdlet creates a session configuration based on a
class that is
defined in an assembly.

Enter the filename or full path of an assembly .dll file that defines a session
configuration. If
you enter only the file name, you can enter the path in the value of
the ApplicationBase
parameter.

Type: String

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ConfigurationTypeName

Specifies the type of the session configuration that is defined in the assembly in the
AssemblyName parameter. The type that you specify must implement the
System.Management.Automation.Remoting.PSSessionConfiguration class.

This parameter is required when you specify an assembly name.

Type: String

Position: 2

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter
Aliases: cf

Position: Named

Default value: False

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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-MaximumReceivedDataSizePerCommandMB

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

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. The
value of this
parameter is ignored.

Type: Nullable<T>[Double]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-MaximumReceivedObjectSizeMB
Specifies the limits on the amount of data that can be sent to this computer in any
single object.
Enter the data size in megabytes. The default is 10 .

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. The
value of this
parameter is ignored.

Type: Nullable<T>[Double]

Position: Named

Default value: 10

Accept pipeline input: False

Accept wildcard characters: False

-ModulesToImport

Specifies the modules and snap-ins that are automatically imported into sessions
that use the
session configuration. Enter the module and snap-in names.

By default, only the Microsoft.PowerShell.Core module is imported into sessions, but


unless the
cmdlets are excluded, you can use the Import-Module and Add-PSSnapin
cmdlets to add modules and
snap-ins to the session.

The modules specified in this parameter value are imported in additions to modules
specified in the
session configuration file ( New-PSSessionConfigurationFile ).
However, settings in the session
configuration file can hide the commands exported
by modules or prevent users from using them.

The modules specified in this parameter value replace the list of modules specified
with the
ModulesToImport parameter of the Register-PSSessionConfiguration
cmdlet.

This parameter was introduced in PowerShell 3.0.

Type: Object[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-Name

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.

Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-NoServiceRestart

Does not restart the WinRM service, and suppresses the prompt to restart the
service.

By default, when you run Set-PSSessionConfiguration , 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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Path

Specifies the path of a session configuration file ( .pssc ), such as one created by the
New-PSSessionConfigurationFile cmdlet. If you omit the path, the default is the

current directory.

For information about how to modify a session configuration file, see the help topic
for the
New-PSSessionConfigurationFile cmdlet.
This parameter was introduced in PowerShell 3.0.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-PSVersion

Specifies the version of PowerShell in sessions that use this session configuration.

The value of this parameter takes precedence over the value of the
PowerShellVersion key in the
session configuration file.

This parameter was introduced in PowerShell 3.0.

Type: Version

Aliases: PowerShellVersion

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RunAsCredential

Specifies credentials for commands in the session. By default, commands run with
the permissions of
the current user.

This parameter was introduced in PowerShell 3.0.

Type: PSCredential

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-SecurityDescriptorSddl

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.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SessionTypeOption

Specifies type-specific options for the session configuration. Enter a session type
options object,
such as the PSWorkflowExecutionOption object that the New-
PSWorkflowExecutionOption cmdlet
returns.

The options of sessions that use the session configuration are determined by the
values of session
options and the session configuration options. Unless specified,
options set in the session, such as
with the New-PSSessionOption cmdlet, take
precedence over options set in the session
configuration. However, session option
values cannot exceed maximum values set in the session
configuration.

This parameter was introduced in PowerShell 3.0.

Type: PSSessionTypeOption

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-ShowSecurityDescriptorUI

When this parameter is used the cmdlet opens a property sheet that helps you
create a new SDDL for
the session configuration. The property sheet appears after
you run the Set-PSSessionConfiguration
command and then restart the WinRM
service.

When you set 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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-StartupScript

Specifies the startup script for the configuration. Enter the fully qualified path of a
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 session. If the script
generates an
error, even a non-terminating error, the session is not created and the
New-PSSession command
fails.

Type: String

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-ThreadApartmentState

Specifies the apartment state of the threading module to be used. Acceptable values
are:

Unknown

MTA
STA

Type: ApartmentState

Accepted values: STA, MTA, Unknown

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ThreadOptions

Specifies the thread options setting in the configuration. This setting defines how
threads are
created and used when a command is executed in the session. The
acceptable values for this parameter
are:

Default

ReuseThread

UseCurrentThread
UseNewThread

The default value is UseCurrentThread .

For more information, see


PSThreadOptions Enumeration.

Type: PSThreadOptions

Accepted values: Default, UseNewThread, ReuseThread, UseCurrentThread

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-TransportOption

Specifies the transport options for the session configuration. Enter a transport
options object,
such as the WSManConfigurationOption object that the New-
PSTransportOption cmdlet returns.

The options of sessions that use the session configuration are determined by the
values of session
options and the session configuration options. Unless specified,
options set in the session, such as
with the New-PSSessionOption cmdlet, take
precedence over options set in the session
configuration. However, session option
values cannot exceed maximum values set in the session
configuration.

This parameter was introduced in PowerShell 3.0.

Type: PSTransportOption

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-UseSharedProcess

Use only one process to host all sessions that are started by the same user and use
the same session
configuration. By default, each session is hosted in its own process.

This parameter was introduced in PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
Microsoft.WSMan.Management.WSManConfigLeafElement

Notes
To run this cmdlet, start PowerShell by using the Run as administrator option.

The Set-PSSessionConfiguration cmdlet does not change the configuration name and
the WSMan
provider does not support the Rename-Item cmdlet. To change the name of
a session 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.

The properties of a session configuration object vary with the options set for the session
configuration and the values of those options. Also, session configurations that use a
session
configuration file have additional properties.
You can use commands in the WSMan: drive to change the properties of session
configurations.
However, you cannot use the WSMan: drive in PowerShell 2.0 to change
session configuration
properties that are introduced in PowerShell 3.0, such as
OutputBufferingMode. Windows
PowerShell 2.0 commands do not generate an error,
but they are ineffective. To change properties
introduced in PowerShell 3.0, use the
WSMan: drive in PowerShell 3.0 or later.

Related Links
Disable-PSSessionConfiguration
Enable-PSSessionConfiguration
Get-PSSessionConfiguration
New-PSSessionConfigurationFile
New-PSSessionOption
New-PSTransportOption
New-PSWorkflowExecutionOption
Register-PSSessionConfiguration
Test-PSSessionConfigurationFile
Unregister-PSSessionConfiguration
WSMan Provider
about_Session_Configurations
about_Session_Configuration_Files
Set-StrictMode
Reference
Module: Microsoft.PowerShell.Core

Establishes and enforces coding rules in expressions, scripts, and script blocks.

Syntax
PowerShell

Set-StrictMode

-Version <Version>

[<CommonParameters>]

PowerShell

Set-StrictMode

[-Off]

[<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, 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 the coding rules to enforce.

Set-PSDebug -Strict cmdlet turns on strict mode for the global scope. Set-StrictMode
affects
only the current scope and its child scopes. Then, you can use it in a script or
function to
override the setting inherited from the global scope.

When Set-StrictMode is off, PowerShell has the following behaviors:

Uninitialized variables are assumed to have a value of 0 (zero) or $Null ,


depending on type
References to non-existent properties return $Null
Results of improper function syntax vary with the error conditions
Attempting to retrieve a value using an invalid index in an array returns $Null
Examples

Example 1: Turn on strict mode as version 1.0


PowerShell

# Strict mode is off by default.

$a -gt 5

False

Set-StrictMode -Version 1.0

$a -gt 5

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

With strict mode set to version 1.0 , attempts to reference variables that aren't initialized
fail.

Example 2: Turn on strict mode as version 2.0


PowerShell

# Strict mode is off by default.

function add ($a, $b) {


'$a = ' + $a

'$b = ' + $b

'$a+$b = ' + ($a + $b)

add 3 4

$a = 3

$b = 4

$a+$b = 7

add(3,4)

$a = 3 4

$b =

$a+$b = 3 4

Set-StrictMode -Version 2.0

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

Set-StrictMode -Off

$string = "This is a string."

$null -eq $string.Month

True

Set-StrictMode -Version 2.0

$string = "This is a string."

$null -eq $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

This command turns strict mode on and sets it to version 2.0 . As a result, PowerShell
returns an
error if you use method syntax, which uses 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's 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's interpreted correctly as a reference error.

Example 3: Turn on strict mode as version 3.0


With strict mode set to Off, invalid or out of bounds indexes result return null values.

PowerShell

# Strict mode is off by default.

$a = @(1)

$null -eq $a[2]

$null -eq $a['abc']

True

True

Set-StrictMode -Version 3.0

$a = @(1)

$null -eq $a[2]

$null -eq $a['abc']

Index was outside the bounds of the array.

At line:1 char:1

+ $null -eq $a[2]

+ ~~~~~~~~~~~~~~~

+ CategoryInfo : OperationStopped: (:) [],


IndexOutOfRangeException

+ FullyQualifiedErrorId : System.IndexOutOfRangeException

Cannot convert value "abc" to type "System.Int32". Error: "Input string was
not in a correct format."

At line:1 char:1

+ $null -eq $a['abc']

+ ~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : InvalidArgument: (:) [], RuntimeException

+ FullyQualifiedErrorId : InvalidCastFromStringToInteger

With strict mode set to version 3 or higher, invalid or out of bounds indexes result in
errors.

Parameters
-Off

Indicates that this cmdlet turns strict mode off for the current scope and all child
scopes.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Version

Specifies the conditions that cause an error in strict mode. This parameter accepts
any valid
PowerShell version number. Any number higher than 3 is treated as
Latest . The value supplied
must be the string Latest or a string that can be

converted to a System.Version type. The


version must match a valid release version
of PowerShell.

The effective values for this parameter are:

1.0

Prohibits references to uninitialized variables, except for uninitialized


variables in strings.
2.0

Prohibits references to uninitialized variables. This includes uninitialized


variables in
strings.
Prohibits references to non-existent properties of an object.
Prohibits function calls that use the syntax for calling methods.
3.0

Prohibits references to uninitialized variables. This includes uninitialized


variables in
strings.
Prohibits references to non-existent properties of an object.
Prohibits function calls that use the syntax for calling methods.
Prohibit out of bounds or unresolvable array indexes.
Latest
Selects the latest version available. The latest version is the most strict. Use
this value to
make sure that scripts use the strictest available version, even
when new versions are added to
PowerShell.

U Caution

Using Latest for Version in scripts isn't deterministic. The meaning of Latest
can change
in new releases of PowerShell. A script written for an older version
of PowerShell that uses
Set-StrictMode -Version Latest is subject to more
restrictive rules when run in a newer version
of PowerShell.

Type: Version

Aliases: v

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
While the Version parameter accepts values greater than 3.0 , there are no additional
rules
defined for anything higher than 3.0 .

Set-StrictMode is effective only in the scope it's set in and in its child scopes. For more

information about scopes in PowerShell, see about_Scopes.

Related Links
Set-PSDebug
Start-Job
Reference
Module: Microsoft.PowerShell.Core

Starts a PowerShell background job.

Syntax
PowerShell

Start-Job

[-Name <String>]

[-ScriptBlock] <ScriptBlock>
[-Credential <PSCredential>]
[-Authentication <AuthenticationMechanism>]

[[-InitializationScript] <ScriptBlock>]

[-RunAs32]

[-PSVersion <Version>]

[-InputObject <PSObject>]

[-ArgumentList <Object[]>]

[<CommonParameters>]

PowerShell

Start-Job

[-DefinitionName] <String>

[[-DefinitionPath] <String>]
[[-Type] <String>]

[<CommonParameters>]

PowerShell

Start-Job

[-Name <String>]

[-Credential <PSCredential>]
[-FilePath] <String>

[-Authentication <AuthenticationMechanism>]

[[-InitializationScript] <ScriptBlock>]

[-RunAs32]

[-PSVersion <Version>]

[-InputObject <PSObject>]

[-ArgumentList <Object[]>]

[<CommonParameters>]

PowerShell
Start-Job

[-Name <String>]

[-Credential <PSCredential>]
-LiteralPath <String>

[-Authentication <AuthenticationMechanism>]

[[-InitializationScript] <ScriptBlock>]

[-RunAs32]

[-PSVersion <Version>]

[-InputObject <PSObject>]

[-ArgumentList <Object[]>]

[<CommonParameters>]

Description
The Start-Job cmdlet starts a PowerShell background job on the local computer.

A PowerShell background job runs a command without interacting with the current
session. When you
start a background job, a job object returns immediately, even if the
job takes an extended time to
finish. 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 doesn't contain the job
results.
When the job finishes, 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.

Starting in PowerShell 3.0, Start-Job can start instances of custom job types, such as
scheduled
jobs. For information about how to use Start-Job to start jobs with custom
types, see the help
documents for the job type feature.

The default working directory for jobs is hardcoded. The Windows default is
$HOME\Documents and on
Linux or macOS the default is $HOME . The script code running in

the background job needs to manage


the working directory as needed.

Examples

Example 1: Start a background job


This example starts a background job that runs on the local computer.
PowerShell

Start-Job -ScriptBlock { Get-Process -Name powershell }

Id Name PSJobTypeName State HasMoreData Location Command

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

1 Job1 BackgroundJob Running True localhost Get-Process -


Name powershell

Start-Job uses the ScriptBlock parameter to run Get-Process as a background job. The
Name parameter specifies to find PowerShell processes, powershell . The job
information is
displayed and PowerShell returns to a prompt while the job runs in the
background.

To view the job's output, use the Receive-Job cmdlet. For example, Receive-Job -Id 1 .

Example 2: Start a job using Invoke-Command


This example runs a job on multiple computers. The job is stored in a variable and is
executed by
using the variable name on the PowerShell command line.

PowerShell

$jobWRM = Invoke-Command -ComputerName (Get-Content -Path C:\Servers.txt) -


ScriptBlock {

Get-Service -Name WinRM } -JobName WinRM -ThrottleLimit 16 -AsJob

A job that uses Invoke-Command is created and stored in the $jobWRM variable. Invoke-
Command
uses the ComputerName parameter to specify the computers where the job

runs. Get-Content gets


the server names from the C:\Servers.txt file.

The ScriptBlock parameter specifies a command that Get-Service gets the WinRM
service. The
JobName parameter specifies a friendly name for the job, WinRM. The
ThrottleLimit
parameter limits the number of concurrent commands to 16. The AsJob
parameter starts a
background job that runs the command on the servers.

Example 3: Get job information


This example gets information about a job and displays the results of a completed job
that was run
on the local computer.

PowerShell
$j = Start-Job -ScriptBlock { Get-WinEvent -Log System } -Credential
Domain01\User01

$j | Select-Object -Property *

State : Completed

HasMoreData : True

StatusMessage :

Location : localhost

Command : Get-WinEvent -Log System

JobStateInfo : Completed

Finished : System.Threading.ManualResetEvent

InstanceId : 27ce3fd9-40ed-488a-99e5-679cd91b9dd3

Id : 18

Name : Job18

ChildJobs : {Job19}

PSBeginTime : 8/8/2019 14:41:57

PSEndTime : 8/8/2019 14:42:07

PSJobTypeName : BackgroundJob

Output : {}

Error : {}

Progress : {}

Verbose : {}

Debug : {}

Warning : {}

Information : {}

Start-Job uses the ScriptBlock parameter to run a command that specifies Get-
WinEvent to get
the System log. The Credential parameter specifies a domain user

account with permission to


run the job on the computer. The job object is stored in the
$j variable.

The object in the $j variable is sent down the pipeline to Select-Object . The Property
parameter specifies an asterisk ( * ) to display all the job object's properties.

Example 4: Run a script as a background job


In this example, a script on the local computer is run as a background job.

PowerShell

Start-Job -FilePath C:\Scripts\Sample.ps1

Start-Job uses the FilePath parameter to specify a script file that's stored on the local
computer.

Example 5: Get a process using a background job


This example uses a background job to get a specified process by name.

PowerShell

Start-Job -Name PShellJob -ScriptBlock { Get-Process -Name PowerShell }

Start-Job uses the Name parameter to specify a friendly job name, PShellJob. The
ScriptBlock parameter specifies Get-Process to get processes with the name
PowerShell.

Example 6: Collect and save data by using a background


job
This example starts a job that collects a large amount of map data and then saves it in a
.tif
file.

PowerShell

Start-Job -Name GetMappingFiles -InitializationScript {Import-Module


MapFunctions} -ScriptBlock {

Get-Map -Name * | Set-Content -Path D:\Maps.tif } -RunAs32

Start-Job uses the Name parameter to specify a friendly job name, GetMappingFiles.

The
InitializationScript parameter runs a script block that imports the MapFunctions
module. The
ScriptBlock parameter runs Get-Map and Set-Content saves the data in the
location specified
by the Path parameter. The RunAs32 parameter runs the process as
32-bit, even on a 64-bit
operating system.

Example 7: Pass input to a background job


This example uses the $input automatic variable to process an input object. Use
Receive-Job to
view the job's output.

PowerShell

Start-Job -ScriptBlock { Get-Content $input } -InputObject "C:\Servers.txt"

Receive-Job -Name Job45 -Keep

Server01

Server02

Server03

Server04
Start-Job uses the ScriptBlock parameter to run Get-Content with the $input

automatic
variable. The $input variable gets objects from the InputObject parameter.
Receive-Job uses
the Name parameter to specify the job and outputs the results. The

Keep parameter saves the


job output so it can be viewed again during the PowerShell
session.

Example 8: Use the ArgumentList parameter to specify an


array
This example uses the ArgumentList parameter to specify an array of arguments. The
array is a
comma-separated list of process names.

PowerShell

Start-Job -ScriptBlock { Get-Process -Name $args } -ArgumentList powershell,


pwsh, notepad

Id Name PSJobTypeName State HasMoreData Location


Command

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


-----

1 Job1 BackgroundJob Running True localhost


Get-Process -Name $args

The Start-Job cmdlet uses the ScriptBlock parameter to run a command. Get-Process
uses the
Name parameter to specify the automatic variable $args . The ArgumentList
parameter passes
the array of process names to $args . The process names powershell,
pwsh, and notepad are processes
running on the local computer.

To view the job's output, use the Receive-Job cmdlet. For example, Receive-Job -Id 1 .

Parameters
-ArgumentList

Specifies an array of arguments, or parameter values, for the script that is specified
by the
FilePath parameter or a command specified with the ScriptBlock parameter.

Arguments must be passed to ArgumentList as single-dimension array argument.


For example, a
comma-separated list. For more information about the behavior of
ArgumentList, see
about_Splatting.

Type: Object[]
Aliases: Args

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Authentication

Specifies the mechanism that is used to authenticate user credentials.

The acceptable values for this parameter are as follows:

Default
Basic
Credssp
Digest
Kerberos
Negotiate
NegotiateWithImplicitCredential

The default value is Default.

CredSSP authentication is available only in Windows Vista, Windows Server 2008,


and later versions
of the Windows operating system.

For more information about the values of this parameter, see


AuthenticationMechanism.

U Caution

Credential Security Support 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.

Type: AuthenticationMechanism

Accepted values: Default, Basic, Negotiate, NegotiateWithImplicitCredential,


Credssp, Digest, Kerberos
Position: Named

Default value: Default

Accept pipeline input: False

Accept wildcard characters: False

-Credential

Specifies a user account that has permission to perform this action. If the Credential
parameter
isn't specified, the command uses the current user's credentials.

Type a user name, such as User01 or Domain01\User01, or enter a PSCredential


object
generated by the Get-Credential cmdlet. If you type a user name, you're
prompted to enter the
password.

Credentials are stored in a PSCredential


object and the password is stored as a
SecureString.

7 Note

For more information about SecureString data protection, see


How secure is
SecureString?.

Type: PSCredential

Position: Named

Default value: Current user

Accept pipeline input: False

Accept wildcard characters: False

-DefinitionName

Specifies the definition name of the job that this cmdlet starts. Use this parameter to
start custom
job types that have a definition name, such as scheduled jobs.

When you use Start-Job to start an instance of a scheduled job, the job starts
immediately,
regardless of job triggers or job options. The resulting job instance is a
scheduled job, but it
isn't saved to disk like triggered scheduled jobs. You can't use
the ArgumentList parameter of
Start-Job to provide values for parameters of
scripts that run in a scheduled job. For more
information, see about_Scheduled_Jobs.

This parameter was introduced in PowerShell 3.0.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-DefinitionPath

Specifies path of the definition for the job that this cmdlet starts. Enter the definition
path. The
concatenation of the values of the DefinitionPath and DefinitionName
parameters is the fully
qualified path of the job definition. Use this parameter to start
custom job types that have a
definition path, such as scheduled jobs.

For scheduled jobs, the value of the DefinitionPath parameter is


$HOME\AppData\Local\Windows\PowerShell\ScheduledJob .

This parameter was introduced in PowerShell 3.0.

Type: String

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-FilePath

Specifies a local script that Start-Job runs as a background job. Enter the path and
file name of
the script or use the pipeline to send a script path to Start-Job . The
script must be on the local
computer or in a folder that the local computer can
access.

When you use this parameter, PowerShell converts the contents of the specified
script file to a
script block and runs the script block as a background job.
Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InitializationScript

Specifies commands that run before the job starts. To create a script block, enclose
the commands in
curly braces ( {} ).

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.

Type: ScriptBlock

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

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.

Type: PSObject

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-LiteralPath
Specifies a local script that this cmdlet runs as a background job. Enter the path of a
script on
the local computer.

Start-Job uses the value of the LiteralPath parameter exactly as it's typed. No

characters are
interpreted as wildcard characters. If the path includes escape
characters, enclose it in single
quotation marks. Single quotation marks tell
PowerShell not to interpret any characters as escape
sequences.

Type: String

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Name

Specifies a friendly name for the new job. You can use the name to identify the job to
other job
cmdlets, such as the Stop-Job cmdlet.

The default friendly name is Job# , where # is an ordinal number that is incremented
for each
job.

Type: String

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-PSVersion

Specifies a version. Start-Job runs the job with the version of PowerShell. The
acceptable values
for this parameter are: 2.0 and 3.0 .

This parameter was introduced in PowerShell 3.0.

Type: Version
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RunAs32

Indicates that Start-Job runs the job in a 32-bit process. RunAs32 forces the job to
run in a
32-bit process, even on a 64-bit operating system.

On 64-bit versions of Windows 7 and Windows Server 2008 R2, when the Start-Job
command includes
the RunAs32 parameter, you can't use the Credential parameter
to specify the credentials of
another user.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-ScriptBlock

Specifies the commands to run in the background job. To create a script block,
enclose the commands
in curly braces ( {} ). Use the $input automatic variable to
access the value of the
InputObject parameter. This parameter is required.

Type: ScriptBlock

Aliases: Command

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Type
Specifies the custom type for jobs started by Start-Job . Enter a custom job type
name, such as
PSScheduledJob for scheduled jobs or PSWorkflowJob for workflows
jobs. This parameter isn't valid
for standard background jobs.

This parameter was introduced in PowerShell 3.0.

Type: String

Position: 2

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe an object with the Name property to the Name parameter to this cmdlet.
For
example, you can pipe a FileInfo object from Get-ChildItem .

Outputs
System.Management.Automation.PSRemotingJob

This cmdlet returns a PSRemotingJob object representing the job that it started.

Notes
Windows PowerShell includes the following aliases for Start-Job :

sajb

To run in the background, Start-Job runs in its own session in 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 in the remote session.

Related Links
about_Arrays
about_Automatic_Variables
about_Jobs
about_Job_Details
about_Remote_Jobs
Get-Job
Invoke-Command
Receive-Job
Remove-Job
Resume-Job
Stop-Job
Suspend-Job
Wait-Job
Stop-Job
Reference
Module: Microsoft.PowerShell.Core

Stops a PowerShell background job.

Syntax
PowerShell

Stop-Job

[-PassThru]

[-Id] <Int32[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Stop-Job

[-Job] <Job[]>

[-PassThru]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Stop-Job

[-PassThru]

[-Name] <String[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Stop-Job

[-PassThru]

[-InstanceId] <Guid[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]
PowerShell

Stop-Job

[-PassThru]

[-State] <JobState>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Stop-Job

[-PassThru]

[-Filter] <Hashtable>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Stop-Job cmdlet stops 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 background jobs, such as those that were started by using
the
Start-Job cmdlet or the AsJob parameter of any cmdlet. When you stop a
background job,
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 the Remove-Job
cmdlet.

Starting in Windows PowerShell 3.0, Stop-Job also stops custom job types, such as
WorkflowJobs
and instances of ScheduledJobs. To enable Stop-Job to stop a job with
custom job type, import
the module that supports the custom job type into the session
before you run a Stop-Job command,
either by using the Import-Module cmdlet or by
using or getting a cmdlet in the module. For
information about a particular custom job
type, see the documentation of the custom job type
feature.

Examples
Example 1: Stop a job on a remote computer with Invoke-
Command
PowerShell

$s = New-PSSession -ComputerName Server01 -Credential Domain01\Admin02

$j = Invoke-Command -Session $s -ScriptBlock {Start-Job -ScriptBlock {Get-


EventLog System}}

Invoke-Command -Session $s -ScriptBlock { Stop-job -Job $Using: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 with the Invoke-Command cmdlet to run a Start-Job
command remotely,
the job object is stored on the remote computer. 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 PowerShell session (PSSession) on the Server01 computer,
and then
stores 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 Using scope modifier to
identify $j as a local
variable. For more information about the Using scope modifier,
see
about_Remote_Variables.

When the command finishes, the job is stopped and the PSSession in $s is available for
use.

Example 2: Stop a background job


PowerShell

Stop-Job -Name "Job1"

This command stops the Job1 background job.


Example 3: Stop several background jobs
PowerShell

Stop-Job -Id 1, 3, 4

This command stops three jobs. It identifies them by their IDs.

Example 4: Stop all background jobs


PowerShell

Get-Job | Stop-Job

This command stops all of the background jobs in the current session.

Example 5: Stop all blocked background jobs


PowerShell

Stop-Job -State Blocked

This command stops all the jobs that are blocked.

Example 6: Stop a job by instance ID


PowerShell

Get-Job | Format-Table ID, Name, Command, @{Label="State";Expression=


{$_.JobStateInfo.State}},

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

Stop-Job -InstanceId e3bbfed1-9c53-401a-a2c3-a8db34336adf

These commands show how to stop a job based on its InstanceID.


The first command uses the Get-Job cmdlet 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
InstanceID of each job. It uses a
calculated property to display the job state.

The second command uses a Stop-Job command that has the InstanceID parameter to
stop a
selected job.

Example 7: Stop a job on a remote computer


PowerShell

$j = Invoke-Command -ComputerName Server01 -ScriptBlock {Get-EventLog


System} -AsJob

$j | Stop-Job -PassThru

Id Name State HasMoreData Location Command

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

5 Job5 Stopped True user01-tablet get-eventlog


system

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 with the AsJob parameter of the Invoke-Command cmdlet,
the Job
object is located on the local computer, even though the job runs on the remote
computer. Therefore,
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 the Start-Job
cmdlet 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.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Filter

Specifies a hash table of conditions. This cmdlet stops jobs that satisfy every
condition.
Enter a hash table where the keys are job properties and the values are
job property values.

This parameter works only on custom job types, such as WorkflowJobs and
ScheduledJobs. It
does not work on standard background jobs, such as those
created by using the Start-Job cmdlet.
For information about support for this
parameter, see the help topic for the job type.

This parameter was introduced in Windows PowerShell 3.0.

Type: Hashtable

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Id

Specifies the IDs of jobs that this cmdlet stops. The default is all jobs in the current
session.

The ID is an integer that uniquely identifies the job in the current session. It is easier
to
remember and type than the instance ID, but it is unique only in the current
session. You can type
one or more IDs, separated by commas. To find the ID of a job,
type Get-Job .

Type: Int32[]

Position: 0

Default value: All jobs

Accept pipeline input: True

Accept wildcard characters: False

-InstanceId

Specifies the instance IDs of jobs that this cmdlet stops. 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 .

Type: Guid[]

Position: 0

Default value: All jobs

Accept pipeline input: True

Accept wildcard characters: False

-Job

Specifies the jobs that this cmdlet stops. 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.

Type: Job[]

Position: 0

Default value: All jobs

Accept pipeline input: True

Accept wildcard characters: False


-Name

Specifies friendly names of jobs that this cmdlet stops. 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.

Type: String[]

Position: 0

Default value: All jobs

Accept pipeline input: True

Accept wildcard characters: True

-PassThru

Returns an object representing the item with which you are working. By default, this
cmdlet does not
generate any output.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-State

Specifies a job state. This cmdlet stops only jobs in the specified state. The
acceptable values for
this parameter are:

NotStarted
Running

Completed

Failed
Stopped

Blocked
Suspended
Disconnected

Suspending
Stopping

For more information about job states, see


JobState Enumeration.

Type: JobState

Accepted values: NotStarted, Running, Completed, Failed, Stopped, Blocked,


Suspended, Disconnected, Suspending, Stopping,
AtBreakpoint

Position: 0

Default value: All jobs

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
System.Management.Automation.RemotingJob

You can pipe a job object to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.


System.Management.Automation.PSRemotingJob

When you use the PassThru parameter, this cmdlet returns a job object.

Notes
Windows PowerShell includes the following aliases for Stop-Job :

spjb

Related Links
Get-Job
Invoke-Command
Receive-Job
Remove-Job
Resume-Job
Start-Job
Suspend-Job
Wait-Job
about_Job_Details
about_Remote_Jobs
about_Remote_Variables
about_Jobs
about_Scopes
Suspend-Job
Reference
Module: Microsoft.PowerShell.Core

Temporarily stops workflow jobs.

Syntax
PowerShell

Suspend-Job

[-Force]

[-Wait]

[-Id] <Int32[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Suspend-Job

[-Job] <Job[]>

[-Force]

[-Wait]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Suspend-Job

[-Force]

[-Wait]

[-Name] <String[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Suspend-Job

[-Force]

[-Wait]

[-InstanceId] <Guid[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Suspend-Job

[-Force]

[-Wait]

[-Filter] <Hashtable>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Suspend-Job

[-Force]

[-Wait]

[-State] <JobState>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Suspend-Job cmdlet suspends workflow jobs. Suspend means to temporarily
interrupt or pause a
workflow job. This cmdlet allows users who are running workflows
to suspend the workflow. It
complements the Suspend-
Workflowhttps://go.microsoft.com/fwlink/?LinkId=267141 activity, which is a
command
in the workflow that suspends the workflow.

The Suspend-Job cmdlet works only on workflow jobs. It does not work on standard
background jobs,
such as those that are started by using the Start-Job cmdlet.

To identify a workflow job, look for a value of PSWorkflowJob in the PSJobTypeName


property of
the job. To determine whether a particular custom job type supports the
Suspend-Job cmdlet, see
the help topics for the custom job type.

When you suspend a workflow job, the workflow job runs to the next checkpoint,
suspends, and
immediately returns a workflow job object. To wait for the suspension to
complete before getting the
job, use the Wait parameter of Suspend-Job or the Wait-
Job cmdlet. When the workflow job is
suspended, the value of the State property of the

job is Suspended.
Suspending correctly relies on checkpoints. The current job state, metadata, and output
are saved in
the checkpoint so the workflow job can be resumed without loss of state or
data. If the workflow job
does not have checkpoints, it cannot be suspended correctly.
To add checkpoints to a workflow that
you are running, use the PSPersist workflow
common parameter. You can use the Force
parameter to suspend any workflow job
immediately and to suspend a workflow job that does not have
checkpoints, but the
action could cause loss of state and data.

Before you use a Job cmdlet on a custom job type, such as a workflow job
(PSWorkflowJob) import
the module that supports the custom job type, either by using
the Import-Module cmdlet or using or
using a cmdlet in the module.

This cmdlet was introduced in Windows PowerShell 3.0.

Examples

Example 1: Suspend a workflow job by name


This example shows how to suspend a workflow job.

The first command creates the Get-SystemLog workflow. The workflow uses the
CheckPoint-Workflow
activity to define a checkpoint in the workflow.

The second command uses the AsJob parameter that is common to all workflows to run
the
Get-SystemLog workflow as a background job. The command uses the JobName
workflow common
parameter to specify a friendly name for the workflow job.

The third command uses the Get-Job cmdlet to get the Get-SystemLogJob workflow job.
The output
shows that the value of the PSJobTypeName property is PSWorkflowJob.

The fourth command uses the Suspend-Job cmdlet to suspend the Get-SystemLogJob
job. The job runs
to the checkpoint and then suspends.

PowerShell

#Sample WorkflowWorkflow Get-SystemLog

$Events = Get-WinEvent -LogName System

CheckPoint-Workflow

InlineScript {\\Server01\Scripts\Analyze-SystemEvents.ps1 -Events


$Events}

PS C:\> Get-SystemLog -AsJob -JobName "Get-SystemLogJob"

PS C:\> Get-Job -Name Get-SystemLogJob

Id Name PSJobTypeName State HasMoreData


Location Command

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


- -------

4 Get-SystemLogJob PSWorkflowJob Running True


localhost Get-SystemLog

PS C:\> Suspend-Job -Name Get-SystemLogJob

Id Name PSJobTypeName State HasMoreData


Location Command

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


- -------

4 Get-SystemLogJob PSWorkflowJob Suspended True


localhost Get-SystemLog

Example 2: Suspend and resume a workflow job


This example shows how to suspend and resume a workflow job.

The first command suspends the LogWorkflowJob job.The command returns


immediately. The output shows
that the workflow job is still running, even though it is
being suspended.

The second command uses the Get-Job cmdlet to get the LogWorkflowJob job. The
output shows that
the workflow job suspended successfully.

The third command uses the Get-Job cmdlet to get the LogWorkflowJob job and the
Resume-Job
cmdlet to resume it. The output shows that the workflow job resumed
successfully and is now running.

PowerShell

PS C:\> Suspend-Job -Name LogWorkflowJob

Id Name PSJobTypeName State HasMoreData


Location Command

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


-- -------

67 LogflowJob PSWorkflowJob Running True


localhost LogWorkflow

PS C:\> Get-Job -Name LogWorkflowJob

Id Name PSJobTypeName State HasMoreData


Location Command

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


-- -------

67 LogflowJob PSWorkflowJob Suspended True


localhost LogWorkflow

PS C:\> Get-Job -Name LogWorkflowJob | Resume-Job

Id Name PSJobTypeName State HasMoreData


Location Command

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


-- -------

67 LogflowJob PSWorkflowJob Running True


localhost LogWorkflow

Example 3: Suspend a workflow job on a remote


computer
PowerShell

PS C:\> Invoke-Command -ComputerName Srv01 -Scriptblock {Suspend-Job -Filter


@{CustomID="031589"}

This command uses the Invoke-Command cmdlet to suspend a workflow job on the Srv01
remote
computer. The value of the Filter parameter is a hash table that specifies a
CustomID value.
This CustomID is job metadata (PSPrivateMetadata).

Example 4: Wait for the workflow job to suspend


PowerShell

PS C:\> Suspend-Job VersionCheck -Wait

Id Name PSJobTypeName State HasMoreData


Location Command

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


-- -------

5 VersionCheck PSWorkflowJob Suspended True


localhost LogWorkflow

This command suspends the VersionCheck workflow job. The command uses the Wait
parameter to wait
until the workflow job is suspended. When the workflow job runs to
the next checkpoint and is
suspended, the command finishes and returns the job object.

Example 5: Force a workflow job to suspend


PowerShell

PS C:\> Suspend-Job Maintenance -Force


This command suspends the Maintenance workflow job forcibly. The Maintenance job
does not have
checkpoints. It cannot be suspended correctly and might not resume
correctly.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Filter

Specifies a hash table of conditions. This cmdlet suspends jobs that satisfy all of the
conditions.
Enter a hash table where the keys are job properties and the values are
job property values.

Type: Hashtable

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Force

Suspends the workflow job immediately. This action could cause a loss of state and
data.

By default, Suspend-Job lets the workflow job run until the next checkpoint and then
suspends it.
You can also use this parameter to suspend workflow jobs that do not
have checkpoints.
Type: SwitchParameter

Aliases: F

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Id

Specifies the IDs of jobs that this cmdlet suspends.

The ID is an integer that uniquely identifies the job in the current session. It is easier
to
remember and to type than the instance ID, but it is unique only in the current
session. You can
type one or more IDs, separated by commas. To find the ID of a job,
use the Get-Job cmdlet.

Type: Int32[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-InstanceId

Specifies the instance IDs of jobs that this cmdlet suspends. 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 .

Type: Guid[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False


-Job

Specifies the workflow jobs that this cmdlet stops. Enter a variable that contains the
workflow jobs
or a command that gets the workflow jobs. You can also pipe
workflow jobs to the Suspend-Job
cmdlet.

Type: Job[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies friendly names of jobs that this cmdlet suspends. Enter one or more
workflow job names.
Wildcard characters are supported.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-State

Specifies a job state. This cmdlet stops only jobs in the specified state. The
acceptable values for
this parameter are:

NotStarted
Running
Completed
Failed
Stopped
Blocked
Suspended
Disconnected
Suspending
Stopping
Suspend-Job suspends only workflow jobs in the Running state.

For more information about job states, see


JobState Enumeration.

Type: JobState

Accepted values: NotStarted, Running, Completed, Failed, Stopped, Blocked,


Suspended, Disconnected, Suspending, Stopping,
AtBreakpoint

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Wait

Indicates that this cmdlet suppresses the command prompt until the workflow job is
in the suspended
state. By default, Suspend-Job returns immediately, even if the
workflow job is not yet in the
suspended state.

The Wait parameter is equivalent to piping a Suspend-Job command to the Wait-Job


cmdlet.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False


Accept pipeline input: False

Accept wildcard characters: False

Inputs
Job

You can pipe all types of jobs to this cmdlet. However, if Suspend-Job gets a job of an
unsupported type, it returns a terminating error.

Outputs
Job

This cmdlet returns the jobs that it suspended.

Notes
The mechanism and location for saving a suspended job might vary depending on
the job type. For
example, suspended workflow jobs are saved in a flat file store by
default, but can also be saved
in a database.

If you submit a workflow job that is not in the Running state, Suspend-Job displays
a warning
message. To suppress the warning, use the WarningAction common
parameter with a value of
SilentlyContinue.

If a job is not of a type that supports suspending, Suspend-Job returns a


terminating error.

To find the workflow jobs that are suspended, including those that were suspended
by this cmdlet,
use the State parameter of the Get-Job cmdlet to get workflow
jobs in the Suspended state.

Some job types have options or properties that prevent Windows PowerShell from
suspending the job.
If attempts to suspend the job fail, verify that the job options
and properties allow for
suspending.

Related Links
Get-Job
Receive-Job
Remove-Job
Resume-Job
Start-Job
Stop-Job
Suspend-Job
Wait-Job
Test-ModuleManifest
Reference
Module: Microsoft.PowerShell.Core

Verifies that a module manifest file accurately describes the contents of a module.

Syntax
PowerShell

Test-ModuleManifest

[-Path] <String>

[<CommonParameters>]

Description
The Test-ModuleManifest cmdlet verifies that the files that are listed in the module
manifest
( .psd1 ) file are actually 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 they run
scripts that depend on the
module.

Test-ModuleManifest returns an object that represents the module. This is 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.

Examples

Example 1: Test a manifest


PowerShell

Test-ModuleManifest -Path "$pshome\Modules\TestModule.psd1"

This command tests the TestModule.psd1 module manifest.

Example 2: Test a manifest by using the pipeline


PowerShell

"$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


processed because the file was not found. Please correct the path and try
again.

At line:1 char:34

+ "$pshome\Modules\TestModule.psd1" | test-modulemanifest <<<<

+ CategoryInfo : ResourceUnavailable:
(C:\Windows\System32\WindowsPowerShell\v1.0\Modules\TestModule\TestTypes.ps1
xml:String) [Test-ModuleManifest], FileNotFoundException

+ FullyQualifiedErrorId :
Modules_TypeDataFileNotFound,Microsoft.PowerShell.Commands.TestModuleManifes
tCommandName

Name : TestModule

Path :
C:\Windows\system32\WindowsPowerShell\v1.0\Modules\TestModule\TestModule.psd
1

Description :

Guid : 6f0f1387-cd25-4902-b7b4-22cff6aefa7b
Version : 1.0

ModuleBase :
C:\Windows\system32\WindowsPowerShell\v1.0\Modules\TestModule

ModuleType : Manifest

PrivateData :

AccessMode : ReadWrite

ExportedAliases : {}

ExportedCmdlets : {}

ExportedFunctions : {}

ExportedVariables : {}

NestedModules : {}

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: Write a function to test a module manifest


PowerShell

function Test-ManifestBool ($path)

{$a = dir $path | Test-ModuleManifest -ErrorAction SilentlyContinue; $?}


This function is like Test-ModuleManifest , but it returns a Boolean value. The function
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. The command uses a pipeline operator ( | ) to pass the
file object to
Test-ModuleManifest .

Test-ModuleManifest 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.
Therefore, the object is not
displayed.

Then, in a separate command, the function displays the value of the $? automatic
variable. If the
previous command generates no error, the command displays $True , 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.

Parameters
-Path

Specifies a path and file name for the manifest file. Enter an optional path and name
of the module
manifest file that has the .psd1 file name extension. The default
location is the current
directory. Wildcard characters are supported, but must resolve
to a single module manifest file.
This parameter is required. You can also pipe a path
to Test-ModuleManifest .

Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

Inputs
String
You can pipe the path to a module manifest to this cmdlet.

Outputs
PSModuleInfo

This cmdlet returns a PSModuleInfo object that represents the module. It returns this
object
even if the manifest has errors.

Related Links
Export-ModuleMember
Get-Module
Import-Module
New-Module
New-ModuleManifest
Remove-Module
about_Modules
Test-PSSessionConfigurationFile
Reference
Module: Microsoft.PowerShell.Core

Verifies the keys and values in a session configuration file.

Syntax
PowerShell

Test-PSSessionConfigurationFile

[-Path] <String>

[<CommonParameters>]

Description
This cmdlet verifies that a session configuration file contains valid keys and the values
are of the
correct type. For enumerated values, the cmdlet verifies that the specified
values are valid.

The cmdlet returns $True if the file passes all tests and $False if it does not. To find any
errors, use the Verbose parameter.

Test-PSSessionConfigurationFile verifies the session configuration files, such as those


created by
the New-PSSessionConfigurationFile cmdlet. For information about session
configurations, see
about_Session_Configurations. For information about session
configuration files, see about_Session_Configuration_Files.

This cmdlet was introduced in PowerShell 3.0.

Examples

Example 1: Test a session configuration file


PowerShell

Test-PSSessionConfigurationFile -Path "FullLanguage.pssc"

True
Example 2: Test the session configuration file of a session
configuration
In this example, we test the configuration file used in the Restricted session
configuration.
The value of the Path parameter is the result of the Get-
PSSessionConfiguration command that
gets the Restricted session configuration. The

path of the session configuration file is stored


in the value of the ConfigFilePath
property of the session configuration.

PowerShell

Test-PSSessionConfigurationFile -Path (Get-PSSessionConfiguration -Name


Restricted).ConfigFilePath

Example 3: Test all session configuration files


The function in this example tests all session configuration files on the local computer.
The
function uses the Get-PSSessionConfiguration cmdlet to get all session
configurations. The code
inside the ForEach-Object loop displays the file path and tests
each of the session
configurations.

PowerShell

function Test-AllConfigFiles

Get-PSSessionConfiguration | ForEach-Object {

if ($_.ConfigFilePath) {

$_.ConfigFilePath

Test-PSSessionConfigurationFile -Verbose -Path $_.ConfigFilePath

Test-AllConfigFiles

C:\WINDOWS\System32\WindowsPowerShell\v1.0\SessionConfig\Empty_6fd77bf6-
e084-4372-bd8a-af3e207354d3.pssc

True

C:\WINDOWS\System32\WindowsPowerShell\v1.0\SessionConfig\Full_1e9cb265-dae0-
4bd3-89a9-8338a47698a1.pssc

VERBOSE: The member 'AliasDefinitions' must contain the required key


'Description'. Add the require key

to the
fileC:\WINDOWS\System32\WindowsPowerShell\v1.0\SessionConfig\Full_1e9cb265-
dae0-4bd3-89a9-8338a47698a1.pssc.

False

C:\WINDOWS\System32\WindowsPowerShell\v1.0\SessionConfig\NoLanguage_0c115179
-ff2a-4f66-a5eb-e56e5692ba22.pssc

True

C:\WINDOWS\System32\WindowsPowerShell\v1.0\SessionConfig\RestrictedLang_b6bd
9474-0a6c-4e06-8722-c2c95bb10d3e.pssc

True

C:\WINDOWS\System32\WindowsPowerShell\v1.0\SessionConfig\RRS_3fb29420-2c87-
46e5-a402-e21436331efc.pssc

True

The ConfigFilePath property of a session configuration contains the path of the session
configuration file that is used in the session configuration, if any.

If the value of the ConfigFilePath property is populated (is true), the command gets
(prints)
the ConfigFilePath property value. Then it uses the Test-
PSSessionConfigurationFile cmdlet to
test the file in the ConfigFilePath value. The

Verbose parameter returns the file error when


the file fails the test.

Parameters
-Path

Specifies the path and filename of a session configuration file (.pssc). If you omit the
path, the
default is the current folder. Wildcard characters are supported, but they
must resolve to a single
file. You can also pipe a session configuration file path to
Test-PSSessionConfigurationFile .

Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

Inputs
String

You can pipe a session configuration file path to this cmdlet.

Outputs
Boolean

Related Links
Disable-PSSessionConfiguration
Enable-PSSessionConfiguration
Get-PSSessionConfiguration
New-PSSessionConfigurationFile
New-PSSessionOption
Register-PSSessionConfiguration
Set-PSSessionConfiguration
Test-PSSessionConfigurationFile
Unregister-PSSessionConfiguration
WSMan Provider
about_Session_Configurations
about_Session_Configuration_Files
Unregister-PSSessionConfiguration
Reference
Module: Microsoft.PowerShell.Core

Deletes registered session configurations from the computer.

Syntax
PowerShell

Unregister-PSSessionConfiguration
[-Name] <String>

[-Force]

[-NoServiceRestart]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Unregister-PSSessionConfiguration cmdlet deletes registered session
configurations from the
computer. This cmdlet is designed for system administrators to
manage customized session
configurations for users.

To make the change effective, Unregister-PSSessionConfiguration restarts the WinRM


service. To
prevent the restart, specify the NoServiceRestart parameter.

If you accidentally delete the default Microsoft.PowerShell or Microsoft.PowerShell32


session
configurations, use the Enable-PSRemoting cmdlet to restore them. For more
information, see
about_Session_Configurations.

Examples

Example 1: Delete a session configuration


This example deletes the MaintenanceShell session configuration from the computer.

PowerShell

Unregister-PSSessionConfiguration -Name "MaintenanceShell"


Example 2: Delete a session configuration and restart the
WinRM service
In this example, we delete the MaintenanceShell configuration and restart the WinRM
service. The
Force parameter suppresses all user messages to restart the WinRM service
without prompting.

PowerShell

Unregister-PSSessionConfiguration -Name MaintenanceShell -Force

Example 3: Delete all session configurations


This examples show two ways to delete all the session configurations on the computer.
Both commands
have the same effect and can be used interchangeably.

PowerShell

Unregister-PSSessionConfiguration -Name *

Get-PSSessionConfiguration -Name * | Unregister-PSSessionConfiguration

Example 4: Unregister without a restart


This example shows the effect of using the NoServiceRestart parameter to prevent a
service
restart that would disrupt any sessions on the computer.

PowerShell

PS> Unregister-PSSessionConfiguration -Name "MaintenanceShell" -


NoServiceRestart

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

PS> New-PSSession -ConfigurationName "MaintenanceShell"

Id Name ComputerName State Configuration Availability

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

1 Session1 localhost Opened MaintenanceShell Available

PS> Restart-Service winrm

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 resources, or logical


endpoints.

For more information, see the about_Remote_Troubleshooting Help topic.

+ CategoryInfo : OpenError:
(System.Manageme....RemoteRunspace:RemoteRunspace) [],
PSRemotingTransportException

+ FullyQualifiedErrorId : PSSessionOpenFailed

The Unregister-PSSessionConfiguration 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.

Next, the Get-PSSessionConfiguration tries to get the MaintenanceShell session.


Because the
session has been removed from the WS-Management resource table, Get-
PSSessionConfiguration cannot
return it.

The New-PSSession cmdlet creates a session using the MaintenanceShell configuration.


The command
succeeds. Next, we restart the WinRM service.

Finally, the New-PSSession cmdlet tries to create a session that uses the
MaintenanceShell
configuration. This time, the session fails because the

MaintenanceShell configuration was deleted


when the WinRM service restarted.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False


Accept wildcard characters: False

-Force

Indicates that the cmdlet does not prompt you for confirmation, 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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Name

Specifies the names of the session configurations to delete. Enter one session
configuration name or
a configuration name pattern. Wildcard characters are
permitted. This parameter is required.

You can also pipe a session configurations to Unregister-PSSessionConfiguration .

Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-NoServiceRestart

Indicates that this cmdlet does not restart the WinRM service, and suppresses the
prompt to
restart the service.

By default, when you run 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, specify the Force parameter. To
restart the
WinRM service manually, use the Restart-Service cmdlet.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
Microsoft.PowerShell.Commands.PSSessionConfigurationCommands

You can pipe a session configuration object to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
To run this cmdlet you must start PowerShell by using the Run as administrator option.

Related Links
Disable-PSSessionConfiguration
Enable-PSSessionConfiguration
Get-PSSessionConfiguration
New-PSSessionConfigurationFile
New-PSSessionOption
Register-PSSessionConfiguration
Set-PSSessionConfiguration
Test-PSSessionConfigurationFile
Unregister-PSSessionConfiguration
WSMan Provider
about_Session_Configurations
about_Session_Configuration_Files
Update-Help
Reference
Module: Microsoft.PowerShell.Core

Downloads and installs the newest help files on your computer.

Syntax
PowerShell

Update-Help

[[-Module] <String[]>]

[-FullyQualifiedModule <ModuleSpecification[]>]

[[-SourcePath] <String[]>]

[-Recurse]

[[-UICulture] <CultureInfo[]>]

[-Credential <PSCredential>]

[-UseDefaultCredentials]

[-Force]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Update-Help

[[-Module] <String[]>]

[-FullyQualifiedModule <ModuleSpecification[]>]

[-LiteralPath <String[]>]

[-Recurse]

[[-UICulture] <CultureInfo[]>]

[-Credential <PSCredential>]

[-UseDefaultCredentials]

[-Force]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Update-Help cmdlet downloads the newest help files for PowerShell modules and
installs them on
your computer. You need not restart PowerShell to make the change
effective. You can use the
Get-Help cmdlet to view the new help files immediately.
Update-Help checks the version of the help files on your computer. If you don't have

help files
for a module or if your help files are outdated, Update-Help downloads the
newest help files. The
help files can be downloaded and installed from the internet or a
file share.

Without parameters, Update-Help updates the help files for modules that support
updateable help
and are loaded in the session or installed in a location included in the
$env:PSModulePath . For
more information, see about_Updatable_Help.

Update-Help checks the version of the help installed. If Update-Help can't find updated

help
files for a module it continues silently without displaying an error message. Use the
Force
parameter to skip the version check. Use the Verbose parameter to see status and
progress
details. Use the Module parameter to update help files for a particular module.

If the cultural settings of your operating system are configured for a language that's not
available for updateable help, Update-Help continues silently without downloading any
help. Use
the UICulture parameter to download help files in a supported language. Help
is always available
for the en-US locale.

You can also use Update-Help on computers that aren't connected to the internet. First,
use the
Save-Help cmdlet to download help files from the internet and save them in a
shared folder that's
accessible to the system not connected to the internet. Then use the
SourcePath parameter of
Update-Help to download the updated help files from the
shared and install them on the computer.

The Update-Help cmdlet was introduced in Windows PowerShell 3.0.

) Important

Update-Help requires administrative privileges.

You must be a member of the Administrators group on the computer


to update the
help files for the core PowerShell modules.

To download or update the help files for modules in the PowerShell


installation
directory ( $PSHOME\Modules ), including the PowerShell
Core modules, start
PowerShell by using the Run as administrator option.
For example: Start-Process
powershell.exe -Verb RunAs .

You can also update help files by using the Update Windows PowerShell Help
menu
item in the Help menu in Windows PowerShell Integrated Scripting
Environment
(ISE).
The Update Windows PowerShell Help item runs an Update-Help cmdlet
without
parameters.
To update help for modules in the $PSHOME directory,
start Windows
PowerShell ISE by using the Run as administrator option.

Examples

Example 1: Update help files for all modules


The Update-Help cmdlet updates help files for installed modules that support Updatable
Help. The
user-interface (UI) culture language is set in the operating system.

PowerShell

Update-Help

Example 2: Update help files for specified modules


The Update-Help cmdlet updates help files only for module names that begin with
Microsoft.PowerShell.

PowerShell

Update-Help -Module Microsoft.PowerShell*

Example 3: Updating help on a system not set to the en-


US locale
The Update-Help cmdlet is designed to download help in multiple languages. However,
when there is
no help available for the language your system uses, Update-Help fails
silently unless you use
the UICulture parameter.

In this example, Update-Help is being run on a system that's set to the en-GB locale.

PowerShell

Update-Help Microsoft.PowerShell.Utility -Force

Update-Help Microsoft.PowerShell.Utility -Force -UICulture en-GB

Update-Help : Failed to update Help for the module(s)


'Microsoft.PowerShell.Utility'

with UI culture(s) {en-GB} : The specified culture is not supported: en-GB.


Specify a

culture from the following list: {en-US}.

At line:1 char:1

+ Update-Help Microsoft.PowerShell.Utility -Force -UICulture en-GB

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : InvalidOperation: (:) [Update-Help], Exception

+ FullyQualifiedErrorId :
HelpCultureNotSupported,Microsoft.PowerShell.Commands

.UpdateHelpCommand

The help files are always published for the en-US locale. To download the English help,
run
Update-Help with the UICulture parameter and specify the en-US locale.

Example 4: Update help files automatically


This example creates a scheduled job that updates help for all modules every day at 3:00
AM.

PowerShell

$jobParams = @{

Name = 'UpdateHelpJob'

Credential = 'Domain01\User01'

ScriptBlock = '{Update-Help}'

Trigger = (New-JobTrigger -Daily -At "3 AM")

Register-ScheduledJob @jobParams

Id Name JobTriggers Command


Enabled

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


-------

1 UpdateHelpJob 1 Update-Help
True

The Register-ScheduledJob cmdlet creates a scheduled job that runs an Update-Help


command. The
command uses the Credential parameter to run Update-Help by using
the credentials of a member
of the Administrators group on the computer. The value of
the Trigger parameter is a
New-JobTrigger command that creates a job trigger that
starts the job every day at 3:00 AM.

To run the Register-ScheduledJob command, start PowerShell by using the Run as


administrator
option. PowerShell prompts you for the password of the user specified in
the Credential
parameter. The credentials are stored with the scheduled job. You aren't
prompted when the job runs.
You can use the Get-ScheduledJob cmdlet to view the scheduled job, use the Set-
ScheduledJob
cmdlet to change it, and use the Unregister-ScheduledJob cmdlet to
delete it. You can also view
and manage the scheduled job in Task Scheduler in the
following path:

Task Scheduler Library\Microsoft\Windows\PowerShell\ScheduledJobs .

Example 5: Update help files on multiple computers from


a file share
In this example, updated help files are downloaded from the internet and saved in a file
share. User
credentials are needed that have permissions to access the file share and
install updates. When a
file share is used, it's possible to update computers that are
behind firewalls or aren't connected
to the internet.

PowerShell

Save-Help -DestinationPath \\Server01\Share\PSHelp -Credential


Domain01\Admin01

Invoke-Command -ComputerName (Get-Content Servers.txt) -ScriptBlock {

Update-Help -SourcePath \\Server01\Share\PSHelp -Credential


Domain01\Admin01

The Save-Help command downloads the newest help files for all modules that support
Updatable Help.
The DestinationPath parameter saves the files in the
\\Server01\Share\PSHelp file share. The
Credential parameter specifies a user who has

permission to access the file share.

The Invoke-Command cmdlet runs remote Update-Help commands on multiple


computers. The
ComputerName parameter gets a list of remote computers from the
Servers.txt file. The
ScriptBlock parameter runs the Update-Help command and uses the
SourcePath parameter to
specify the file share containing the updated help files. The
Credential parameter specifies a
user who can access the file share and run the remote
Update-Help command.

Example 6: Get a list of updated help files


The Update-Help cmdlet updates help for a specified module. The cmdlet uses the
Verbose common
parameter to display the list of help files that were updated. You can
use Verbose to view
output for all help files or help files for a specific module.
Without the Verbose parameter, Update-Help doesn't display the results of the
command. The
Verbose parameter output is useful to verify that the help files were
updated or if the latest
version is installed.

PowerShell

Update-Help -Module Microsoft.PowerShell.Utility -Verbose

Example 7: Find modules that support Updatable Help


This example lists modules that support Updatable Help. The command uses the
module's
HelpInfoUri property to identify modules that support Updatable Help. The
HelpInfoUri
property contains a URL that's redirected when the Update-Help cmdlet is
run.

PowerShell

Get-Module -ListAvailable | Where-Object -Property HelpInfoUri

Directory: C:\program files\powershell\6\Modules

ModuleType Version Name PSEdition


ExportedCommands

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


--------

Manifest 6.1.0.0 CimCmdlets Core {Get-


CimAssociatedInstance... }

Manifest 1.2.2.0 Microsoft.PowerShell.Archive Desk


{Compress-Archive... }

Manifest 6.1.0.0 Microsoft.PowerShell.Diagnostics Core {Get-


WinEvent, New-WinEvent}

Directory: C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules

ModuleType Version Name PSEdition


ExportedCommands

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


--------

Manifest 2.0.1.0 Appx Core,Desk {Add-


AppxPackage, ... }

Script 1.0.0.0 AssignedAccess Core,Desk {Clear-


AssignedAccess, ... }

Manifest 1.0.0.0 BitLocker Core,Desk {Unlock-


BitLocker, ... }

Example 8: Inventory updated help files


In this example, the script Get-UpdateHelpVersion.ps1 creates an inventory of the
Updatable Help
files for each module and their version numbers.

The script identifies modules that support Updatable Help using the HelpInfoUri
property of
modules. For modules that support Updatable Help, the script looks for and
parses the help
information file (*helpinfo.xml) to find the latest version number.

The script uses the PSCustomObject class and a hash table to create a custom output
object.

PowerShell

# Get-UpdateHelpVersion.ps1

Param(

[parameter(Mandatory=$False)]

[String[]]

$Module

$HelpInfoNamespace =
@{helpInfo='http://schemas.microsoft.com/powershell/help/2010/05'}

if ($Module) { $Modules = Get-Module $Module -ListAvailable | where


{$_.HelpInfoUri} }

else { $Modules = Get-Module -ListAvailable | where {$_.HelpInfoUri} }

foreach ($mModule in $Modules)

$mDir = $mModule.ModuleBase

if (Test-Path $mdir\*helpinfo.xml)

$mName=$mModule.Name

$mNodes = dir $mdir\*helpinfo.xml -ErrorAction SilentlyContinue |

Select-Xml -Namespace $HelpInfoNamespace -XPath


"//helpInfo:UICulture"

foreach ($mNode in $mNodes)

$mCulture=$mNode.Node.UICultureName

$mVer=$mNode.Node.UICultureVersion

[PSCustomObject]@{"ModuleName"=$mName; "Culture"=$mCulture;
"Version"=$mVer}

ModuleName Culture
Version

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

ActiveDirectory en-US
3.0.0.0

ADCSAdministration en-US
3.0.0.0

ADCSDeployment en-US
3.0.0.0

ADDSDeployment en-US
3.0.0.0

ADFS en-US
3.0.0.0

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Credential

Specifies credentials of a user who has permission to access the file system location
specified by
SourcePath. This parameter is valid only when the SourcePath or
LiteralPath parameter is
used in the command.

The Credential parameter enables you to run Update-Help commands with the
SourcePath
parameter on remote computers. By providing explicit credentials, you
can run the command on a
remote computer and access a file share on a third
computer without encountering an access denied
error or using CredSSP
authentication to delegate credentials.

Type a user name, such as User01 or Domain01\User01, or enter a PSCredential


object
generated by the Get-Credential cmdlet. If you type a user name, you're
prompted to enter the
password.

Credentials are stored in a PSCredential


object and the password is stored as a
SecureString.
7 Note

For more information about SecureString data protection, see


How secure is
SecureString?.

Type: PSCredential

Position: Named

Default value: Current user

Accept pipeline input: False

Accept wildcard characters: False

-Force

Indicates that this cmdlet doesn't follow the once-per-day limitation, skips version
checking, and
downloads files that exceed the 1 GB limit.

Without this parameter, Update-Help runs only once in each 24-hour period.
Downloads are limited
to 1 GB of uncompressed content per module and help files
are only installed when they're newer than
the existing files on the computer.

The once-per-day limit protects the servers that host the help files and makes it
practical for you
to add an Update-Help command to your PowerShell profile without
incurring the resource cost of
repeated connections or downloads.

To update help for a module in multiple UI cultures without the Force parameter,
include all UI
cultures in the same command, such as:

Update-Help -Module PSScheduledJobs -UICulture en-US, fr-FR, pt-BR

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-FullyQualifiedModule
The value can be a module name, a full module specification, or a path to a module
file.

When the value is a path, the path can be fully qualified or relative. A relative path is
resolved
relative to the script that contains the using statement.

When the value is a name or module specification, PowerShell searches the


PSModulePath for the
specified module.

A module specification is a hashtable that has the following keys.

ModuleName - Required Specifies the module name.

GUID - Optional Specifies the GUID of the module.


It's also Required to specify at least one of the three below keys.
ModuleVersion - Specifies a minimum acceptable version of the module.

MaximumVersion - Specifies the maximum acceptable version of the module.


RequiredVersion - Specifies an exact, required version of the module. This

can't be used with


the other Version keys.

You can't specify the FullyQualifiedModule parameter in the same command as a


Module
parameter.

Type: ModuleSpecification[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-LiteralPath

Specifies the folder for updated help files instead of downloading them from the
internet. Use this
parameter or SourcePath if you've used the Save-Help cmdlet to
download help files to a
directory.

You can pipeline a directory object, such as from the Get-Item or Get-ChildItem
cmdlets, to
Update-Help .

Unlike the value of SourcePath, the value of LiteralPath is used exactly as it's typed.
No
characters are interpreted as wildcard characters. If the path includes escape
characters, enclose
it in single quotation marks. Single quotation marks tell
PowerShell not to interpret any characters
as escape sequences.
Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Module

Updates help for the specified modules. Enter one or more module names or name
patterns in a
comma-separated list, or specify a file that lists one module name on
each line. Wildcard characters
are permitted. You can pipeline modules from the
Get-Module cmdlet to the Update-Help cmdlet.

The modules that you specify must be installed on the computer, but they don't have
to be imported
into the current session. You can specify any module in the session or
any module that's installed
in a location listed in the $env:PSModulePath environment
variable.

A value of * (all) attempts to update help for all modules that are installed on the
computer.
Modules that don't support Updatable Help are included. This value
might generate errors when the
command encounters modules that don't support
Updatable Help. Instead, run Update-Help without
parameters.

The Module parameter of the Update-Help cmdlet doesn't accept the full path of a
module file
or module manifest file. To update help for a module that isn't in a
$env:PSModulePath location,
import the module into the current session before you

run the Update-Help command.

Type: String[]

Aliases: Name

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True


-Recurse

Performs a recursive search for help files in the specified directory. This parameter is
valid only
when the command uses the SourcePath parameter.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SourcePath

Specifies a file system folder where Update-Help gets updated help files, instead of
downloading
them from the internet. Enter the path of a folder. Don't specify a file
name or file name
extension. You can pipeline a folder, such as one from the Get-
Item or Get-ChildItem cmdlets, to
Update-Help .

By default, Update-Help downloads updated help files from the internet. Use
SourcePath when
you've used the Save-Help cmdlet to download updated help files
to a directory.

To specify a default value for SourcePath, go to Group Policy, Computer


Configuration,
and Set the default source path for Update-Help. This Group Policy
setting prevents users from
using Update-Help to download help files from the
internet.
For more information, see about_Group_Policy_Settings.

Type: String[]

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-UICulture

Specifies UI culture values that Update-Help uses to get updated help files. Enter one
or more
language codes, such as es-ES, a variable containing culture objects, or a
command that gets
culture objects, such as a Get-Culture or Get-UICulture
command. Wildcard characters aren't
permitted and you can't submit a partial
language code, such as de.

By default, Update-Help gets help files in the UI culture set for the operating system.
If you
specify the UICulture parameter, Update-Help looks for help only for the
specified UI culture.

Commands that use the UICulture parameter succeed only when the module
provides help files for
the specified UI culture. If the command fails because the
specified UI culture isn't supported, an
error message is displayed.

Type: CultureInfo[]

Position: 2

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-UseDefaultCredentials

Indicates that Update-Help runs the command, including the internet download,
using the
credentials of the current user. By default, the command runs without
explicit credentials.

This parameter is effective only when the web download uses NT LAN Manager
(NTLM), negotiate, or
Kerberos-based authentication.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet isn't run.

Type: SwitchParameter

Aliases: wi
Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
DirectoryInfo

You can pipe a directory path object to this cmdlet.

PSModuleInfo

You can pipe a module object to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
To update help for the core PowerShell modules, that contain the commands that are
installed with
PowerShell, or any module in the $PSHOME\Modules directory, start
PowerShell with the option to
Run as administrator.

Only members of the Administrators group on the computer can update help for the
core PowerShell
modules, the commands that are installed together with PowerShell,
and for modules in the
$PSHOME\Modules folder. If you don't have permission to update
help files, you can read the help
files online. For example, Get-Help Update-Help -
Online .

Modules are the smallest unit of updatable help. You can't update help for a particular
cmdlet. To
find the module containing a particular cmdlet, use the ModuleName
property of the Get-Command
cmdlet, for example, (Get-Command Update-
Help).ModuleName .

Because help files are installed in the module directory, the Update-Help cmdlet can
install
updated help file only for modules that are installed on the computer. However,
the Save-Help
cmdlet can save help for modules that aren't installed on the computer.

The Update-Help cmdlet was introduced in Windows PowerShell 3.0. It doesn't work in
earlier
versions of PowerShell. On computers that have both Windows PowerShell 2.0
and Windows
PowerShell 3.0, use the Update-Help cmdlet in a Windows PowerShell 3.0
session to download and
update help files. The help files are available to both Windows
PowerShell 2.0 and Windows
PowerShell 3.0.

The Update-Help and Save-Help cmdlets use the following ports to download help files:
Port 80
for HTTP and port 443 for HTTPS.

Update-Help supports all modules and the core PowerShell snap-ins. It doesn't support
any other
snap-ins.

To update help for a module in a location that isn't listed in the $env:PSModulePath
environment
variable, import the module into the current session and then run an
Update-Help command. Run
Update-Help without parameters or use the Module

parameter to specify the module name. The


Module parameter of the Update-Help and
Save-Help cmdlets doesn't accept the full path of a
module file or module manifest file.

Any module can support Updatable Help. For instructions for supporting Updatable
Help in the modules
that you author, see
Supporting Updatable Help.

The Update-Help and Save-Help cmdlets aren't supported on Windows Preinstallation


Environment
(Windows PE).

Related Links
Get-Culture
Get-Help
Get-Module
Get-UICulture
Start-Job
Save-Help
Wait-Job
Reference
Module: Microsoft.PowerShell.Core

Waits until one or all of the PowerShell jobs running in the session are in a terminating
state.

Syntax
PowerShell

Wait-Job

[-Any]

[-Timeout <Int32>]

[-Force]

[-Id] <Int32[]>

[<CommonParameters>]

PowerShell

Wait-Job

[-Job] <Job[]>

[-Any]

[-Timeout <Int32>]

[-Force]

[<CommonParameters>]

PowerShell

Wait-Job

[-Any]

[-Timeout <Int32>]

[-Force]

[-Name] <String[]>

[<CommonParameters>]

PowerShell

Wait-Job

[-Any]

[-Timeout <Int32>]

[-Force]

[-InstanceId] <Guid[]>

[<CommonParameters>]
PowerShell

Wait-Job

[-Any]

[-Timeout <Int32>]

[-Force]

[-State] <JobState>

[<CommonParameters>]

PowerShell

Wait-Job

[-Any]

[-Timeout <Int32>]

[-Force]

[-Filter] <Hashtable>

[<CommonParameters>]

Description
The Wait-Job cmdlet waits for a job to be in a terminating state before continuing
execution.
The terminating states are:

Completed
Failed
Stopped
Suspended
Disconnected

You can wait until a specified job, or all jobs are in a terminating state. You can also set a
maximum wait time for the job using the Timeout parameter, or use the Force
parameter to
wait for a job in the Suspended or Disconnected states.

When the commands in the job are complete, Wait-Job returns a job object and
continues execution.

You can use the Wait-Job cmdlet to wait for jobs started by using the Start-Job cmdlet
or the
AsJob parameter of the Invoke-Command cmdlet. For more information about jobs,
see about_Jobs.

Starting in Windows PowerShell 3.0, the Wait-Job cmdlet also waits for custom job
types, such as
workflow jobs and instances of scheduled jobs. To enable Wait-Job to
wait for jobs of a particular
type, import the module that supports the custom job type
into the session before you run the
Get-Job cmdlet, either by using the Import-Module
cmdlet or by using or getting a cmdlet in the
module. For information about a particular
custom job type, see the documentation of the custom job
type feature.

Examples

Example 1: Wait for all jobs


PowerShell

Get-Job | Wait-Job

This command waits for all of the jobs running in the session to finish.

Example 2: Wait for jobs started on remote computers by


using Start-Job
PowerShell

$s = New-PSSession Server01, Server02, Server03

Invoke-Command -Session $s -ScriptBlock {Start-Job -Name Date1 -ScriptBlock


{Get-Date}}

$done = Invoke-Command -Session $s -Command {Wait-Job -Name Date1}

$done.Count

This example shows how to use the Wait-Job cmdlet with jobs started on remote
computers by using
the Start-Job cmdlet. Both 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


job
on three different computers is finished.

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 Invoke-Command to run Start-Job in each of the three
sessions in $s .
All of the jobs are named Date1.

The third command uses Invoke-Command to run Wait-Job . This command waits for the
Date1 jobs
on each computer to finish. 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 finished.

Example 3: Determine when the first job finishes


PowerShell

$s = New-PSSession (Get-Content Machines.txt)

$c = 'Get-EventLog -LogName System | where {$_.EntryType -eq "error" --and


$_.Source -eq "LSASRV"} | Out-File Errors.txt'

Invoke-Command -Session $s -ScriptBlock {Start-Job -ScriptBlock {$Using:c}

Invoke-Command -Session $s -ScriptBlock {Wait-Job -Any}

This example uses the Any parameter of Wait-Job to determine when the first of many
jobs
running in the current session are in a terminating state. It also shows how to use
the Wait-Job
cmdlet to wait for remote jobs to finish.

The first command creates a PSSession on each of the computers listed in the
Machines.txt file
and stores the PSSession objects 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 make sure
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 Invoke-Command cmdlet to run Start-Job in each of the
sessions in $s .
The Start-Job command starts a job that runs the Get-EventLog
command in the $c
variable.

The command uses the Using scope modifier to indicate that the $c variable was
defined on the
local computer. The Using scope modifier is introduced in Windows
PowerShell 3.0. For more
information about the Using scope modifier, see
about_Remote_Variables.

The fourth command uses Invoke-Command to run a Wait-Job command in the sessions.
It uses the
Any parameter to wait until the first job on the remote computers is
terminating state.

Example 4: Set a wait time for jobs on remote computers


PowerShell
PS> $s = New-PSSession Server01, Server02, Server03

PS> $jobs = Invoke-Command -Session $s -ScriptBlock {Start-Job -ScriptBlock


{Get-Date}}

PS> $done = Invoke-Command -Session $s -ScriptBlock {Wait-Job -Timeout 30}

PS>

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 then stores the PSSession objects in the $s variable.

The second command uses Invoke-Command to run Start-Job in each of the PSSession
objects in
$s . It stores the resulting job objects in the $jobs variable.

The third command uses Invoke-Command to run Wait-Job in each of the sessions 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 to establish the
maximum wait time, and then stores 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, returns the object that represents the job that was
completed, and displays the command prompt.

The $done variable contains a job object that represents the job that ran on Server02.

Example 5: Wait until one of several jobs finishes


PowerShell

Wait-Job -id 1,2,5 -Any

This command identifies three jobs by their IDs and waits until any one of them are in a
terminating
state. Execution continues when the first job finishes.

Example 6: Wait for a period, then allow job to continue


in background
PowerShell

Wait-Job -Name "DailyLog" -Timeout 120


This command waits 120 seconds (two minutes) for the DailyLog job to finish. If the job
does not
finish in the next two minutes, execution continues, and the job continues to
run in
the background.

Example 7: Wait for a job by name


PowerShell

Wait-Job -Name "Job3"

This command uses the job name to identify the job for which to wait.

Example 8: Wait for jobs on local computer started with


Start-Job
PowerShell

$j = Start-Job -ScriptBlock {Get-ChildItem *.ps1| where {$_.lastwritetime -


gt ((Get-Date) - (New-TimeSpan -Days 7))}}

$j | Wait-Job

This example shows how to use the Wait-Job cmdlet with jobs started on the local
computer by using
Start-Job .

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 Start-Job to start a job on the local computer. The job runs a
Get-ChildItem command that gets all of the files that have a .ps1 file name extension

that were
added or updated in the last week.

The third command uses Wait-Job to wait until the job is in a terminating state. When
the job
finishes, the command displays the job object, which contains information about
the job.

Example 9: Wait for jobs started on remote computers by


using Invoke-Command
PowerShell

$s = New-PSSession Server01, Server02, Server03

$j = Invoke-Command -Session $s -ScriptBlock {Get-Process} -AsJob

$j | Wait-Job

This example shows how to use Wait-Job with jobs started on remote computers by
using the
AsJob parameter of Invoke-Command . 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 in a terminating state.

The first command creates PSSession objects on three computers and stores them in
the $s
variable.

The second command uses Invoke-Command to run Get-Process in each of the three
sessions in $s .
The command uses the AsJob parameter to run the command
asynchronously as a 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. An Invoke-Command command is not required in this case, because the
job resides on the
local computer.

Example 10: Wait for a job that has an ID


PowerShell

Get-Job

Id Name State HasMoreData Location Command

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

1 Job1 Completed True localhost,Server01.. get-service

4 Job4 Completed True localhost dir | where

Wait-Job -Id 1

This command waits for the job with an ID value of 1.

Parameters
-Any
Indicates that this cmdlet returns the job object and continues execution when any
job finishes. By
default, Wait-Job waits until all of the specified jobs are complete
before it displays the
prompt.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Filter

Specifies a hash table of conditions. This cmdlet waits for jobs that satisfy all of the
conditions
in the hash table. Enter a hash table where the keys are job properties and
the values are job
property values.

This parameter works only on custom job types, such as workflow jobs and
scheduled jobs. It does not
work on standard jobs, such as those created by using
the Start-Job cmdlet. For information about
support for this parameter, see the help
topic for the job type.

This parameter was introduced in Windows PowerShell 3.0.

Type: Hashtable

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Force

Indicates that this cmdlet continues to wait for jobs in the Suspended or
Disconnected state. By
default, Wait-Job returns, or ends the wait, when jobs are in
one of the following states:

Completed
Failed
Stopped
Suspended
Disconnected

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Id

Specifies an array of IDs of jobs for which this cmdlet waits.

The ID is an integer that uniquely identifies the job in the current session. It is easier
to
remember and type than the instance ID, but it is unique only in the current
session. You can type
one or more IDs, separated by commas. To find the ID of a job,
type Get-Job .

Type: Int32[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-InstanceId

Specifies an array of instance IDs of jobs for which this cmdlet waits. 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 .

Type: Guid[]

Position: 0

Default value: None


Accept pipeline input: True

Accept wildcard characters: False

-Job

Specifies the jobs for which this cmdlet waits. 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.

Type: Job[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies friendly names of jobs for which this cmdlet waits.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-State

Specifies a job state. This cmdlet waits only for jobs in the specified state. The
acceptable values
for this parameter are:

NotStarted
Running
Completed
Failed
Stopped
Blocked
Suspended
Disconnected
Suspending
Stopping

For more information about job states, see


JobState Enumeration.

Type: JobState

Accepted values: NotStarted, Running, Completed, Failed, Stopped, Blocked,


Suspended, Disconnected, Suspending, Stopping,
AtBreakpoint

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Timeout

Specifies the maximum wait time for each job, in seconds. The default value, -1,
indicates that the
cmdlet waits until the job finishes. The timing starts when you
submit the Wait-Job command, not
the Start-Job command.

If this time is exceeded, the wait ends and execution continues, even if the job is still
running.
The command does not display any error message.

Type: Int32

Aliases: TimeoutSec

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
System.Management.Automation.RemotingJob

You can pipe a job object to this cmdlet.


Outputs
System.Management.Automation.PSRemotingJob

This cmdlet returns job objects that represent the jobs in a terminating state. If the wait
ends
because the value of the Timeout parameter is exceeded, Wait-Job does not
return any objects.

Notes
Windows PowerShell includes the following aliases for Wait-Job :

wjb

By default, Wait-Job returns, or ends the wait, when jobs are in one of the following
states:

Completed
Failed
Stopped
Suspended
Disconnected

To direct Wait-Job to continue to wait for Suspended and Disconnected jobs, use the
Force parameter.

Related Links
Get-Job
Invoke-Command
Receive-Job
Remove-Job
Resume-Job
Start-Job
Stop-Job
Suspend-Job
Where-Object
Reference
Module: Microsoft.PowerShell.Core

Selects objects from a collection based on their property values.

Syntax
PowerShell

Where-Object

[-InputObject <PSObject>]

[-Property] <String>

[[-Value] <Object>]

[-EQ]

[<CommonParameters>]

PowerShell

Where-Object

[-InputObject <PSObject>]

[-FilterScript] <ScriptBlock>

[<CommonParameters>]

PowerShell

Where-Object

[-InputObject <PSObject>]

[-Property] <String>

[[-Value] <Object>]

-Match

[<CommonParameters>]

PowerShell

Where-Object

[-InputObject <PSObject>]

[-Property] <String>

[[-Value] <Object>]

-CEQ

[<CommonParameters>]

PowerShell
Where-Object

[-InputObject <PSObject>]

[-Property] <String>

[[-Value] <Object>]

-NE

[<CommonParameters>]

PowerShell

Where-Object

[-InputObject <PSObject>]

[-Property] <String>

[[-Value] <Object>]

-CNE

[<CommonParameters>]

PowerShell

Where-Object

[-InputObject <PSObject>]

[-Property] <String>

[[-Value] <Object>]

-GT

[<CommonParameters>]

PowerShell

Where-Object

[-InputObject <PSObject>]

[-Property] <String>

[[-Value] <Object>]

-CGT

[<CommonParameters>]

PowerShell

Where-Object

[-InputObject <PSObject>]

[-Property] <String>

[[-Value] <Object>]

-LT

[<CommonParameters>]

PowerShell

Where-Object

[-InputObject <PSObject>]

[-Property] <String>

[[-Value] <Object>]

-CLT

[<CommonParameters>]

PowerShell

Where-Object

[-InputObject <PSObject>]

[-Property] <String>

[[-Value] <Object>]

-GE

[<CommonParameters>]

PowerShell

Where-Object

[-InputObject <PSObject>]

[-Property] <String>

[[-Value] <Object>]

-CGE

[<CommonParameters>]

PowerShell

Where-Object

[-InputObject <PSObject>]

[-Property] <String>

[[-Value] <Object>]

-LE

[<CommonParameters>]

PowerShell

Where-Object

[-InputObject <PSObject>]

[-Property] <String>

[[-Value] <Object>]

-CLE

[<CommonParameters>]

PowerShell

Where-Object

[-InputObject <PSObject>]

[-Property] <String>

[[-Value] <Object>]

-Like

[<CommonParameters>]

PowerShell

Where-Object

[-InputObject <PSObject>]

[-Property] <String>

[[-Value] <Object>]

-CLike

[<CommonParameters>]

PowerShell

Where-Object

[-InputObject <PSObject>]

[-Property] <String>

[[-Value] <Object>]

-NotLike

[<CommonParameters>]

PowerShell

Where-Object

[-InputObject <PSObject>]

[-Property] <String>

[[-Value] <Object>]

-CNotLike

[<CommonParameters>]

PowerShell

Where-Object

[-InputObject <PSObject>]

[-Property] <String>

[[-Value] <Object>]

-CMatch

[<CommonParameters>]

PowerShell

Where-Object

[-InputObject <PSObject>]

[-Property] <String>

[[-Value] <Object>]

-NotMatch

[<CommonParameters>]
PowerShell

Where-Object

[-InputObject <PSObject>]

[-Property] <String>

[[-Value] <Object>]

-CNotMatch

[<CommonParameters>]

PowerShell

Where-Object

[-InputObject <PSObject>]

[-Property] <String>

[[-Value] <Object>]

-Contains

[<CommonParameters>]

PowerShell

Where-Object

[-InputObject <PSObject>]

[-Property] <String>

[[-Value] <Object>]

-CContains

[<CommonParameters>]

PowerShell

Where-Object

[-InputObject <PSObject>]

[-Property] <String>

[[-Value] <Object>]

-NotContains

[<CommonParameters>]

PowerShell

Where-Object

[-InputObject <PSObject>]

[-Property] <String>

[[-Value] <Object>]

-CNotContains

[<CommonParameters>]

PowerShell
Where-Object

[-InputObject <PSObject>]

[-Property] <String>

[[-Value] <Object>]

-In

[<CommonParameters>]

PowerShell

Where-Object

[-InputObject <PSObject>]

[-Property] <String>

[[-Value] <Object>]

-CIn

[<CommonParameters>]

PowerShell

Where-Object

[-InputObject <PSObject>]

[-Property] <String>

[[-Value] <Object>]

-NotIn

[<CommonParameters>]

PowerShell

Where-Object

[-InputObject <PSObject>]

[-Property] <String>

[[-Value] <Object>]

-CNotIn

[<CommonParameters>]

PowerShell

Where-Object

[-InputObject <PSObject>]

[-Property] <String>

[[-Value] <Object>]

-Is

[<CommonParameters>]

PowerShell

Where-Object

[-InputObject <PSObject>]

[-Property] <String>

[[-Value] <Object>]

-IsNot

[<CommonParameters>]

Description
The Where-Object cmdlet selects objects that have particular property values from the
collection
of objects that are passed to it. For example, you can use the Where-Object
cmdlet to select files
that were created after a certain date, events with a particular ID, or
computers that use a
particular version of Windows.

Starting in Windows PowerShell 3.0, there are two different ways to construct a Where-
Object
command.

Script block. You can use a script block to specify the property name, a comparison
operator,
and a property value. Where-Object returns all objects for which the
script block statement is
true.

For example, the following command gets processes in the Normal priority class,
that is,
processes where the value of the PriorityClass property equals Normal .

Get-Process | Where-Object {$_.PriorityClass -eq "Normal"}

All PowerShell comparison operators are valid in the script block format. For more
information,
see about_Comparison_Operators.

Comparison statement. You can also write a comparison statement, which is much
more like
natural language. Comparison statements were introduced in Windows
PowerShell 3.0.

For example, the following commands also get processes that have a priority class
of Normal .
These commands are equivalent and you can use them interchangeably.

Get-Process | Where-Object -Property PriorityClass -eq -Value "Normal"

Get-Process | Where-Object PriorityClass -eq "Normal"

Starting in Windows PowerShell 3.0, Where-Object adds comparison operators as


parameters in a
Where-Object command. Unless specified, all operators are case-
insensitive. Before Windows
PowerShell 3.0, the comparison operators in the
PowerShell language were only usable in script
blocks.
When you provide a single Property to Where-Object , the cmdlet treats the value of the
property as a boolean expression. When the value of the property's Length isn't zero,
the
expression evaluates to $true . For example: ('hi', '', 'there') | Where-Object
Length

The previous example is functionally equivalent to:

('hi', '', 'there') | Where-Object Length -GT 0

('hi', '', 'there') | Where-Object { $_.Length -gt 0 }

For more information about how PowerShell evaluates booleans, see


about_Booleans.

Examples

Example 1: Get stopped services


These commands get a list of all services that are stopped. The $_ automatic variable
represents
each object that's passed to the Where-Object cmdlet.

The first command uses the script block format, the second command uses the
comparison statement
format. The commands filter the services the same way and
return the same output. Only the syntax
is different.

PowerShell

Get-Service | Where-Object { $_.Status -eq "Stopped" }

Get-Service | where Status -eq "Stopped"

Example 2: Get processes based on working set


These commands list processes that have a working set greater than 250 megabytes
(MB). The commands
filter the processes the same way and return the same output.
Only the syntax is different.

PowerShell

Get-Process | Where-Object { $_.WorkingSet -GT 250MB }

Get-Process | Where-Object WorkingSet -GT 250MB

Example 3: Get processes based on process name


These commands get the processes that have a ProcessName property value that
begins with the
letter p . The Match operator lets you use regular expression matches.

The commands filter the processes the same way and return the same output. Only the
syntax is
different.

PowerShell

Get-Process | Where-Object { $_.ProcessName -Match "^p.*" }

Get-Process | Where-Object ProcessName -Match "^p.*"

Example 4: Use the comparison statement format


This example shows how to use the new comparison statement format of the Where-
Object cmdlet.

The first command uses the comparison statement format. It doesn't use any aliases and
includes the
name for every parameter.

The second command is the more natural use of the comparison command format. The
command
substitutes the where alias for the Where-Object cmdlet name and omits all
optional parameter
names.

The commands filter the processes the same way and return the same output. Only the
syntax is
different.

PowerShell

Get-Process | Where-Object -Property Handles -GE -Value 1000

Get-Process | where Handles -GE 1000

Example 5: Get commands based on properties


This example shows how to write commands that return items that are true or false or
have any value
for a specified property. Each example shows both the script block and
comparison statement formats
for the command.

The commands filter their input the same way and return the same output. Only the
syntax is
different.

PowerShell
# Use Where-Object to get commands that have any value for the OutputType

# property of the command. This omits commands that do not have an


OutputType

# property and those that have an OutputType property, but no property


value.

Get-Command | where OutputType

Get-Command | where { $_.OutputType }

# Use Where-Object to get objects that are containers. This gets objects
that

# have the **PSIsContainer** property with a value of $True and excludes all

# others.

Get-ChildItem | where PSIsContainer

Get-ChildItem | where { $_.PSIsContainer }

# Finally, use the -not operator (!) to get objects that are not containers.

# This gets objects that do have the **PSIsContainer** property and those

# that have a value of $False for the **PSIsContainer** property.

Get-ChildItem | where { !$_.PSIsContainer }

# You cannot use the -not operator (!) in the comparison statement format

# of the command.

Get-ChildItem | where PSIsContainer -eq $False

Example 6: Use multiple conditions


PowerShell

Get-Module -ListAvailable | where {

($_.Name -notlike "Microsoft*" -and $_.Name -notlike "PS*") -and


$_.HelpInfoUri

This example shows how to create a Where-Object command with multiple conditions.

This command gets non-core modules that support the Updatable Help feature. The
command uses the
ListAvailable parameter of the Get-Module cmdlet to get all modules
on the computer. A
pipeline operator ( | ) sends the modules to the Where-Object
cmdlet, which gets modules whose
names don't begin with Microsoft or PS , and have a
value for the HelpInfoURI property,
which tells PowerShell where to find updated help
files for the module. The -and logical operator
connects the comparison statements.

The example uses the script block command format. Logical operators, such as -and , -
or , and
-not are valid only in script blocks. You can't use them in the comparison

statement format of a
Where-Object command.
For more information about PowerShell logical operators, see
about_Logical_Operators.
For more information about the Updatable Help feature, see
about_Updatable_Help.

Parameters
-CContains

Indicates that this cmdlet gets objects from a collection if the property value of the
object is an
exact match for the specified value. This operation is case-sensitive.

For example: Get-Process | where ProcessName -CContains "svchost"

CContains refers to a collection of values and is true if the collection contains an


item that
is an exact match for the specified value. If the input is a single object,
PowerShell converts it
to a collection of one object.

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-CEQ

Indicates that this cmdlet gets objects if the property value is the same as the
specified value.
This operation is case-sensitive.

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-CGE

Indicates that this cmdlet gets objects if the property value is greater than or equal
to the
specified value. This operation is case-sensitive.

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-CGT

Indicates that this cmdlet gets objects if the property value is greater than the
specified value.
This operation is case-sensitive.

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-CIn

Indicates that this cmdlet gets objects if the property value includes the specified
value. This
operation is case-sensitive.

For example: Get-Process | where -Value "svchost" -CIn ProcessName

CIn resembles CContains, except that the property and value positions are reversed.
For
example, the following statements are both true.

"abc", "def" -CContains "abc"

"abc" -CIn "abc", "def"


This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-CLE

Indicates that this cmdlet gets objects if the property value is less-than or equal to
the specified
value. This operation is case-sensitive.

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-CLike

Indicates that this cmdlet gets objects if the property value matches a value that
includes wildcard
characters ( * ). This operation is case-sensitive.

For example: Get-Process | where ProcessName -CLike "*host"

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-CLT

Indicates that this cmdlet gets objects if the property value is less-than the specified
value. This
operation is case-sensitive.

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-CMatch

Indicates that this cmdlet gets objects if the property value matches the specified
regular
expression. This operation is case-sensitive. When the input is a single object,
the matched value
is saved in the $Matches automatic variable.

For example: Get-Process | where ProcessName -CMatch "Shell"

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-CNE

Indicates that this cmdlet gets objects if the property value is different than the
specified value.
This operation is case-sensitive.

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-CNotContains

Indicates that this cmdlet gets objects if the property value of the object isn't an
exact match
for the specified value. This operation is case-sensitive.

For example: Get-Process | where ProcessName -CNotContains "svchost"

NotContains and CNotContains refer to a collection of values and are true when the
collection doesn't contain any items that are an exact match for the specified value. If
the input
is a single object, PowerShell converts it to a collection of one object.

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-CNotIn

Indicates that this cmdlet gets objects if the property value isn't an exact match for
the
specified value. This operation is case-sensitive.

For example: Get-Process | where -Value "svchost" -CNotIn -Property ProcessName

NotIn and CNotIn operators resemble NotContains and CNotContains, except that
the
property and value positions are reversed. For example, the following statements
are true.

"abc", "def" -CNotContains "Abc"

"abc" -CNotIn "Abc", "def"

Type: SwitchParameter

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-CNotLike

Indicates that this cmdlet gets objects if the property value doesn't match a value
that includes
wildcard characters. This operation is case-sensitive.

For example: Get-Process | where ProcessName -CNotLike "*host"

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-CNotMatch

Indicates that this cmdlet gets objects if the property value doesn't match the
specified regular
expression. This operation is case-sensitive. When the input is a
single object, the matched value
is saved in the $Matches automatic variable.

For example: Get-Process | where ProcessName -CNotMatch "Shell"

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Contains
Indicates that this cmdlet gets objects if any item in the property value of the object
is an exact
match for the specified value.

For example: Get-Process | where ProcessName -Contains "Svchost"

If the input is a single object, PowerShell converts it to a collection of one object.

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Aliases: IContains

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-EQ

Indicates that this cmdlet gets objects if the property value is the same as the
specified value.

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Aliases: IEQ

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-FilterScript

Specifies the script block that's used to filter the objects. Enclose the script block in
braces
( {} ).

The parameter name, FilterScript, is optional.

Type: ScriptBlock
Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-GE

Indicates that this cmdlet gets objects if the property value is greater than or equal
to the
specified value.

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Aliases: IGE

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-GT

Indicates that this cmdlet gets objects if the property value is greater than the
specified value.

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Aliases: IGT

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-In
Indicates that this cmdlet gets objects if the property value matches any of the
specified values.
For example:

Get-Process | where -Property ProcessName -in -Value "Svchost", "TaskHost",

"WsmProvHost"

If the input is a single object, PowerShell converts it to a collection of one object.

If the property value of an object is an array, PowerShell uses reference equality to


determine a
match. Where-Object returns the object only if the value of the Property
parameter and any
value of Value are the same instance of an object.

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Aliases: IIn

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies the objects to filter. You can also pipe the objects to Where-Object .

When you use the InputObject parameter with Where-Object , instead of piping
command results
to Where-Object , the cmdlet treats the InputObject as a single
object. This is true even if
the value is a collection that's the result of a command,
such as -InputObject (Get-Process) .

Because InputObject can't return individual properties from an array or collection of


objects,
we recommend that, if you use Where-Object to filter a collection of objects
for those objects
that have specific values in defined properties, you use Where-
Object in the pipeline, as shown
in the examples in this topic.

Type: PSObject

Position: Named

Default value: None

Accept pipeline input: True


Accept wildcard characters: False

-Is

Indicates that this cmdlet gets objects if the property value is an instance of the
specified .NET
type. Enclose the type name in square brackets.

For example, Get-Process | where StartTime -Is [DateTime]

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-IsNot

Indicates that this cmdlet gets objects if the property value isn't an instance of the
specified
.NET type.

For example, Get-Process | where StartTime -IsNot [DateTime]

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-LE

Indicates that this cmdlet gets objects if the property value is less than or equal to
the specified
value.

This parameter was introduced in Windows PowerShell 3.0.


Type: SwitchParameter

Aliases: ILE

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Like

Indicates that this cmdlet gets objects if the property value matches a value that
includes wildcard
characters ( * ).

For example: Get-Process | where ProcessName -Like "*host"

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Aliases: ILike

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-LT

Indicates that this cmdlet gets objects if the property value is less than the specified
value.

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Aliases: ILT

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-Match

Indicates that this cmdlet gets objects if the property value matches the specified
regular
expression. When the input is a single object, the matched value is saved in
the $Matches
automatic variable.

For example: Get-Process | where ProcessName -Match "shell"

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Aliases: IMatch

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-NE

Indicates that this cmdlet gets objects if the property value is different than the
specified value.

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Aliases: INE

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-NotContains

Indicates that this cmdlet gets objects if none of the items in the property value is an
exact match
for the specified value.
For example: Get-Process | where ProcessName -NotContains "Svchost"

NotContains refers to a collection of values and is true if the collection doesn't


contain any
items that are an exact match for the specified value. If the input is a
single object, PowerShell
converts it to a collection of one object.

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Aliases: INotContains

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-NotIn

Indicates that this cmdlet gets objects if the property value isn't an exact match for
any of the
specified values.

For example: Get-Process | where -Value "svchost" -NotIn -Property ProcessName

If the value of Value is a single object, PowerShell converts it to a collection of one


object.

If the property value of an object is an array, PowerShell uses reference equality to


determine a
match. Where-Object returns the object only if the value of Property and
any value of
Value aren't the same instance of an object.

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Aliases: INotIn

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-NotLike

Indicates that this cmdlet gets objects if the property value doesn't match a value
that includes
wildcard characters ( * ).

For example: Get-Process | where ProcessName -NotLike "*host"

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Aliases: INotLike

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-NotMatch

Indicates that this cmdlet gets objects when the property value doesn't match the
specified regular
expression. When the input is a single object, the matched value is
saved in the $Matches
automatic variable.

For example: Get-Process | where ProcessName -NotMatch "PowerShell"

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Aliases: INotMatch

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Property

Specifies the name of an object property. The parameter name, Property, is optional.

This parameter was introduced in Windows PowerShell 3.0.


Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Value

Specifies a property value. The parameter name, Value, is optional. This parameter
accepts
wildcard characters when used with the following comparison parameters:

CLike
CNotLike
Like
NotLike

This parameter was introduced in Windows PowerShell 3.0.

Type: PSObject

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

Inputs
PSObject

You can pipe any object to this cmdlet.

Outputs
Object

This cmdlet returns the selected items from the input object set.

Notes
Windows PowerShell includes the following aliases for Where-Object :

?
where

Starting in Windows PowerShell 4.0, Where and ForEach methods were added for use
with
collections.

You can read more about these methods here about_arrays

Related Links
Compare-Object
ForEach-Object
Group-Object
Measure-Object
New-Object
Select-Object
Sort-Object
Tee-Object
about_Booleans
Microsoft.PowerShell.Diagnostics
Reference

This section contains the help topics for the cmdlets that are installed with the
PowerShell
Microsoft.PowerShell.Diagnostics module, which contains cmdlets that
manage data from event logs.

Microsoft.PowerShell.Diagnostics
Export-Counter Exports performance counter data to log files.

Get-Counter Gets performance counter data from local and remote


computers.

Get-WinEvent Gets events from event logs and event tracing log files on local
and remote computers.

Import-Counter Imports performance counter log files and creates the objects
that represent each counter sample in
the log.

New-WinEvent Creates a new Windows event for the specified event provider.
Export-Counter
Reference
Module: Microsoft.PowerShell.Diagnostics

Exports performance counter data to log files.

Syntax
PowerShell

Export-Counter

[-Path] <String>

[-FileFormat <String>]

[-MaxSize <UInt32>]

-InputObject <PerformanceCounterSampleSet[]>

[-Force]

[-Circular]

[<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 use this
cmdlet to log performance counter data.

The Export-Counter cmdlet is designed to export data that is returned by the Get-
Counter and
Import-Counter cmdlets.

This cmdlet runs only on Windows 7, Windows Server 2008 R2, and later versions of
Windows.

Examples

EXAMPLE 1: Export counter data to a file


This example exports counter data to a BLG file.

PowerShell
Get-Counter "\Processor(*)\% Processor Time" | Export-Counter -Path
$HOME\Counters.blg

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 example sends the data to Export-
Counter through
the pipeline. If the data were saved in a variable, you might use a

disproportionate amount of
memory.

Example 2: Export a file to a counter file format


This example converts a CSV file to a counter data BLG format.

The Import-Counter cmdlet imports 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 the Export-Counter cmdlet to
create a circular log that wraps at
1 GB. The MaxSize parameter is expressed in
megabytes.

PowerShell

$1GBInMB = 1024 # 1GB = 1024MB

Import-Counter Threads.csv | Export-Counter -Path ThreadTest.blg -Circular -


MaxSize $1GBInMB

Example 3: Get counter data from a remote computer and


save the data to a file
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 of
the Server01 computer.
PowerShell

$C = Get-Counter -ComputerName Server01 -Counter "\Process(*)\Working Set -


Private" -MaxSamples $C | Export-Counter -Path
\\Server01\Perf\WorkingSet.blg

20

Example 4: Re-log existing data


This example shows how to use the Import-Counter and Export-Counter cmdlets to re-
log 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 Where-Object cmdlet to select objects with CookedValue
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 parameter to
indicate that the selected data
should be logged in the LowDiskSpace.blg file.

PowerShell

$All = Import-Counter DiskSpace.blg

$LowSpace = $All | Where-Object {$_.CounterSamples.CookedValue -lt 15}

$LowSpace | Export-Counter -Path LowDiskSpace.blg

Parameters
-Circular

Indicates that the output file is a circular log with first in, first out (FIFO) format.
When you
include this parameter, the MaxSize parameter is required.

Type: SwitchParameter

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-FileFormat

Specifies the output format of the output log file.

The acceptable values for this parameter are:

CSV
TSV

BLG

The default value is BLG .

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Force

Overwrites and replaces an existing file if one exists in the location specified by the
Path
parameter.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies, as an array, the counter data to export. Enter a variable that contains the
data or a
command that gets the data, such as the Get-Counter or Import-Counter
cmdlet.
Type: PerformanceCounterSampleSet[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-MaxSize

Specifies the maximum size of the output file in megabytes (MB).

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.

Type: UInt32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Path

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.

The file format is determined by the value of the FileFormat parameter, not by the
file name
extension in the path.

Type: String

Aliases: PSPath

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False


Inputs
PerformanceCounterSampleSet

You can pipe performance counter data from Get-Counter or Import-Counter to this
cmdlet.

Outputs
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
instance, 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 remote Windows PowerShell Windows PowerShell, you can
use the Invoke-Command cmdlet
to run an Import-Counter command on a remote
computer.

Related Links
Get-Counter
Import-Counter
Get-Counter
Reference
Module: Microsoft.PowerShell.Diagnostics

Gets performance counter data from local and remote computers.

Syntax
PowerShell

Get-Counter

[[-Counter] <String[]>]

[-SampleInterval <Int32>]

[-MaxSamples <Int64>]

[-Continuous]

[-ComputerName <String[]>]

[<CommonParameters>]

PowerShell

Get-Counter

[-ListSet] <String[]>

[-ComputerName <String[]>]

[<CommonParameters>]

Description
The Get-Counter cmdlet gets performance counter data directly from the performance
monitoring
instrumentation in the Windows family of operating systems. Get-Counter
gets performance data from
a local computer or remote computers.

You can use the Get-Counter parameters to specify one or more computers, list the
performance
counter sets and the instances they contain, set the sample intervals, and
specify the maximum
number of samples. Without parameters, Get-Counter gets
performance counter data for a set of
system counters.

Many counter sets are protected by access control lists (ACL). To see all counter sets,
open
PowerShell with the Run as administrator option.

7 Note
Performance counter names are localized. The examples shown here use the
English names of the
performance objects, counters, and instances. The names will
be different on a system that uses
another language. Use the Get-Counter -ListSet
command to see the localized names.

Examples

Example 1: Get the counter set list


This example gets the local computer's list of counter sets.

PowerShell

Get-Counter -ListSet *

CounterSetName : Processor

MachineName : .

CounterSetType : MultiInstance

Description : The Processor performance object consists of counters


that measure aspects ...

computer that performs arithmetic and logical


computations, initiates ...

computer can have multiple processors. The processor


object represents ...

Paths : {\Processor(*)\% Processor Time, \Processor(*)\% User


Time, ...

PathsWithInstances : {\Processor(0)\% Processor Time, \Processor(1)\%


Processor Time, ...

Counter : {\Processor(*)\% Processor Time, \Processor(*)\% User


Time, ...

Get-Counter uses the ListSet parameter with an asterisk ( * ) to get the list of counter

sets.
The dot ( . ) in the MachineName column represents the local computer.

Example 2: Specify the SampleInterval and MaxSamples


This examples gets the counter data for all processors on the local computer. Data is
collected at
two-second intervals until there are three samples.

PowerShell

Get-Counter -Counter "\Processor(_Total)\% Processor Time" -SampleInterval 2


-MaxSamples 3

Timestamp CounterSamples

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

6/18/2019 14:39:56 \\Computer01\processor(_total)\% processor time :

20.7144271584086

6/18/2019 14:39:58 \\Computer01\processor(_total)\% processor time :

10.4391790575511

6/18/2019 14:40:01 \\Computer01\processor(_total)\% processor time :

37.5968799396998

Get-Counter uses the Counter parameter to specify the counter path


\Processor(_Total)\% Processor Time . The SampleInterval parameter sets a two-second

interval
to check the counter. MaxSamples determines that three is the maximum
number of times to check
the counter.

Example 3: Get continuous samples of a counter


This examples gets continuous samples for a counter every second. To stop the
command, press
CTRL + C . To specify a longer interval between samples, use the
SampleInterval parameter.

PowerShell

Get-Counter -Counter "\Processor(_Total)\% Processor Time" -Continuous

Timestamp CounterSamples

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

6/19/2019 15:35:03 \\Computer01\processor(_total)\% processor time :

43.8522842937022

6/19/2019 15:35:04 \\Computer01\processor(_total)\% processor time :

29.7896844697383

6/19/2019 15:35:05 \\Computer01\processor(_total)\% processor time :

29.4962645638135

6/19/2019 15:35:06 \\Computer01\processor(_total)\% processor time :

25.5901500127408

Get-Counter uses the Counter parameter to specify the \Processor\% Processor Time
counter.
The Continuous parameter specifies to get samples every second until the
command is stopped with
CTRL + C .

Example 4: Alphabetical list of counter sets


This example uses the pipeline to get the counter list set and then sort the list in
alphabetical
order.

PowerShell

Get-Counter -ListSet * | Sort-Object -Property CounterSetName | Format-Table


-AutoSize

CounterSetName MachineName CounterSetType


Description

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


-

.NET CLR Data . SingleInstance .Net CLR


Data

.NET Data Provider for SqlServer . SingleInstance Counters


for System.Data.SqlClient

AppV Client Streamed Data Percentage . SingleInstance Size of


data streamed to disk ...

Authorization Manager Applications . SingleInstance The set of


Counters for ...

BitLocker . MultiInstance BitLocker


Drive Encryption ...

Bluetooth Device . SingleInstance Counters


related to a remote ...

Cache . SingleInstance The Cache


performance object ...

Client Side Caching . SingleInstance


Performance counters for SMB ...

Get-Counter uses the ListSet parameter with an asterisk ( * ) to get a complete list of
counter sets. The CounterSet objects are sent down the pipeline. Sort-Object uses the
Property parameter to specify that the objects are sorted by CounterSetName. The
objects are
sent down the pipeline to Format-Table . The AutoSize parameter adjusts the
column widths to
minimize truncation.

The dot ( . ) in the MachineName column represents the local computer.

Example 5: Run a background job to get counter data


In this example, Start-Job runs a Get-Counter command as a background job on the
local computer.
To view the performance counter output from the job, use the Receive-
Job cmdlet.

PowerShell

Start-Job -ScriptBlock {Get-Counter -Counter "\LogicalDisk(_Total)\% Free


Space" -MaxSamples 1000}

Id Name PSJobTypeName State HasMoreData Location Command

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

1 Job1 BackgroundJob Running True localhost Get-Counter -


Counter

Start-Job uses the ScriptBlock parameter to run a Get-Counter command. Get-Counter

uses
the Counter parameter to specify the counter path \LogicalDisk(_Total)\% Free
Space . The
MaxSamples parameter specifies to get 1000 samples of the counter.

Example 6: Get counter data from multiple computers


This example uses a variable to get performance counter data from two computers.

PowerShell

$DiskReads = "\LogicalDisk(C:)\Disk Reads/sec"

$DiskReads | Get-Counter -ComputerName Server01, Server02 -MaxSamples 10

Timestamp CounterSamples

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

6/21/2019 10:51:04 \\Server01\logicaldisk(c:)\disk reads/sec :

\\Server02\logicaldisk(c:)\disk reads/sec :

0.983050344269146

The $DiskReads variable stores the \LogicalDisk(C:)\Disk Reads/sec counter path. The
$DiskReads variable is sent down the pipeline to Get-Counter . Counter is the first
position
parameter and accepts the path stored in $DiskReads . ComputerName
specifies the two computers
and MaxSamples specifies to get 10 samples from each
computer.

Example 7: Get a counter's instance values from multiple


random computers
This example gets the value of a performance counter on 50 random, remote computers
in the
enterprise. The ComputerName parameter uses random computer names stored
in a variable. To
update the computer names in the variable, recreate the variable.

An alternative for the server names in the ComputerName parameter is to use a text file.
For
example:

-ComputerName (Get-Random (Get-Content -Path C:\Servers.txt) -Count 50)


The counter path includes an asterisk ( * ) in the instance name to get the data for each
of the
remote computer's processors.

PowerShell

$Servers = Get-Random (Get-Content -Path C:\Servers.txt) -Count 50

$Counter = "\Processor(*)\% Processor Time"

Get-Counter -Counter $Counter -ComputerName $Servers

Timestamp CounterSamples

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

6/20/2019 12:20:35 \\Server01\processor(0)\% processor time :

6.52610319637854

\\Server01\processor(1)\% processor time :

3.41030663625782

\\Server01\processor(2)\% processor time :

9.64189975649925

\\Server01\processor(3)\% processor time :

1.85240835619747

\\Server01\processor(_total)\% processor time :

5.35768447160776

The Get-Random cmdlet uses Get-Content to select 50 random computer names from
the
Servers.txt file. The remote computer names are stored in the $Servers variable.
The
\Processor(*)\% Processor Time counter's path is stored in the $Counter variable.
Get-Counter
uses the Counter parameter to specify the counters in the $Counter
variable. The
ComputerName parameter specifies the computer names in the $Servers
variable.

Example 8: Use the Path property to get formatted path


names
This example uses the Path property of a counter set to find the formatted path names
for the
performance counters.

The pipeline is used with the Where-Object cmdlet to find a subset of the path names. To
find a
counter sets complete list of counter paths, remove the pipeline ( | ) and Where-
Object command.

The $_ is an automatic variable for the current object in the pipeline.


For more
information, see about_Automatic_Variables.
PowerShell

(Get-Counter -ListSet Memory).Paths | Where-Object { $_ -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

\Memory\Long-Term Average Standby Cache Lifetime (s)

Get-Counter uses the ListSet parameter to specify the Memory counter set. The

command is
enclosed in parentheses so that the Paths property returns each path as a
string. The objects
are sent down the pipeline to Where-Object . Where-Object uses the
variable $_ to process each
object and uses the -like operator to find matches for the
string *Cache* . The asterisks ( * )
are wildcards for any characters.

Example 9: Use the PathsWithInstances property to get


formatted path names
This example gets the formatted path names that include the instances for the
PhysicalDisk
performance counters.

PowerShell

(Get-Counter -ListSet PhysicalDisk).PathsWithInstances

\PhysicalDisk(0 C:)\Current Disk Queue Length

\PhysicalDisk(_Total)\Current Disk Queue Length

\PhysicalDisk(0 C:)\% Disk Time

\PhysicalDisk(_Total)\% Disk Time


\PhysicalDisk(0 C:)\Avg. Disk Queue Length

\PhysicalDisk(_Total)\Avg. Disk Queue Length

\PhysicalDisk(0 C:)\% Disk Read Time

\PhysicalDisk(_Total)\% Disk Read Time

Get-Counter uses the ListSet parameter to specify the PhysicalDisk counter set. The

command is enclosed in parentheses so that the PathsWithInstances property returns


each path
instance as a string.

Example 10: Get a single value for each counter in a


counter set
In this example, a single value is returned for each performance counter in the local
computer's
Memory counter set.

PowerShell

$MemCounters = (Get-Counter -ListSet Memory).Paths

Get-Counter -Counter $MemCounters

Timestamp CounterSamples

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

6/19/2019 12:05:00 \\Computer01\memory\page faults/sec :

868.772077545597

\\Computer01\memory\available bytes :

9031176192

\\Computer01\memory\committed bytes :

8242982912

\\Computer01\memory\commit limit :

19603333120

Get-Counter uses the ListSet parameter to specify the Memory counter set. The

command is
enclosed in parentheses so that the Paths property returns each path as a
string. The paths are
stored in the $MemCounters variable. Get-Counter uses the Counter
parameter to specify the
counter paths in the $MemCounters variable.

Example 11: Display an object's property values


The property values in the PerformanceCounterSample object represent each data
sample. In this
example we use the properties of the CounterSamples object to
examine, select, sort, and group
the data.

PowerShell

$Counter = "\\Server01\Process(Idle)\% Processor Time"

$Data = Get-Counter $Counter

$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 : 6/19/2019 12:20:49

Timestamp100NSec : 128606207528320000

Status : 0

DefaultScale : 0

TimeBase : 10000000

The counter path is stored in the $Counter variable. Get-Counter gets one sample of the
counter
values and stores the results in the $Data variable. The $Data variable uses the
CounterSamples property to get the object's properties. The object is sent down the
pipeline to
Format-List . The Property parameter uses an asterisk ( * ) wildcard to select
all the
properties.

Example 12: Performance counter array values


In this example, a variable stores each performance counter. The CounterSamples
property is an
array that can display specific counter values.

To display each counter sample, use $Counter.CounterSamples .

PowerShell

$Counter = Get-Counter -Counter "\Processor(*)\% Processor Time"

$Counter.CounterSamples[0]

Path InstanceName CookedValue

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

\\Computer01\processor(0)\% processor time 0 1.33997091699662

Get-Counter uses the Counter parameter to specify the counter


\Processor(*)\%
Processor Time . The values are stored in the $Counter variable.

$Counter.CounterSamples[0] displays the array value for the first counter value.

Example 13: Compare performance counter values


This example finds the amount of processor time used by each processor on the local
computer. The
CounterSamples property is used to compare the counter data against a
specified value.

To display each counter sample, use $Counter.CounterSamples .

PowerShell

$Counter = Get-Counter -Counter "\Processor(*)\% Processor Time"

$Counter.CounterSamples | Where-Object { $_.CookedValue -lt "20" }

Path InstanceName CookedValue

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

\\Computer01\processor(0)\% processor time 0 12.6398025240208

\\Computer01\processor(1)\% processor time 1 15.7598095767344

Get-Counter uses the Counter parameter to specify the counter


\Processor(*)\%

Processor Time . The values are stored in the $Counter variable. The objects
stored in
$Counter.CounterSamples are sent down the pipeline. Where-Object uses a script block

to compare each objects value against a specified value of 20 . The $_.CookedValue is a


variable
for the current object in the pipeline. Counters with a CookedValue that is less
than 20 are
displayed.

Example 14: Sort performance counter data


This example shows how to sort performance counter data. The example finds the
processes on the
computer that are using the most processor time during the sample.

PowerShell

$Procs = Get-Counter -Counter "\Process(*)\% Processor Time"

$Procs.CounterSamples | Sort-Object -Property CookedValue -Descending |

Format-Table -Property Path, InstanceName, CookedValue -AutoSize

Path InstanceName
CookedValue

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

\\Computer01\process(_total)\% processor time _total


395.464129650573

\\Computer01\process(idle)\% processor time idle


389.356575524695

\\Computer01\process(mssense)\% processor time mssense


3.05377706293879

\\Computer01\process(csrss#1)\% processor time csrss


1.52688853146939

\\Computer01\process(microsoftedgecp#10)\% processor time microsoftedgecp


1.52688853146939

\\Computer01\process(runtimebroker#5)\% processor time runtimebroker


0

\\Computer01\process(settingsynchost)\% processor time settingsynchost


0

\\Computer01\process(microsoftedgecp#16)\% processor time microsoftedgecp


0

Get-Counter uses the Counter parameter to specify the \Process(*)\% Processor Time

counter
for all the processes on the local computer. The result is stored in the $Procs
variable. The
$Procs variable with the CounterSamples property sends the
PerformanceCounterSample
objects down the pipeline. Sort-Object uses the Property
parameter to sort the objects by
CookedValue in Descending order. Format-Table uses
the Property parameter to select
the columns for the output. The AutoSize parameter
adjusts the column widths to minimize
truncation.

Parameters
-ComputerName

Specifies one computer name or a comma-separated array of remote computer


names. Use the NetBIOS
name, an IP address, or the computer's fully qualified
domain name.

To get performance counter data from the local computer, exclude the
ComputerName parameter.
For output such as a ListSet that contains the
MachineName column, a dot ( . ) indicates the
local computer.

Get-Counter doesn't rely on PowerShell remoting. You can use the ComputerName
parameter even
if your computer isn't configured to run remote commands.

Type: String[]

Aliases: Cn

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Continuous

When Continuous is specified, Get-Counter gets samples until you press


CTRL + C .
Samples are obtained every second for each specified performance
counter. Use the
SampleInterval parameter to increase the interval between continuous samples.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-Counter

Specifies the path to one or more counter paths. Paths are input as a comma-
separated array, a
variable, or values from a text file. You can send counter path
strings down the pipeline to
Get-Counter .

Counter paths use the following syntax:

\\ComputerName\CounterSet(Instance)\CounterName

\CounterSet(Instance)\CounterName

For example:

\\Server01\Processor(*)\% User Time

\Processor(*)\% User Time

The \\ComputerName is optional in a performance counter path. If the counter path


doesn't include
the computer name, Get-Counter uses the local computer.

An asterisk ( * ) in the instance is a wildcard character to get all instances of the


counter.

Type: String[]

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-ListSet

Lists the performance counter sets on the computers. Use an asterisk ( * ) to specify
all counter
sets. Enter one name or a comma-separated string of counter set names.
You can send counter set
names down the pipeline.

To get a counter sets formatted counter paths, use the ListSet parameter. The Paths
and
PathsWithInstances properties of each counter set contain the individual
counter paths formatted
as a string.
You can save the counter path strings in a variable or use the pipeline to send the
string to
another Get-Counter command.

For example to send each Processor counter path to Get-Counter :

Get-Counter -ListSet Processor | Get-Counter

Type: String[]

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-MaxSamples

Specifies the number of samples to get from each specified performance counter. To
get a constant
stream of samples, use the Continuous parameter.

If the MaxSamples parameter isn't specified, Get-Counter only gets one sample for
each
specified counter.

To collect a large data set, run Get-Counter as a PowerShell background job. For
more information,
see about_Jobs.

Type: Int64

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SampleInterval

Specifies the number of seconds between samples for each specified performance
counter. If the
SampleInterval parameter isn't specified, Get-Counter uses a one-
second interval.

Type: Int32

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String[]

Get-Counter accepts pipeline input for counter paths and counter set names.

Outputs
CounterSet

With the ListSet parameter, this cmdlet returns CounterSet objects.

PerformanceCounterSampleSet

By default and with the Counter parameter, this cmdlet returns


PerformanceCounterSampleSet
objects.

Notes
If no parameters are specified, Get-Counter gets one sample for each specified
performance
counter. Use the MaxSamples and Continuous parameters to get more
samples.

Get-Counter uses a one-second interval between samples. Use the SampleInterval


parameter to
increase the interval.

The MaxSamples and SampleInterval values apply to all the counters on each computer
in the
command. To set different values for different counters, enter separate Get-
Counter commands.

Related Links
about_Automatic_Variables
about_Jobs
Format-List
Format-Table
Get-Member
Receive-Job
Start-Job
Where-Object
Get-WinEvent
Reference
Module: Microsoft.PowerShell.Diagnostics

Gets events from event logs and event tracing log files on local and remote computers.

Syntax
PowerShell

Get-WinEvent

[[-LogName] <String[]>]

[-MaxEvents <Int64>]

[-ComputerName <String>]

[-Credential <PSCredential>]

[-FilterXPath <String>]

[-Force]

[-Oldest]

[<CommonParameters>]

PowerShell

Get-WinEvent

[-ListLog] <String[]>

[-ComputerName <String>]

[-Credential <PSCredential>]

[-Force]

[<CommonParameters>]

PowerShell

Get-WinEvent

[-ListProvider] <String[]>

[-ComputerName <String>]

[-Credential <PSCredential>]

[<CommonParameters>]

PowerShell

Get-WinEvent

[-ProviderName] <String[]>

[-MaxEvents <Int64>]

[-ComputerName <String>]

[-Credential <PSCredential>]

[-FilterXPath <String>]

[-Force]

[-Oldest]

[<CommonParameters>]

PowerShell

Get-WinEvent

[-Path] <String[]>

[-MaxEvents <Int64>]

[-Credential <PSCredential>]

[-FilterXPath <String>]

[-Oldest]

[<CommonParameters>]

PowerShell

Get-WinEvent

[-MaxEvents <Int64>]

[-ComputerName <String>]

[-Credential <PSCredential>]

[-FilterHashtable] <Hashtable[]>

[-Force]

[-Oldest]

[<CommonParameters>]

PowerShell

Get-WinEvent

[-MaxEvents <Int64>]

[-ComputerName <String>]

[-Credential <PSCredential>]

[-FilterXml] <XmlDocument>

[-Oldest]

[<CommonParameters>]

Description
The Get-WinEvent cmdlet gets events from event logs, including classic logs, such as the
System and Application logs. The cmdlet gets data from event logs that are generated
by the
Windows Event Log technology introduced in Windows Vista and events in log
files generated by
Event Tracing for Windows (ETW). By default, Get-WinEvent returns
event information in the
order of newest to oldest.

Get-WinEvent lists event logs and event log providers. To interrupt the command, press

CTRL + C . 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 using XPath queries, structured XML
queries, and hash
table queries.

If you're not running PowerShell as an Administrator, you might see error messages that
you cannot
retrieve information about a log.

Examples

Example 1: Get all the logs from a local computer


This command gets all the event logs on the local computer. Logs are listed in the order
that
Get-WinEvent gets them. Classic logs are retrieved first, followed by the new
Windows Event logs.
It's possible for a log's RecordCount to be null, which is blank, or
zero.

PowerShell

Get-WinEvent -ListLog *

LogMode MaximumSizeInBytes RecordCount LogName

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

Circular 15532032 14500 Application

Circular 1052672 117 Azure Information Protection

Circular 1052672 3015 CxAudioSvcLog

Circular 20971520 ForwardedEvents

Circular 20971520 0 HardwareEvents

The Get-WinEvent cmdlet gets log information from the computer. The ListLog
parameter uses the
asterisk ( * ) wildcard to display information about each log.

Example 2: Get the classic Setup log


This command gets an EventLogConfiguration object that represents the classic Setup
log. The
object includes information about the log, such as file size, provider, file path,
and whether the
log is enabled.

PowerShell

Get-WinEvent -ListLog Setup | Format-List -Property *

FileSize : 69632

IsLogFull : False

LastAccessTime : 3/13/2019 09:41:46

LastWriteTime : 3/13/2019 09:41:46

OldestRecordNumber : 1

RecordCount : 23

LogName : Setup

LogType : Operational

LogIsolation : Application

IsEnabled : True

IsClassicLog : False

SecurityDescriptor : O:BAG:SYD: ...

LogFilePath :
%SystemRoot%\System32\Winevt\Logs\Setup.evtx

MaximumSizeInBytes : 1052672

LogMode : Circular

OwningProviderName : Microsoft-Windows-Eventlog

ProviderNames : {Microsoft-Windows-WUSA, Microsoft-Windows-


ActionQueue...

ProviderLevel :

ProviderKeywords :

ProviderBufferSize : 64

ProviderMinimumNumberOfBuffers : 0

ProviderMaximumNumberOfBuffers : 64

ProviderLatency : 1000

ProviderControlGuid :

The Get-WinEvent cmdlet uses the ListLog parameter to specify the Setup log. The
object is
sent down the pipeline to the Format-List cmdlet. Format-List uses the
Property parameter
with the asterisk ( * ) wildcard to display each property.

Example 3: Configure the classic Security log


This command gets an EventLogConfiguration object that represents the classic
Security log. The
object is then used to configure settings for the log, such as max file
size, file path, and whether the
log is enabled.

PowerShell

$log = Get-WinEvent -ListLog Security

$log.MaximumSizeInBytes = 1gb

try{

$log.SaveChanges()

Get-WinEvent -ListLog Security | Format-List -Property *

}catch [System.UnauthorizedAccessException]{

$ErrMsg = 'You do not have permission to configure this log!'

$ErrMsg += ' Try running this script with administrator privileges. '

$ErrMsg += $_.Exception.Message

Write-Error $ErrMsg

FileSize : 69632

IsLogFull : False

LastAccessTime : 3/13/2019 09:41:46

LastWriteTime : 3/13/2019 09:41:46

OldestRecordNumber : 1

RecordCount : 23

LogName : Security

LogType : Administrative

LogIsolation : Custom

IsEnabled : True

IsClassicLog : True

SecurityDescriptor : O:BAG:SYD: ...

LogFilePath :
%SystemRoot%\System32\Winevt\Logs\Security.evtx

MaximumSizeInBytes : 1073741824

LogMode : Circular

OwningProviderName :

ProviderNames : {Microsoft-Windows-WUSA, Microsoft-Windows-


ActionQueue...

ProviderLevel :

ProviderKeywords :

ProviderBufferSize : 64

ProviderMinimumNumberOfBuffers : 0

ProviderMaximumNumberOfBuffers : 64

ProviderLatency : 1000

ProviderControlGuid :

The Get-WinEvent cmdlet uses the ListLog parameter to specify the Security log. The
object is
saved to a variable. The MaximumSizeInBytes property is set to 1 gigabyte on
the object. The
SaveChanges method is called to push the change to the system inside
of a try block to handle
access violations. The Get-WinEvent cmdlet is called again on
the Security log and piped to the
Format-List cmdlet to verify that the
MaximumSizeInBytes property has been saved on the machine.

Example 4: Get event logs from a server


This command only gets event logs on the local computer that contain events. It's
possible for a
log's RecordCount to be null or zero. The example uses the $_ variable.
For more information,
see about_Automatic_Variables.

PowerShell

Get-WinEvent -ListLog * -ComputerName localhost | Where-Object {


$_.RecordCount }

LogMode MaximumSizeInBytes RecordCount LogName

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

Circular 15532032 14546 Application

Circular 1052672 117 Azure Information Protection

Circular 1052672 2990 CxAudioSvcLog

Circular 1052672 9 MSFTVPN Setup

Circular 1052672 282 OAlerts

The Get-WinEvent cmdlet gets log information from the computer. The ListLog
parameter uses the
asterisk ( * ) wildcard to display information about each log. The
ComputerName parameter
specifies to get the logs from the local computer, localhost.
The objects are sent down the
pipeline to the Where-Object cmdlet. Where-Object uses
$_.RecordCount to return only logs that
contain data. $_ is a variable that represents the

current object in the pipeline. RecordCount


is a property of the object with a non-null
value.

Example 5: Get event logs from multiple servers


This example gets objects that represent the Application event logs on three computers:
Server01, Server02, and Server03. The ForEach keyword is used because the
ComputerName
parameter accepts only one value. For more information, see
about_Foreach.

PowerShell

$S = 'Server01', 'Server02', 'Server03'

ForEach ($Server in $S) {

Get-WinEvent -ListLog Application -ComputerName $Server |

Select-Object LogMode, MaximumSizeInBytes, RecordCount, LogName,

@{name='ComputerName'; expression={$Server}} |

Format-Table -AutoSize

LogMode MaximumSizeInBytes RecordCount LogName ComputerName

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

Circular 15532032 14577 Application Server01

Circular 15532032 9689 Application Server02

Circular 15532032 5309 Application Server03

The variable $S stores the names three servers: Server01, Server02, and Server03. The
ForEach statement uses a loop to process each server, ($Server in $S) . The script block
in the
curly braces ( { } ) runs the Get-WinEvent command. The ListLog parameter
specifies the
Application log. The ComputerName parameter uses the variable $Server
to get log
information from each server.

The objects are sent down the pipeline to the Select-Object cmdlet. Select-Object gets
the
properties LogMode, MaximumSizeInBytes, RecordCount, LogName, and uses a
calculated
expression to display the ComputerName using the $Server variable. The
objects are sent down
the pipeline to the Format-Table cmdlet to display the output in
the PowerShell console. The
AutoSize parameter formats the output to fit the screen.

Example 6: Get event log providers and log names


This command gets the event log providers and the logs to which they write.

PowerShell

Get-WinEvent -ListProvider *

Name : .NET Runtime

LogLinks : {Application}

Opcodes : {}

Tasks : {}

Name : .NET Runtime Optimization Service

LogLinks : {Application}

Opcodes : {}

Tasks : {}

The Get-WinEvent cmdlet gets log information from the computer. The ListProvider
parameter
uses the asterisk ( * ) wildcard to display information about each provider. In
the output, the
Name is the provider and LogLinks is the log that the provider writes to.

Example 7: Get all event log providers that write to a


specific log
This command gets all of the providers that write to the Application log.

PowerShell

(Get-WinEvent -ListLog Application).ProviderNames

.NET Runtime

.NET Runtime Optimization Service


Application

Application Error

Application Hang

Application Management

The Get-WinEvent cmdlet gets log information from the computer. The ListLog
parameter uses
Application to get objects for that log. ProviderNames is a property of
the object and
displays the providers that write to the Application log.
Example 8: Get event log provider names that contain a
specific string
This command gets the event log providers with names that include a specific string in
the
provider's name.

PowerShell

Get-WinEvent -ListProvider *Policy*

Name : Group Policy Applications

LogLinks : {Application}

Opcodes : {}

Tasks : {}

Name : Group Policy Client

LogLinks : {Application}

Opcodes : {}

Tasks : {}

Name : Group Policy Data Sources

LogLinks : {Application}

Opcodes : {}

Tasks : {}

The Get-WinEvent cmdlet gets log information from the computer. The ListProvider
parameter
uses the asterisk ( * ) wildcard to find Policy anywhere within the provider's
name.

Example 9: Get Event Ids that the event provider


generates
This command lists the Event Ids that the Microsoft-Windows-GroupPolicy event
provider generates
along with the event description.

PowerShell

(Get-WinEvent -ListProvider Microsoft-Windows-GroupPolicy).Events | Format-


Table Id, Description

Id Description

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

1500 The Group Policy settings for the computer were processed
successfully...

1501 The Group Policy settings for the user were processed successfully...

4115 Group Policy Service started.

4116 Started the Group Policy service initialization phase.

4117 Group Policy Session started.

The Get-WinEvent cmdlet gets log information from the computer. The ListProvider
parameter
specifies the provider, Microsoft-Windows-GroupPolicy. The expression is
wrapped in parentheses
and uses the Events property to get objects. The objects are
sent down the pipeline to the
Format-Table cmdlet. Format-Table displays the Id and
Description of the event objects.

Example 10: Get log information from event object


properties
This example shows how to get information about a log's contents using event object
properties.
Event objects are stored in a variable and then grouped and counted by
Event Id and Level.

PowerShell

$Event = Get-WinEvent -LogName 'Windows PowerShell'

$Event.Count

$Event | Group-Object -Property Id -NoElement | Sort-Object -Property Count


-Descending

$Event | Group-Object -Property LevelDisplayName -NoElement

195

Count Name

----- ----

147 600

22 400

21 601

3 403

2 103

Count Name

----- ----

2 Warning

193 Information

The Get-WinEvent cmdlet uses the LogName parameter to specify the Windows
PowerShell event
log. The event objects are stored in the $Event variable. The Count
property of $Event shows
the total number of logged events.

The $Event variable is sent down the pipeline to the Group-Object cmdlet. Group-Object
uses
the Property parameter to specify the Id property and counts the objects by the
event Id
value. The NoElement parameter removes other properties from the objects
output. The grouped
objects are sent down the pipeline to the Sort-Object cmdlet.
Sort-Object uses the Property
parameter to sort the objects by Count. The Descending
parameter displays the output by
count, from highest to lowest. In the output, the
Count column contains the total number of each
event. The Name column contains the
grouped event Id numbers.

The $Event variable is sent down the pipeline to the Group-Object cmdlet. Group-Object
uses
the Property parameter to specify the LevelDisplayName property and counts the
objects by
LevelDisplayName. The objects are grouped by the levels such as Warning
and Information.
The NoElement parameter removes other properties from the output.
In the output, the Count
column contains the total number of each event. The Name
column contains the grouped
LevelDisplayName.

Example 11: Get error events that have a specified string


in their name
This example uses a comma-separated string of log names. The output is grouped by
the level such as
error or warning and the log name.

PowerShell

Get-WinEvent -LogName *PowerShell*, Microsoft-Windows-Kernel-WHEA* |

Group-Object -Property LevelDisplayName, LogName -NoElement |

Format-Table -AutoSize

Count Name

----- ----

1 Error, PowerShellCore/Operational

26 Information, Microsoft-Windows-Kernel-WHEA/Operational

488 Information, Microsoft-Windows-PowerShell/Operational

77 Information, PowerShellCore/Operational

9835 Information, Windows PowerShell

19 Verbose, PowerShellCore/Operational

444 Warning, Microsoft-Windows-PowerShell/Operational


512 Warning, PowerShellCore/Operational

The Get-WinEvent cmdlet gets log information from the computer. The LogName
parameter uses a
comma-separated string with the asterisk ( * ) wildcard to specify the
log names. The objects are
sent down the pipeline to the Group-Object cmdlet. Group-
Object uses the Property parameter
to group the objects by LevelDisplayName and

LogName. The NoElement parameter removes


other properties from the output. The
grouped objects are sent down the pipeline to the
Format-Table cmdlet. Format-Table
uses the AutoSize parameter to format the columns. The
Count column contains the
total number of each event. The Name column contains the grouped
LevelDisplayName
and LogName.

Example 12: Get events from an archived event log


Get-WinEvent can get event information from saved log files. This sample uses an

archived
PowerShell log that is stored on the local computer.

PowerShell

Get-WinEvent -Path 'C:\Test\Windows PowerShell.evtx'

ProviderName: PowerShell

TimeCreated Id LevelDisplayName Message

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

3/15/2019 13:54:13 403 Information Engine state is changed from


Available to Stopped...

3/15/2019 13:54:13 400 Information Engine state is changed from


None to Available...

3/15/2019 13:54:13 600 Information Provider "Variable" is


Started...

3/15/2019 13:54:13 600 Information Provider "Function" is


Started...

3/15/2019 13:54:13 600 Information Provider "FileSystem" is


Started...

The Get-WinEvent cmdlet gets log information from the computer. The Path parameter
specifies
the directory and file name.

Example 13: Get a specific number of events from an


archived event log
These commands get a specific number of events from an archived event log. Get-
WinEvent has
parameters that can get a maximum number of events or the oldest
events. This sample uses an
archived PowerShell log that is stored in
C:\Test\PowerShellCore Operational.evtx.

PowerShell

Get-WinEvent -Path 'C:\Test\PowerShellCore Operational.evtx' -MaxEvents 100

ProviderName: PowerShellCore

TimeCreated Id LevelDisplayName Message

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

3/15/2019 09:54:54 4104 Warning Creating Scriptblock text


(1 of 1):...

3/15/2019 09:37:13 40962 Information PowerShell console is


ready for user input

3/15/2019 07:56:24 4104 Warning Creating Scriptblock text


(1 of 1):...

...

3/7/2019 10:53:22 40961 Information PowerShell console is


starting up

3/7/2019 10:53:22 8197 Verbose Runspace state changed to


Opening

3/7/2019 10:53:22 8195 Verbose Opening RunspacePool

The Get-WinEvent cmdlet gets log information from the computer. The Path parameter
specifies
the directory and filename. The MaxEvents parameter specifies that 100
records are displayed,
from newest to oldest.

Example 14: Event Tracing for Windows


Event Tracing for Windows (ETW) writes events to the log as events occur. The events
are stored in
the order of oldest to newest. An archived ETW file is saved as an .etl
such as TraceLog.etl.
The events are listed in the order in which they are written to the
log, so the Oldest parameter
is required.

PowerShell

Get-WinEvent -Path 'C:\Tracing\TraceLog.etl' -Oldest |

Sort-Object -Property TimeCreated -Descending |

Select-Object -First 100

The Get-WinEvent cmdlet gets log information from the archived file. The Path
parameter
specifies the directory and file name. The Oldest parameter is used to output
events in the
order they are written, oldest to newest. The objects are sent down the
pipeline to the
Sort-Object cmdlet Sort-Object sorts the objects in descending order
by the value of the
TimeCreated property. The objects are sent down the pipeline to the
Select-Object cmdlet that
displays the 100 newest events.

Example 15: Get events from an event trace log


This example shows how to get the events from an event trace log file ( .etl ) and an
archived
Windows PowerShell log file ( .evtx ). You can combine multiple file types in a
single command.
Because the files contain the same type of .NET Framework object,
EventLogRecord, you can
filter them with the same properties. The command requires
the Oldest parameter because it is
reading from an .etl file, but the Oldest parameter
applies to each file.

PowerShell

Get-WinEvent -Path 'C:\Tracing\TraceLog.etl', 'C:\Test\Windows


PowerShell.evtx' -Oldest |

Where-Object { $_.Id -eq '403' }

The Get-WinEvent cmdlet gets log information from the archived files. The Path
parameter uses
a comma-separated list to specify each files directory and file name. The
Oldest parameter is
used to output events in the order they are written, oldest to
newest. The objects are sent down the
pipeline to the Where-Object cmdlet. Where-
Object uses a script block to find events with an
Id of 403. The $_ variable represents
the current object in the pipeline and Id is the
Event Id property.

Example 16: Filter event log results


This example shows a variety of methods to filter and select 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. Filters are applied as
the objects are retrieved. Where-Object retrieves all of the
objects, then applies filters to all
of the objects.

PowerShell

# Using the Where-Object cmdlet:

$Yesterday = (Get-Date) - (New-TimeSpan -Day 1)

Get-WinEvent -LogName 'Windows PowerShell' | Where-Object { $_.TimeCreated -


ge $Yesterday }

# Using the FilterHashtable parameter:

$Yesterday = (Get-Date) - (New-TimeSpan -Day 1)

Get-WinEvent -FilterHashtable @{ LogName='Windows PowerShell'; Level=3;


StartTime=$Yesterday }

# Using the FilterXML parameter:

$xmlQuery = @'

<QueryList>

<Query Id="0" Path="Windows PowerShell">

<Select Path="System">*[System[(Level=3) and

TimeCreated[timediff(@SystemTime) <= 86400000]]]</Select>

</Query>

</QueryList>

'@

Get-WinEvent -FilterXML $xmlQuery

# Using the FilterXPath parameter:

$XPath = '*[System[Level=3 and TimeCreated[timediff(@SystemTime) <=


86400000]]]'

Get-WinEvent -LogName 'Windows PowerShell' -FilterXPath $XPath

Example 17: Use FilterHashtable to get events from the


Application log
This example uses the FilterHashtable parameter to get events from the Application
log. The
hash table uses key/value pairs. For more information about the
FilterHashtable parameter,
see Creating Get-WinEvent queries with FilterHashtable.
For
more information about hash tables, see about_Hash_Tables.

PowerShell

$Date = (Get-Date).AddDays(-2)

Get-WinEvent -FilterHashtable @{ LogName='Application'; StartTime=$Date;


Id='1003' }

The Get-Date cmdlet uses the AddDays method to get a date that is two days before
the current
date. The date object is stored in the $Date variable.

The Get-WinEvent cmdlet gets log information. The FilterHashtable parameter is used to
filter
the output. The LogName key specifies the value as the Application log. The
StartTime
key uses the value stored in the $Date variable. The Id key uses an Event Id
value, 1003.

Example 18: Use FilterHashtable to get application errors


This example uses the FilterHashtable parameter to find Internet Explorer application
errors
that occurred within the last week.

PowerShell

$StartTime = (Get-Date).AddDays(-7)

Get-WinEvent -FilterHashtable @{

Logname='Application'

ProviderName='Application Error'

Data='iexplore.exe'

StartTime=$StartTime

}
The Get-Date cmdlet uses the AddDays method to get a date that is seven days before
the
current date. The date object is stored in the $StartTime variable.

The Get-WinEvent cmdlet gets log information. The FilterHashtable parameter is used to
filter
the output. The LogName key specifies the value as the Application log. The
ProviderName
key uses the value, Application Error, which is the event's Source. The
Data key uses
the value iexplore.exe The StartTime key uses the value stored in
$StartTime variable.

Parameters
-ComputerName

Specifies the name of the computer that this cmdlet gets events from the event logs.
Type the
NetBIOS name, an IP address, or the fully qualified domain name (FQDN) of
the computer. The default
value is the local computer, localhost. This parameter
accepts only one computer name at a time.

To get event logs from remote computers, configure the firewall port for the event
log service to
allow remote access.

This cmdlet does not rely on PowerShell remoting. You can use the ComputerName
parameter even if
your computer is not configured to run remote commands.

Type: String

Aliases: Cn

Position: Named

Default value: Local computer

Accept pipeline input: False

Accept wildcard characters: False

-Credential

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 are prompted for
a password. If you type only the parameter name, you
are prompted for both a username and a
password.

Type: PSCredential

Position: Named

Default value: Current user

Accept pipeline input: False

Accept wildcard characters: False

-FilterHashtable

Specifies 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. For example, events in
classic event
logs.

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 Get-WinEvent key/value pairs are as follows:

LogName= <String[]>
ProviderName= <String[]>
Path= <String[]>
Keywords= <Long[]>
ID= <Int32[]>
Level= <Int32[]>
StartTime= <DateTime>
EndTime= <DateTime>
UserID= <SID>
Data= <String[]>

Type: Hashtable[]

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-FilterXml

Specifies a structured XML query that this cmdlet selects events from one or more
event logs.

To generate a valid XML query, use the Create Custom View and Filter Current Log
features in
Windows 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.

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 Query Schema
and the XML Event Queries section of Event Selection.

Type: XmlDocument

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-FilterXPath

Specifies an XPath query that this cmdlet select events from one or more logs.

For more information about the XPath language, see XPath Reference
and the
Selection Filters section of Event Selection.
Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Force

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, the Get-WinEvent cmdlet excludes these logs unless you specify the full
name of a
debug or analytic log.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ListLog

Specifies the event logs. Enter the event log names in a comma-separated list.
Wildcards are
permitted. To get all the logs, use the asterisk ( * ) wildcard.

Type: String[]

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-ListProvider
Specifies the event log providers that this cmdlet gets. 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, use the asterisk ( * ) wildcard.

Type: String[]

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-LogName

Specifies the event logs that this cmdlet get events from. Enter the event log names
in a
comma-separated list. Wildcards are permitted. You can also pipe log names to
the Get-WinEvent
cmdlet.

7 Note

PowerShell does not limit the amount of logs you can request. However, the
Get-WinEvent cmdlet
queries the Windows API which has a limit of 256. This can

make it difficult to filter through all


of your logs at one time. You can work
around this by using a foreach loop to iterate through each
log like this: Get-
WinEvent -ListLog * | ForEach-Object{ Get-WinEvent -LogName $_.Logname }

Type: String[]

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-MaxEvents

Specifies the maximum number of events that are returned. Enter an integer such as
100. The default
is to return all the events in the logs or files.
Type: Int64

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Oldest

Indicate that this cmdlet gets 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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Path

Specifies the path to the event log files that this cmdlet get events from. 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.

Type: String[]

Aliases: PSPath

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: True


-ProviderName

Specifies, as a string array, the event log providers from which this cmdlet gets
events. 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
PowerShell provider.

Type: String[]

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

Inputs
String

You can pipe a LogName (string) to this cmdlet.

XmlDocument

You can pipe a FilterXML query to this cmdlet.

Hashtable

You can pipe a FilterHashtable query to this cmdlet.

Outputs
EventLogConfiguration

With the ListLog parameter, this cmdlet returns EventLogConfiguration objects.

EventLogRecord

By default, this cmdlet returns EventLogRecord objects.

ProviderMetadata
With the ListProvider parameter, this cmdlet returns ProviderMetadata 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 for backward compatibility.

The Get-WinEvent and Get-EventLog cmdlets are not supported in Windows Pre-
installation
Environment (Windows PE).

Related Links
about_Automatic_Variables
about_Foreach
about_Hash_Tables
Creating Get-WinEvent queries with FilterHashtable
Format-Table
Group-Object
Sort-Object
Where-Object
Import-Counter
Reference
Module: Microsoft.PowerShell.Diagnostics

Imports performance counter log files and creates the objects that represent each
counter sample in
the log.

Syntax
PowerShell

Import-Counter

[-Path] <String[]>

[-StartTime <DateTime>]

[-EndTime <DateTime>]

[-Counter <String[]>]

[-MaxSamples <Int64>]

[<CommonParameters>]

PowerShell

Import-Counter

[-Path] <String[]>

-ListSet <String[]>

[<CommonParameters>]

PowerShell

Import-Counter

[-Path] <String[]>

[-Summary]

[<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 up to
32 files in each command. You can use the parameters of Import-
Counter to filter the data that you
import.

Along with the Get-Counter and Export-Counter cmdlets, this feature lets you collect,
export,
import, combine, filter, manipulate, and re-export performance counter data
within Windows
PowerShell.

Examples

Example 1: Import all counter data from a file


PowerShell

$data = Import-Counter -Path ProcessorData.csv

This command imports all counter data from the ProcessorData.csv file into the $data
variable.

Example 2: Import specific counter data from a file


PowerShell

$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: Select data from a performance counter then


export it to a file
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 the variable named $data . The last two commands
import selected data and then export
only the selected data.

PowerShell
$data = Import-Counter .\ProcessorData.blg

$data[0].CounterSamples | Format-Table -Property 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

$intCtrs = $Data[0].Countersamples | Where-Object {$_.Path -like


"*Interrupts/sec"} | ForEach-Object {$_.Path}

$intCtrs

\\SERVER01\Processor(_Total)\Interrupts/sec

\\SERVER01\Processor(1)\Interrupts/sec

\\SERVER01\Processor(0)\Interrupts/sec

$i = Import-Counter -Path .\ProcessorData.blg -Counter $intCtrs

$i | Export-Counter -Path .\Interrupts.csv -Format CSV

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. To get the
display shown in
the command output, the example uses the Format-Table cmdlet to
format as a table the counter
paths of the first counter in the $data variable.

The third command gets the counter paths that end in Interrupts/sec and saves the
paths in the
$intCtrs variable. It uses the Where-Object cmdlet to filter the counter
paths and the
ForEach-Object cmdlet to get only the value of the Path property of each
selected path object.

The fourth command displays the selected counter paths in the $intCtrs variable.

The fifth command uses the Import-Counter cmdlet to import the data. It uses the
$intCtrs
variable as the value of the Counter parameter to import only data for the

counter paths in
$intCtrs .

The sixth command uses the Export-Counter cmdlet to export the data to the
Interrupts.csv file.
Example 4: Display all counter paths in a group of
imported counter sets
This example shows how to display all the counter paths in a group of imported counter
sets.

PowerShell

Import-Counter -Path ProcessorData.csv -ListSet *

CounterSetName : Processor

MachineName : \\SERVER01

CounterSetType : MultiInstance

Description :

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

\Processor(0)\DPC Rate, \\SERVER01\Processor(_Total)\% Idle Time...}

Counter : {\\SERVER01\Processor(*)\DPC Rate,


\\SERVER01\Processor(*)\% Idle Time, \\SERVER01

\Processor(*)\% C3 Time, \\SERVER01\Processor(*)\% Interrupt Time...}

Import-Counter -Path ProcessorData.csv -ListSet * | ForEach-Object


{$_.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

The first command uses the ListSet parameter of the Import-Counter cmdlet 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: Import counter data from a range of
timestamps
This example imports only the counter data that has a timestamp between the starting
an ending
ranges specified in the command.

PowerShell

Import-Counter -Path ".\disk.blg" | Format-Table -Property Timestamp

$start = [datetime]"7/9/2008 3:47:00 PM"; $end = [datetime]"7/9/2008 3:47:59


PM"

Import-Counter -Path Disk.blg -StartTime $start -EndTime $end

The first command lists in a table the timestamps of all of the data in the
ProcessorData.blg
file.

The second command saves particular timestamps in the $start and $end variables.
The strings
are cast to DateTime objects.

The third command uses the Import-Counter cmdlet 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 of Import-Counter to specify the range.

Example 6: Import a specified number of the oldest


samples from a performance counter log file
This example shows how to import the five oldest and five newest samples from a
performance counter
log file.

PowerShell

Import-Counter -Path "Disk.blg" -MaxSamples 5

(Import-Counter -Path Disk.blg)[-1 .. -5]

The first command uses the Import-Counter cmdlet to import the first (oldest) five
samples from
the Disk.blg file. The command uses the MaxSamples parameter to limit
the import to five
counter samples.

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: Get a summary of counter data from a file


PowerShell

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

This command uses the Summary parameter of the Import-Counter cmdlet to get a
summary of the
counter data in the Memory.blg file.

Example 8: Update a performance counter log file


This example updates a performance counter log file.

PowerShell

$counters = Import-Counter OldData.blg -ListSet * | ForEach-Object


{$_.PathsWithInstances}

Get-Counter -Counter $Counters -MaxSamples 20 | Export-Counter


C:\Logs\NewData.blg

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 gets updated data for the counters in the $counters variable. It
uses the
Get-Counter cmdlet to get a current sample, and then export the results to the
NewData.blg file.

Example 9: Import performance log data from multiple


files and then save it
PowerShell

$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 the performance log

paths to Import-Counter,
which imports the data from the specified paths.
Notice that each path is enclosed in quotation marks and that the paths are separated
from each
other by a comma.

Parameters
-Counter

Specifies, as a string array, the 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. The ComputerName value is required in
the path. For
instance:

\\<ComputerName>\<CounterSet>(<Instance>)\<CounterName>

For example:

\\Server01\Processor(2)\% User Time


\\Server01\Processor(*)\% Processor Time

Type: String[]

Position: Named

Default value: All counter

Accept pipeline input: False

Accept wildcard characters: True

-EndTime

Specifies an end date and time that this cmdlet imports counter data between the
StartTime and
this parameter timestamps. 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.

Type: DateTime

Position: Named

Default value: No end time

Accept pipeline input: False


Accept wildcard characters: False

-ListSet

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

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-MaxSamples

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.

Type: Int64

Position: Named

Default value: No maximum

Accept pipeline input: False

Accept wildcard characters: False

-Path

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 .

Type: String[]

Aliases: PSPath
Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-StartTime

Specifies the start date and time in which this cmdlet gets counter data. 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.

Type: DateTime

Position: Named

Default value: No start time

Accept pipeline input: False

Accept wildcard characters: False

-Summary

Indicates that this cmdlet gets a summary of the imported data, instead of getting
individual
counter data samples.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe performance counter log paths to this cmdlet.


Outputs
Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSampleSet,
Microsoft.PowerShell.Commands.GetCounter.CounterSet,
Microsoft.PowerShell.Commands.GetCounter.CounterFileInfo

This cmdlet returns a


Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSampleSet. If
you
use the ListSet parameter, this cmdlet returns a
Microsoft.PowerShell.Commands.GetCounter.CounterSet object. If you use the
Summary
parameter, this cmdlet returns a
Microsoft.PowerShell.Commands.GetCounter.CounterFileInfo
object.

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

Related Links
Export-Counter
Get-Counter
New-WinEvent
Reference
Module: Microsoft.PowerShell.Diagnostics

Creates a new Windows event for the specified event provider.

Syntax
PowerShell

New-WinEvent

[-ProviderName] <String>

[-Id] <Int32>

[-Version <Byte>]

[[-Payload] <Object[]>]

[<CommonParameters>]

Description
The New-WinEvent cmdlet creates an Event Tracing for Windows (ETW) event for an event
provider.
You can use this cmdlet to add events to ETW channels from PowerShell.

Examples

Example 1 - Create a new event


PowerShell

New-WinEvent -ProviderName Microsoft-Windows-PowerShell -Id 45090 -Payload


@("Workflow", "Running")

This command uses the New-WinEvent cmdlet to create event 45090 for the
Microsoft-
Windows-PowerShell provider.

Example 2 - Get the template for an event


In this example, Get-WinEvent is used to get the template for event id 8007 from the
Group Policy
event provider. Notice that the event has two formats.
In version 0, the IsMachine field is a boolean value. In version 1, the IsMachine field is
an unsigned integer value.

PowerShell

(Get-WinEvent -ListProvider Microsoft-Windows-GroupPolicy).Events | Where-


Object Id -eq 8007

Id : 8007

Version : 0

LogLink : System.Diagnostics.Eventing.Reader.EventLogLink

Level : System.Diagnostics.Eventing.Reader.EventLevel

Opcode : System.Diagnostics.Eventing.Reader.EventOpcode

Task : System.Diagnostics.Eventing.Reader.EventTask

Keywords : {}

Template : <template
xmlns="http://schemas.microsoft.com/win/2004/08/events">

<data name="PolicyElaspedTimeInSeconds" inType="win:UInt32"


outType="xs:unsignedInt"/>

<data name="ErrorCode" inType="win:UInt32"


outType="win:HexInt32"/>

<data name="PrincipalSamName" inType="win:UnicodeString"


outType="xs:string"/>

<data name="IsMachine" inType="win:Boolean"


outType="xs:boolean"/>

<data name="IsConnectivityFailure" inType="win:Boolean"


outType="xs:boolean"/>

</template>

Description : Completed periodic policy processing for user %3 in %1


seconds.

Id : 8007

Version : 1

LogLink : System.Diagnostics.Eventing.Reader.EventLogLink

Level : System.Diagnostics.Eventing.Reader.EventLevel

Opcode : System.Diagnostics.Eventing.Reader.EventOpcode

Task : System.Diagnostics.Eventing.Reader.EventTask

Keywords : {}

Template : <template
xmlns="http://schemas.microsoft.com/win/2004/08/events">

<data name="PolicyElaspedTimeInSeconds" inType="win:UInt32"


outType="xs:unsignedInt"/>

<data name="ErrorCode" inType="win:UInt32"


outType="win:HexInt32"/>

<data name="PrincipalSamName" inType="win:UnicodeString"


outType="xs:string"/>

<data name="IsMachine" inType="win:UInt32"


outType="xs:unsignedInt"/>

<data name="IsConnectivityFailure" inType="win:Boolean"


outType="xs:boolean"/>

</template>

Description : Completed periodic policy processing for user %3 in %1


seconds.

The Description property contains the message that gets written to the event log. The
%3 and
%1 value are placeholders for the values passed into the template. The %3 string
is replace with
the value passed to the PrincipalSamName field. The %1 string is
replaced withe value passed
to the PolicyElaspedTimeInSeconds field.

Example 3 - Create a new event using a versioned


template
This example shows how to create an event using a specific template version.

PowerShell

$Payload = @(300, [uint32]'0x8001011f', $env:USERNAME, 0, 1)

New-WinEvent -ProviderName Microsoft-Windows-GroupPolicy -Id 8007 -Version 1


-Payload $Payload

Get-winEvent -ProviderName Microsoft-Windows-GroupPolicy -MaxEvents 1

ProviderName: Microsoft-Windows-GroupPolicy

TimeCreated Id LevelDisplayName Message

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

5/4/2022 8:40:24 AM 8007 Information Completed periodic policy


processing for user User1 in 300 seconds

If the values in the payload do not match the types in the template, the event is logged
but the
payload contains an error.

Parameters
-Id

Specifies an event Id that is registered in the event provider.

Type: Int32

Position: 2

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-Payload

The payload is an array of values passed as positional arguments to the event


template. The values
are inserted into the template to construct the message for the
event. Events can have multiple
template versions that use different formats.

If the values in the payload do not match the types in the template, the event is
logged but the
payload contains an error.

Type: Object[]

Position: 3

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ProviderName

Specifies the event provider that writes the event to an event log, such as
"Microsoft-
Windows-PowerShell". An ETW event provider is a logical entity that writes events to
ETW
sessions.

Type: String

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Version

Specifies the version number of the event. PowerShell converts the number to the
required Byte type.
The value specifies the version of the event when different
versions of the same event are defined.

Type: Byte

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
After the provider writes the event to an eventlog, you can use the Get-WinEvent cmdlet
to get the
event from the event log.

Related Links
Get-WinEvent
Microsoft.PowerShell.Host
Reference

This section contains the help topics for the cmdlets that are installed with the
PowerShell
Microsoft.PowerShell.Host module. The Host module contains cmdlets that
manage data from host
programs.

Microsoft.PowerShell.Host
Start-Transcript Creates a record of all or part of a PowerShell session to a text
file.

Stop-Transcript Stops a transcript.


Start-Transcript
Reference
Module: Microsoft.PowerShell.Host

Creates a record of all or part of a PowerShell session to a text file.

Syntax
PowerShell

Start-Transcript

[[-Path] <String>]

[-Append]

[-Force]

[-NoClobber]

[-IncludeInvocationHeader]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Start-Transcript

[[-LiteralPath] <String>]

[-Append]

[-Force]

[-NoClobber]

[-IncludeInvocationHeader]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Start-Transcript

[[-OutputDirectory] <String>]

[-Append]

[-Force]

[-NoClobber]

[-IncludeInvocationHeader]

[-WhatIf]

[-Confirm]

[<CommonParameters>]
Description
The Start-Transcript cmdlet creates a record of all or part of a PowerShell session to a
text
file. The transcript includes all command that the user types and all output that
appears on the
console.

Starting in Windows PowerShell 5.0, Start-Transcript includes the hostname in the


generated file
name of all transcripts. This is especially useful when your enterprise's
logging is centralized.
Files that are created by the Start-Transcript cmdlet include
random characters in names to
prevent potential overwrites or duplication when two or
more transcripts are started simultaneously.
This also prevents unauthorized discovery
of transcripts that are stored in a centralized file
share.

When using the Append parameter, if the target file doesn't have a Byte Order Mark
(BOM)
Start-Transcript defaults to ASCII encoding in the target file. This behavior can
result in
improper encoding of mulitbyte characters in the transcript.

Examples

Example 1: Start a transcript file with default settings


PowerShell

Start-Transcript

This command starts a transcript in the default file location.

Example 2: Start a transcript file at a specific location


PowerShell

Start-Transcript -Path "C:\transcripts\transcript0.txt" -NoClobber

This command starts a transcript in the Transcript0.txt file in C:\transcripts . Since


the
NoClobber parameter is used, the command prevents any existing files from being
overwritten. If
the Transcript0.txt file already exists, the command fails.

Parameters
-Append

Indicates that this cmdlet adds the new transcript to the end of an existing file. Use
the Path
parameter to specify the file.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

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. The cmdlet
cannot override security
restrictions when this parameter is used.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-IncludeInvocationHeader
Indicates that this cmdlet logs the time stamp when commands are run.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-LiteralPath

Specifies a location to the transcript file. 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 inform PowerShell not to interpret any characters as escape
sequences.

Type: String

Aliases: PSPath

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-NoClobber

Indicates that this cmdlet does not overwrite an existing file. By default, if a transcript
file
exists in the specified path, Start-Transcript overwrites the file without warning.

Type: SwitchParameter

Aliases: NoOverwrite

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-OutputDirectory

Specifies a specific path and folder in which to save a transcript. PowerShell


automatically assigns
the transcript name.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Path

Specifies a location to 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.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs.


The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False


Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
String

This cmdlet returns a string containing 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.

Related Links
Stop-Transcript
Stop-Transcript
Reference
Module: Microsoft.PowerShell.Host

Stops a transcript.

Syntax
PowerShell

Stop-Transcript []

Description
The Stop-Transcript cmdlet stops a transcript that was started by the Start-Transcript
cmdlet.
Alternatively, you can end a session to stop a transcript.

Examples

Example 1: Stop all transcripts


PowerShell

Stop-Transcript

This command stops all transcripts.

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
String
This cmdlet 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.

Related Links
Start-Transcript
Microsoft.PowerShell.LocalAccounts
Reference

This section contains the help topics for the Local Accounts cmdlets in Windows
PowerShell.

7 Note

This module is not available in 32-bit PowerShell on a 64-bit system.

Microsoft.PowerShell.LocalAccounts
Add-LocalGroupMember Adds members to a local group.

Disable-LocalUser Disables a local user account.

Enable-LocalUser Enables a local user account.

Get-LocalGroup Gets the local security groups.

Get-LocalGroupMember Gets members from a local group.

Get-LocalUser Gets local user accounts.

New-LocalGroup Creates a local security group.

New-LocalUser Creates a local user account.

Remove-LocalGroup Deletes local security groups.

Remove-LocalGroupMember Removes members from a local group.

Remove-LocalUser Deletes local user accounts.

Rename-LocalGroup Renames a local security group.

Rename-LocalUser Renames a local user account.

Set-LocalGroup Changes a local security group.

Set-LocalUser Modifies a local user account.


Add-LocalGroupMember
Reference
Module: Microsoft.PowerShell.LocalAccounts

Adds members to a local group.

Syntax
PowerShell

Add-LocalGroupMember

[-Group] <LocalGroup>

[-Member] <LocalPrincipal[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Add-LocalGroupMember

[-Member] <LocalPrincipal[]>

[-Name] <String>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Add-LocalGroupMember

[-Member] <LocalPrincipal[]>

[-SID] <SecurityIdentifier>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Add-LocalGroupMember cmdlet adds users or groups to a local security group. All the
rights and
permissions that are assigned to a group are assigned to all members of that
group.
Members of the Administrators group on a local computer have Full Control
permissions on that
computer. Limit the number of users in the Administrators group.

If the computer is joined to a domain, you can add user accounts, computer accounts,
and group
accounts from that domain and from trusted domains to a local group.

7 Note

If the computer is joined to a domain and you try to add a local user that has the
same name as a
member of the domain it adds the domain member.

Examples

Example 1: Add members to the Administrators group


This command adds several members to the local Administrators group. The new
members include a local
user account, a Microsoft account, an Azure Active Directory
account, and a domain group. This
example uses a placeholder value for the user name
of an account at Outlook.com.

PowerShell

Add-LocalGroupMember -Group "Administrators" -Member "Admin02",


"MicrosoftAccount\username@Outlook.com", "AzureAD\DavidChew@contoso.com",
"CONTOSO\Domain Admins"

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


-Group

Specifies the security group to which this cmdlet adds members.

Type: Microsoft.PowerShell.Commands.LocalGroup

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Member

Specifies an array of users or groups that this cmdlet adds to a security group. You
can specify
users or groups by name, security ID (SID), or LocalPrincipal objects.

Type: Microsoft.PowerShell.Commands.LocalPrincipal[]

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies the name of the security group to which this cmdlet adds members.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SID

Specifies the security ID of the security group to which this cmdlet adds members.
Type: SecurityIdentifier

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
System.Management.Automation.SecurityAccountsManager.LocalGroup

You can pipe a local principal to this cmdlet.

String

You can pipe a string to this cmdlet.

SecurityIdentifier

You can pipe a SID to this cmdlet.

Outputs
None

This cmdlet returns no output.


Notes
The Microsoft.PowerShell.LocalAccounts module is not available in 32-bit PowerShell on
a 64-bit
system.

The PrincipalSource property is a property on LocalUser, LocalGroup, and


LocalPrincipal objects that describes the source of the object. The possible sources are
as
follows:

Local
Active Directory
Azure Active Directory group
Microsoft Account

PrincipalSource is supported only by Windows 10, Windows Server 2016, and later
versions of the
Windows operating system. For earlier versions, the property is blank.

Related Links
Get-LocalGroupMember
New-LocalGroup
Remove-LocalGroupMember
Disable-LocalUser
Reference
Module: Microsoft.PowerShell.LocalAccounts

Disables a local user account.

Syntax
PowerShell

Disable-LocalUser

[-InputObject] <LocalUser[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Disable-LocalUser

[-Name] <String[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Disable-LocalUser

[-SID] <SecurityIdentifier[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Disable-LocalUser cmdlet disables local user accounts. When a user account is
disabled, the
user cannot log on. When a user account is enabled, the user can log on.

7 Note

The Microsoft.PowerShell.LocalAccounts module is not available in 32-bit


PowerShell on a
64-bit system.
Examples

Example 1: Disable an account by specifying a name


PowerShell

Disable-LocalUser -Name "Admin02"

This command disables the user account named Admin02.

Example 2: Disable an account by using the pipeline


PowerShell

Get-LocalUser Guest | Disable-LocalUser

This command gets the built-in Guest account by using Get-LocalUser , and then passes
it to the
current cmdlet by using the pipeline operator( | ). That cmdlet disables that
account.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies an array of user accounts that this cmdlet disables. To obtain a user
account, use the
Get-LocalUser cmdlet.
Type: Microsoft.PowerShell.Commands.LocalUser[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies an array of names of the user accounts that this cmdlet disables.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-SID

Specifies an array of user accounts that this cmdlet disables.

Type: SecurityIdentifier[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False


Accept pipeline input: False

Accept wildcard characters: False

Inputs
System.Management.Automation.SecurityAccountsManager.LocalUser

You can pipe a local user this cmdlet.

String

You can pipe a string to this cmdlet.

SecurityIdentifier

You can pipe a SID to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
The PrincipalSource property is a property on LocalUser, LocalGroup, and
LocalPrincipal objects that describes the source of the object. The possible sources
are as
follows:

Local

Active Directory

Azure Active Directory group

Microsoft Account

PrincipalSource is supported only by Windows 10, Windows Server 2016, and later
versions of the
Windows operating system. For earlier versions, the property is blank.

Related Links
Enable-LocalUser
Get-LocalUser
New-LocalUser
Remove-LocalUser
Rename-LocalUser
Set-LocalUser
Enable-LocalUser
Reference
Module: Microsoft.PowerShell.LocalAccounts

Enables a local user account.

Syntax
PowerShell

Enable-LocalUser

[-InputObject] <LocalUser[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Enable-LocalUser

[-Name] <String[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Enable-LocalUser

[-SID] <SecurityIdentifier[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Enable-LocalUser cmdlet enables local user accounts.
When a user account is
disabled, the user cannot log on.
When a user account is enabled, the user can log on.

7 Note

The Microsoft.PowerShell.LocalAccounts module is not available in 32-bit


PowerShell on a 64-bit
system.
Examples

Example 1: Enable an account by specifying a name


PowerShell

Enable-LocalUser -Name "Admin02"

This command enables the user account named Admin02.

Example 2: Enable an account by using the pipeline


PowerShell

Get-LocalUser -Name "Administrator" | Enable-LocalUser

This command gets the built-in Administrator account by using Get-LocalUser , and then
passes it to
the current cmdlet by using the pipeline operator. That cmdlet enables that
account.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies an array of user accounts that this cmdlet enables. To obtain a user account,
use the
Get-LocalUser cmdlet.
Type: Microsoft.PowerShell.Commands.LocalUser[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies an array of names of the user accounts that this cmdlet enables.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-SID

Specifies an array of user accounts that this cmdlet enables.

Type: SecurityIdentifier[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False


Accept pipeline input: False

Accept wildcard characters: False

Inputs
System.Management.Automation.SecurityAccountsManager.LocalUser

You can pipe a local user to this cmdlet.

String

You can pipe a string to this cmdlet.

SecurityIdentifier

You can pipe a SID to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
The PrincipalSource property is a property on LocalUser, LocalGroup, and
LocalPrincipal objects that describes the source of the object. The possible sources
are as
follows:

Local

Active Directory

Azure Active Directory group

Microsoft Account

PrincipalSource is supported only by Windows 10, Windows Server 2016, and later
versions of the
Windows operating system. For earlier versions, the property is blank.

Related Links
Disable-LocalUser
Get-LocalUser
New-LocalUser
Remove-LocalUser
Rename-LocalUser
Set-LocalUser
Get-LocalGroup
Reference
Module: Microsoft.PowerShell.LocalAccounts

Gets the local security groups.

Syntax
PowerShell

Get-LocalGroup

[[-Name] <String[]>]

[<CommonParameters>]

PowerShell

Get-LocalGroup

[[-SID] <SecurityIdentifier[]>]

[<CommonParameters>]

Description
The Get-LocalGroup cmdlet gets local security groups in Security Account Manager.
This
cmdlet gets default built-in groups and local security groups that you create.

7 Note

The Microsoft.PowerShell.LocalAccounts module is not available in 32-bit


PowerShell on a 64-bit
system.

Examples

Example 1: Get the Administrators group


PowerShell

Get-LocalGroup -Name "Administrators"


This command gets the local Administrators group. The command displays properties of
the group in
the console.

Parameters
-Name

Specifies an array of names of security groups that this cmdlet gets. You can use the
wildcard
character.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-SID

Specifies an array of security IDs (SIDs) of security groups that this cmdlet gets.

Type: SecurityIdentifier[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

Inputs
String

You can pipe a string to this cmdlet.

SecurityIdentifier

You can pipe a SID to this cmdlet.

Outputs
System.Management.Automation.SecurityAccountsManager.LocalGroup

This cmdlet returns a local group.

Notes
The PrincipalSource property is a property on LocalUser, LocalGroup, and
LocalPrincipal objects that describes the source of the object. The possible sources
are as
follows:

Local

Active Directory

Azure Active Directory group

Microsoft Account

PrincipalSource is supported only by Windows 10, Windows Server 2016, and later
versions of the
Windows operating system. For earlier versions, the property is blank.

Related Links
New-LocalGroup
Remove-LocalGroup
Rename-LocalGroup
Set-LocalGroup
Get-LocalGroupMember
Reference
Module: Microsoft.PowerShell.LocalAccounts

Gets members from a local group.

Syntax
PowerShell

Get-LocalGroupMember

[[-Member] <String>]

[-Name] <String>

[<CommonParameters>]

PowerShell

Get-LocalGroupMember

[-Group] <LocalGroup>

[[-Member] <String>]

[<CommonParameters>]

PowerShell

Get-LocalGroupMember

[[-Member] <String>]

[-SID] <SecurityIdentifier>

[<CommonParameters>]

Description
The Get-LocalGroupMember cmdlet gets members from a local group.

7 Note

The Microsoft.PowerShell.LocalAccounts module is not available in 32-bit


PowerShell on a 64-bit
system.

Examples
Example 1: Get all members of the Administrators group
PowerShell

Get-LocalGroupMember -Group "Administrators"

This command gets all the members of the local Administrators group.

Parameters
-Group

Specifies the security group from which this cmdlet gets members.

Type: Microsoft.PowerShell.Commands.LocalGroup

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Member

Specifies a user or group that this cmdlet gets from a security group. You can specify
users or
groups by name or security ID (SID). Specify SID strings in S-R-I-S-S . . .
format. You can use
wildcard characters. If you do not specify this parameter, the
cmdlet gets all members of the group.

Type: String

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Name

Specifies the name of the security group from which this cmdlet gets members.
Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-SID

Specifies the security ID of the security group from which this cmdlet gets members.

Type: SecurityIdentifier

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

Inputs
System.Management.Automation.SecurityAccountsManager.LocalGroup

You can pipe a local group to this cmdlet.

String

You can pipe a string to this cmdlet.

SecurityIdentifier

You can pipe a SID to this cmdlet.

Outputs
Microsoft.SecurityAccountsManager.LocalPrincipal

This cmdlet returns local principals.

Notes
The PrincipalSource property is a property on LocalUser, LocalGroup, and
LocalPrincipal objects that describes the source of the object. The possible sources
are as
follows:

Local

Active Directory

Azure Active Directory group

Microsoft Account

PrincipalSource is supported only by Windows 10, Windows Server 2016, and later
versions of the
Windows operating system. For earlier versions, the property is blank.

Related Links
Add-LocalGroupMember
New-LocalGroup
Remove-LocalGroupMember
Get-LocalUser
Reference
Module: Microsoft.PowerShell.LocalAccounts

Gets local user accounts.

Syntax
PowerShell

Get-LocalUser

[[-Name] <String[]>]

[<CommonParameters>]

PowerShell

Get-LocalUser

[[-SID] <SecurityIdentifier[]>]

[<CommonParameters>]

Description
The Get-LocalUser cmdlet gets local user accounts. This cmdlet gets default built-in
user
accounts, local user accounts that you created, and local accounts that you
connected to Microsoft
accounts.

7 Note

The Microsoft.PowerShell.LocalAccounts module is not available in 32-bit


PowerShell on a 64-bit
system.

Examples

Example 1: Get an account by using its name


This example gets a user account named AdminContoso02.

PowerShell
Get-LocalUser -Name "AdminContoso02"

Name Enabled Description

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

AdminContoso02 True Description of this account.

Example 2: Get an account that is connected to a


Microsoft account
This example gets a user account that is connected to a Microsoft account. This example
uses a
placeholder value for the username of an account at Outlook.com.

PowerShell

Get-LocalUser -Name "MicrosoftAccount\username@Outlook.com"

Name Enabled Description

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

MicrosoftAccount\username@outlook.com True Description of this account.

Example 3: Get an account that has the specified SID


This example gets a local user account that has the specified SID.

PowerShell

Get-LocalUser -SID S-1-5-21-9526073513-1762370368-3942940353-500

Name Enabled Description


---- ------- -----------
Administrator True Built-in account for administering the computer/domain

Parameters
-Name

Specifies an array of names of user accounts that this cmdlet gets. You can use the
wildcard
character.

Type: String[]

Position: 0

Default value: None


Accept pipeline input: True

Accept wildcard characters: True

-SID

Specifies an array of security IDs (SIDs) of user accounts that this cmdlet gets.

Type: SecurityIdentifier[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

Inputs
String

You can pipe a string to this cmdlet.

SecurityIdentifier

You can pipe a SID to this cmdlet.

Outputs
System.Management.Automation.SecurityAccountsManager.LocalUser[]

This cmdlet returns local user accounts.

Notes
The PrincipalSource property on LocalUser, LocalGroup, and LocalPrincipal objects
describes the source of the object. The possible sources are as follows:

Local
Active Directory
Azure Active Directory group
Microsoft Account
PrincipalSource is supported only by Windows 10, Windows Server 2016, and later
versions of the
Windows operating system. For earlier versions, the property is blank.

Related Links
Disable-LocalUser
Enable-LocalUser
New-LocalUser
Remove-LocalUser
Rename-LocalUser
Set-LocalUser
New-LocalGroup
Reference
Module: Microsoft.PowerShell.LocalAccounts

Creates a local security group.

Syntax
PowerShell

New-LocalGroup

[-Description <String>]

[-Name] <String>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The New-LocalGroup cmdlet creates a local security group in the Security Account
Manager.

7 Note

The Microsoft.PowerShell.LocalAccounts module is not available in 32-bit


PowerShell on a 64-bit
system.

Examples

Example 1: Create a security group


PowerShell

New-LocalGroup -Name "SecurityGroup04"

This command creates a group named SecurityGroup04.


Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Description

Specifies a comment for the group. The maximum length is 48 characters.

Type: String

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies a name for the group. The maximum length is 256 characters.

Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a string to this cmdlet.

Outputs
System.Management.Automation.SecurityAccountsManager.LocalGroup

This cmdlet returns a LocalGroup object representing the created security group.

Notes
` The PrincipalSource property is a property on LocalUser, LocalGroup, and
LocalPrincipal objects that describes the source of the object. The possible sources are
as
follows:

Local
Active Directory
Azure Active Directory group
Microsoft Account

PrincipalSource is supported only by Windows 10, Windows Server 2016, and later
versions of the
Windows operating system. For earlier versions, the property is blank.

Related Links
Get-LocalGroup
Remove-LocalGroup
Rename-LocalGroup
Set-LocalGroup
New-LocalUser
Reference
Module: Microsoft.PowerShell.LocalAccounts

Creates a local user account.

Syntax
PowerShell

New-LocalUser

[-AccountExpires <DateTime>]

[-AccountNeverExpires]

[-Description <String>]

[-Disabled]

[-FullName <String>]

[-Name] <String>

-Password <SecureString>

[-PasswordNeverExpires]

[-UserMayNotChangePassword]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

New-LocalUser

[-AccountExpires <DateTime>]

[-AccountNeverExpires]

[-Description <String>]

[-Disabled]

[-FullName <String>]

[-Name] <String>

[-NoPassword]

[-UserMayNotChangePassword]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The New-LocalUser cmdlet creates a local user account. This cmdlet creates a local user
account.
7 Note

The Microsoft.PowerShell.LocalAccounts module isn't available in 32-bit PowerShell


on a 64-bit
system.

Examples

Example 1: Create a user account


PowerShell

New-LocalUser -Name 'User02' -Description 'Description of this account.' -


NoPassword

Name Enabled Description

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

User02 True Description of this account.

This command creates a local user account and doesn't specify the AccountExpires or
Password parameters. The account doesn't expire or have a password.

Example 2: Create a user account that has a password


PowerShell

$Password = Read-Host -AsSecureString

$params = @{

Name = 'User03'

Password = $Password

FullName = 'Third User'

Description = 'Description of this account.'

New-LocalUser @params

Name Enabled Description

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

User03 True Description of this account.

The first command uses the Read-Host cmdlet to prompts you for a password. The
command stores the
password as a secure string in the $Password variable.

The second command creates a local user account and sets the new account's password
to the secure
string stored in $Password . The command specifies a user name, full name,
and description for the
user account.

Parameters
-AccountExpires

Specifies when the user account expires. You can use the Get-Date cmdlet to get a
DateTime
object. If you don't specify this parameter, the account doesn't expire.

Type: DateTime

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-AccountNeverExpires

Indicates that the account doesn't expire.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


-Description

Specifies a comment for the user account. The maximum length is 48 characters.

Type: String

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Disabled

Indicates that this cmdlet creates the user account as disabled.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-FullName

Specifies the full name for the user account. The full name differs from the user name
of the user
account.

Type: String

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies the user name for the user account.


A user name can contain up to 20 uppercase characters or lowercase characters. A
user name can't
contain the following characters:

", /, \, [, ], :, ;, |, =, ,, +, *, ?, <, >, @

A user name can't consist only of periods . or spaces.

Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-NoPassword

Indicates that the user account doesn't have a password.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Password

Specifies a password for the user account. You can use Read-Host -AsSecureString ,
Get-Credential , or ConvertTo-SecureString to create a SecureString object for the

password.

If you omit the Password and NoPassword parameters, New-LocalUser prompts you
for the new
user's password.

Type: SecureString

Position: Named

Default value: None

Accept pipeline input: True


Accept wildcard characters: False

-PasswordNeverExpires

Indicates whether the new user's password expires.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-UserMayNotChangePassword

Indicates that the user can't change the password on the user account.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet isn't run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a string to this cmdlet.

DateTime

You can pipe a DateTime object to this cmdlet.

Boolean

You can pipe a boolean value to this cmdlet.

SecureString

You can pipe a secure string to this cmdlet.

Outputs
System.Management.Automation.SecurityAccountsManager.LocalUser

This cmdlet returns a LocalUser object representing the created user account.

Notes
A user name can't be identical to any other user name or group name on the
computer. A user name
can't consist only of periods . or spaces. A user name can
contain up to 20 uppercase
characters or lowercase characters. A user name can't
contain the following characters:

", /, \, [, ], :, ;, |, =, ,, +, *, ?, <, >, @

A password can contain up to 127 characters.

The PrincipalSource property is a property on LocalUser, LocalGroup, and


LocalPrincipal objects that describes the source of the object. The possible sources
are as
follows:
Local

Active Directory
Azure Active Directory group

Microsoft Account

7 Note
PrincipalSource is supported only by Windows 10, Windows Server 2016, and later
versions of
the Windows operating system. For earlier versions, the property is
blank.

Related Links
Disable-LocalUser
Enable-LocalUser
Get-LocalUser
Remove-LocalUser
Rename-LocalUser
Set-LocalUser
Remove-LocalGroup
Reference
Module: Microsoft.PowerShell.LocalAccounts

Deletes local security groups.

Syntax
PowerShell

Remove-LocalGroup

[-InputObject] <LocalGroup[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-LocalGroup

[-Name] <String[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-LocalGroup

[-SID] <SecurityIdentifier[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Remove-LocalGroup cmdlet deletes local security groups. This cmdlet deletes only a
local
group. It does not delete the user accounts, computer accounts, or group accounts
that belong to
that group. You cannot recover a deleted group.

If you delete a group and then create another group that has the same group name, you
must set new
permissions for the new group. The new group does not inherit the
permissions that were assigned to
the group.
7 Note

The Microsoft.PowerShell.LocalAccounts module is not available in 32-bit


PowerShell on a 64-bit
system.

Examples

Example 1: Delete a security group


PowerShell

Remove-LocalGroup -Name "SecurityGroup04"

This command deletes the group named SecurityGroup04.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies an array of security groups that this cmdlet deletes. To obtain groups, use
the
Get-LocalGroup cmdlet.

Type: Microsoft.PowerShell.Commands.LocalGroup[]

Position: 0

Default value: None


Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies an array of names of the security groups that this cmdlet deletes.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-SID

Specifies an array of security IDs (SIDs) of security groups that this cmdlet deletes.

Type: SecurityIdentifier[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


Inputs
System.Management.Automation.SecurityAccountsManager.LocalGroup

You can pipe a security group to this cmdlet.

String

You can pipe a string to this cmdlet.

SecurityIdentifier

You can pipe a SID to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
This cmdlet cannot delete the following default groups:

Administrators

Backup Operators

Cryptographic Operators

Distributed COM Users

Event Log Readers

Guests

Hyper-V Administrators

IIS_IUSRS

Network Configuration Operators

Performance Log Users

Performance Monitor Users


Power Users

Remote Desktop Users

Remote Management Users

Replicator

Users

WinRMRemoteWMIUsers__

The PrincipalSource property is a property on LocalUser, LocalGroup, and


LocalPrincipal objects that describes the source of the object. The possible sources
are as
follows:

Local

Active Directory

Azure Active Directory group

Microsoft Account

PrincipalSource is supported only by Windows 10, Windows Server 2016, and later
versions of the
Windows operating system. For earlier versions, the property is blank.

Related Links
Get-LocalGroup
New-LocalGroup
Rename-LocalGroup
Set-LocalGroup
Remove-LocalGroupMember
Reference
Module: Microsoft.PowerShell.LocalAccounts

Removes members from a local group.

Syntax
PowerShell

Remove-LocalGroupMember

[-Group] <LocalGroup>

[-Member] <LocalPrincipal[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-LocalGroupMember

[-Member] <LocalPrincipal[]>

[-Name] <String>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-LocalGroupMember

[-Member] <LocalPrincipal[]>

[-SID] <SecurityIdentifier>
[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Remove-LocalGroupMember cmdlet removes users or groups from a local group.

7 Note
The Microsoft.PowerShell.LocalAccounts module is not available in 32-bit
PowerShell on a 64-bit
system.

Examples

Example 1: Remove members from the Administrators


group
PowerShell

$members = "Admin02", "MicrosoftAccount\username@Outlook.com",


"AzureAD\DavidChew@contoso.com", "CONTOSO\Domain Admins"

Remove-LocalGroupMember -Group "Administrators" -Member $members

This command removes several members from the local Administrators group. The
members that this
cmdlet removes include a local user account, a Microsoft account, an
Azure Active Directory account,
and a domain group. This example uses a placeholder
value for the user name of an account at
Outlook.com.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Group

Specifies the security group from which this cmdlet removes members.

Type: Microsoft.PowerShell.Commands.LocalGroup
Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Member

Specifies an array of users or groups that this cmdlet removes from a security group.
You can
specify users or groups by name, security ID (SID), or LocalPrincipal objects.
Specify SID
strings in S-R-I-S-S . . . format.

Type: Microsoft.PowerShell.Commands.LocalPrincipal[]

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies the name of the security group from which this cmdlet removes members.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SID

Specifies the security ID of the security group from which this cmdlet removes
members.

Type: SecurityIdentifier

Position: 0

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs.


The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
System.Management.Automation.SecurityAccountsManager.LocalPrincipal

You can pipe a local principal to this cmdlet.

String

You can pipe a string to this cmdlet.

SecurityIdentifier

You can pipe a SID to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
The PrincipalSource property is a property on LocalUser, LocalGroup, and
LocalPrincipal objects that describes the source of the object. The possible sources
are as
follows:
Local

Active Directory

Azure Active Directory group

Microsoft Account

PrincipalSource is supported only by Windows 10, Windows Server 2016, and later
versions of the
Windows operating system. For earlier versions, the property is blank.

Related Links
Add-LocalGroupMember
Get-LocalGroupMember
New-LocalGroup
Remove-LocalUser
Reference
Module: Microsoft.PowerShell.LocalAccounts

Deletes local user accounts.

Syntax
PowerShell

Remove-LocalUser

[-InputObject] <LocalUser[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-LocalUser

[-Name] <String[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-LocalUser

[-SID] <SecurityIdentifier[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Remove-LocalUser cmdlet deletes local user accounts.

Examples

Example 1: Delete a user account


PowerShell

Remove-LocalUser -Name "AdminContoso02"

This command deletes the user account named AdminContoso02.

7 Note

The Microsoft.PowerShell.LocalAccounts module is not available in 32-bit


PowerShell on a 64-bit
system.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies an array of user accounts that this cmdlet deletes. To obtain a user account,
use the
Get-LocalUser cmdlet.

Type: Microsoft.PowerShell.Commands.LocalUser[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name
Specifies an array of names of the user accounts that this cmdlet deletes.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-SID

Specifies an array of security IDs (SIDs) of user accounts that this cmdlet deletes.

Type: SecurityIdentifier[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
System.Management.Automation.SecurityAccountsManager.LocalUser

You can pipe a local user to this cmdlet.


String

You can pipe a string to this cmdlet.

SecurityIdentifier

You can pipe a SID to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
The PrincipalSource property is a property on LocalUser, LocalGroup, and
LocalPrincipal objects that describes the source of the object. The possible sources
are as
follows:

Local

Active Directory

Azure Active Directory group

Microsoft Account

PrincipalSource is supported only by Windows 10, Windows Server 2016, and later
versions of the
Windows operating system. For earlier versions, the property is blank.

Related Links
Disable-LocalUser
Enable-LocalUser
Get-LocalUser
New-LocalUser
Rename-LocalUser
Set-LocalUser
Rename-LocalGroup
Reference
Module: Microsoft.PowerShell.LocalAccounts

Renames a local security group.

Syntax
PowerShell

Rename-LocalGroup

[-InputObject] <LocalGroup>
[-NewName] <String>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Rename-LocalGroup

[-Name] <String>

[-NewName] <String>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Rename-LocalGroup

[-NewName] <String>

[-SID] <SecurityIdentifier>
[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Rename-LocalGroup cmdlet renames a local security group.

7 Note
The Microsoft.PowerShell.LocalAccounts module is not available in 32-bit
PowerShell on a 64-bit
system.

Examples

Example 1: Change the name of a group


PowerShell

PS C:\> Rename-LocalGroup -Name "SecurityGroup" -NewName "SecurityGroup04"

This command renames a security group named SecurityGroup.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies the security group that this cmdlet renames.


To obtain a security group, use
the Get-LocalGroup cmdlet.

Type: Microsoft.PowerShell.Commands.LocalGroup

Position: 0

Default value: None

Accept pipeline input: True


Accept wildcard characters: False

-Name

Specifies the name of the security group that this cmdlet renames.

Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-NewName

Specifies a new name for the security group.

Type: String

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SID

Specifies the security ID (SID) of a security group that this cmdlet renames.

Type: SecurityIdentifier

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs.


The cmdlet is not run.
Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
System.Management.Automation.SecurityAccountsManager.LocalGroup

You can pipe a security group to this cmdlet.

String

You can pipe a string to this cmdlet.

SecurityIdentifier

You can pipe a SID to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
The PrincipalSource property is a property on LocalUser, LocalGroup, and
LocalPrincipal objects that describes the source of the object. The possible sources
are as
follows:

Local

Active Directory

Azure Active Directory group

Microsoft Account
PrincipalSource is supported only by Windows 10, Windows Server 2016, and later
versions of the
Windows operating system. For earlier versions, the property is blank.

Related Links
Get-LocalGroup
New-LocalGroup
Remove-LocalGroup
Set-LocalGroup
Rename-LocalUser
Reference
Module: Microsoft.PowerShell.LocalAccounts

Renames a local user account.

Syntax
PowerShell

Rename-LocalUser

[-InputObject] <LocalUser>

[-NewName] <String>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Rename-LocalUser

[-Name] <String>

[-NewName] <String>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Rename-LocalUser

[-NewName] <String>

[-SID] <SecurityIdentifier>
[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Rename-LocalUser cmdlet renames a local user account.

7 Note
The Microsoft.PowerShell.LocalAccounts module is not available in 32-bit
PowerShell on a 64-bit
system.

Examples

Example 1: Rename a user account


PowerShell

Rename-LocalUser -Name "Admin02" -NewName "AdminContoso02"

This command renames the user account named Admin02.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies the user account that this cmdlet renames. To obtain a user account, use
the Get-LocalUser
cmdlet.

Type: Microsoft.PowerShell.Commands.LocalUser

Position: 0

Default value: None

Accept pipeline input: True


Accept wildcard characters: False

-Name

Specifies the name of the user account that this cmdlet renames.

Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-NewName

Specifies a new name for the user account.

Type: String

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SID

Specifies the security ID (SID) of a user accounts that this cmdlet renames.

Type: SecurityIdentifier

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
System.Management.Automation.SecurityAccountsManager.LocalUser

You can pipe a local user to this cmdlet.

String

You can pipe a string to this cmdlet.

SecurityIdentifier

You can pipe a SID to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
The PrincipalSource property is a property on LocalUser, LocalGroup, and
LocalPrincipal objects that describes the source of the object. The possible sources
are as
follows:

Local

Active Directory

Azure Active Directory group

Microsoft Account
PrincipalSource is supported only by Windows 10, Windows Server 2016, and later
versions of the
Windows operating system. For earlier versions, the property is blank.

Related Links
Disable-LocalUser
Enable-LocalUser
Get-LocalUser
New-LocalUser
Remove-LocalUser
Set-LocalUser
Set-LocalGroup
Reference
Module: Microsoft.PowerShell.LocalAccounts

Changes a local security group.

Syntax
PowerShell

Set-LocalGroup

-Description <String>

[-InputObject] <LocalGroup>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Set-LocalGroup

-Description <String>

[-Name] <String>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Set-LocalGroup

-Description <String>

[-SID] <SecurityIdentifier>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Set-LocalGroup cmdlet changes a local security group.

Examples
Example 1: Change a group description
PowerShell

Set-LocalGroup -Name "SecurityGroup04" -Description "This is a sample


description."

This command changes the description of a local group.

7 Note

The Microsoft.PowerShell.LocalAccounts module is not available in 32-bit


PowerShell on a 64-bit
system.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Description

Specifies a comment for the group. The maximum length is 48 characters.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-InputObject

Specifies the security group that this cmdlet changes. To obtain a security group, use
the
Get-LocalGroup cmdlet.

Type: Microsoft.PowerShell.Commands.LocalGroup

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies the name of the security group that this cmdlet changes.

Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-SID

Specifies the security ID (SID) of the security group that this cmdlet changes.

Type: SecurityIdentifier

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter
Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
System.Management.Automation.SecurityAccountsManager.LocalGroup

You can pipe a security group to this cmdlet.

String

You can pipe a string to this cmdlet.

SecurityIdentifier

You can pipe a SID to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
The PrincipalSource property is a property on LocalUser, LocalGroup, and
LocalPrincipal objects that describes the source of the object. The possible sources
are as
follows:

Local

Active Directory

Azure Active Directory group

Microsoft Account
PrincipalSource is supported only by Windows 10, Windows Server 2016, and later
versions of the
Windows operating system. For earlier versions, the property is blank.

Related Links
Get-LocalGroup
New-LocalGroup
Remove-LocalGroup
Rename-LocalGroup
Set-LocalUser
Reference
Module: Microsoft.PowerShell.LocalAccounts

Modifies a local user account.

Syntax
PowerShell

Set-LocalUser

[-AccountExpires <DateTime>]

[-AccountNeverExpires]

[-Description <String>]

[-FullName <String>]

[-Name] <String>

[-Password <SecureString>]

[-PasswordNeverExpires <Boolean>]

[-UserMayChangePassword <Boolean>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Set-LocalUser

[-AccountExpires <DateTime>]

[-AccountNeverExpires]

[-Description <String>]

[-FullName <String>]

[-InputObject] <LocalUser>

[-Password <SecureString>]

[-PasswordNeverExpires <Boolean>]

[-UserMayChangePassword <Boolean>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Set-LocalUser

[-AccountExpires <DateTime>]

[-AccountNeverExpires]

[-Description <String>]

[-FullName <String>]

[-Password <SecureString>]

[-PasswordNeverExpires <Boolean>]

[-SID] <SecurityIdentifier>

[-UserMayChangePassword <Boolean>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Set-LocalUser cmdlet modifies a local user account. This cmdlet can reset the
password of a
local user account.

7 Note

The Microsoft.PowerShell.LocalAccounts module is not available in 32-bit


PowerShell on a 64-bit
system.

Examples

Example 1: Change a description of a user account


PowerShell

Set-LocalUser -Name "Admin07" -Description "Description of this account."

This command changes the description of a user account named Admin07.

Example 2: Change the password on an account


PowerShell

$Password = Read-Host -AsSecureString

$UserAccount = Get-LocalUser -Name "User02"

$UserAccount | Set-LocalUser -Password $Password

The first command prompts you for a password by using the Read-Host cmdlet. The
command stores the
password as a secure string in the $Password variable.

The second command gets a user account named User02 by using Get-LocalUser . The
command stores the
account in the $UserAccount variable.
The third command sets the new password on the user account stored in $UserAccount .

Parameters
-AccountExpires

Specifies when the user account expires. To obtain a DateTime object, use the Get-
Date cmdlet.

If you do not want the account to expire, specify the AccountNeverExpires


parameter.

Type: DateTime

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-AccountNeverExpires

Indicates that the account does not expire.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False


Accept pipeline input: False

Accept wildcard characters: False

-Description

Specifies a comment for the user account. The maximum length is 48 characters.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-FullName

Specifies the full name for the user account. The full name differs from the user name
of the user
account.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies the user account that this cmdlet changes. To obtain a user account, use
the
Get-LocalUser cmdlet.

Type: Microsoft.PowerShell.Commands.LocalUser

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False


-Name

Specifies the name of the user account that this cmdlet changes.

Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Password

Specifies a password for the user account. If the user account is connected to a
Microsoft account,
do not set a password.

You can use Read-Host -AsSecureString , Get-Credential , or ConvertTo-SecureString


to create a
SecureString object for the password.

If you omit the Password and NoPassword parameters, Set-LocalUser prompts you
for the
user's password.

Type: SecureString

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-PasswordNeverExpires

Indicates whether the password expires.

Type: Boolean

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-SID

Specifies the security ID (SID) of the user account that this cmdlet changes.

Type: SecurityIdentifier

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-UserMayChangePassword

Indicates that the user can change the password on the user account.

Type: Boolean

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
System.Management.Automation.SecurityAccountsManager.LocalUser
You can pipe a local user to this cmdlet.

String

You can pipe a string to this cmdlet.

SecurityIdentifier

You can pipe a SID to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
The PrincipalSource property is a property on LocalUser, LocalGroup, and
LocalPrincipal objects that describes the source of the object. The possible sources
are as
follows:

Local

Active Directory

Azure Active Directory group

Microsoft Account

PrincipalSource is supported only by Windows 10, Windows Server 2016, and later
versions of the
Windows operating system. For earlier versions, the property is blank.

Related Links
Disable-LocalUser
Enable-LocalUser
Get-LocalUser
New-LocalUser
Remove-LocalUser
Rename-LocalUser
Microsoft.PowerShell.Management
Reference

This section contains the help topics for the cmdlets that are installed with PowerShell
Microsoft.PowerShell.Management module. The Management module contains cmdlets
that help you manage
Windows in PowerShell.

Microsoft.PowerShell.Management
Add-Computer Add the local computer to a domain or workgroup.

Add-Content Adds content to the specified items, such as adding words to a


file.

Checkpoint-Computer Creates a system restore point on the local computer.

Clear-Content Deletes the contents of an item, but does not delete the item.

Clear-EventLog Clears all entries from specified event logs on the local or remote
computers.

Clear-Item Clears the contents of an item, but does not delete the item.

Clear-ItemProperty Clears the value of a property but does not delete the property.

Clear-RecycleBin Clears the contents of a recycle bin.

Complete-Transaction Commits the active transaction.

Convert-Path Converts a path from a PowerShell path to a PowerShell provider


path.

Copy-Item Copies an item from one location to another.

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.

Enable-ComputerRestore Enables the System Restore feature on the specified file system
drive.

Get-ChildItem Gets the items and child items in one or more specified
locations.

Get-Clipboard Gets the current Windows clipboard entry.


Get-ComputerInfo Gets a consolidated object of system and operating system
properties.

Get-ComputerRestorePoint Gets the restore points on the local computer.

Get-Content Gets the content of the item at the specified location.

Get-ControlPanelItem Gets control panel items.

Get-EventLog Gets the events in an event log, or a list of the event logs, on the
local computer or remote
computers.

Get-HotFix Gets the hotfixes that are installed on local or remote computers.

Get-Item Gets the item at the specified location.

Get-ItemProperty Gets the properties of a specified item.

Get-ItemPropertyValue Gets the value for one or more properties of a specified item.

Get-Location Gets information about the current working location or a


location stack.

Get-Process Gets the processes that are running on the local computer or a
remote computer.

Get-PSDrive Gets drives in the current session.

Get-PSProvider Gets information about the specified PowerShell provider.

Get-Service Gets the services on a local or remote computer.

Get-TimeZone Gets the current time zone or a list of available time zones.

Get-Transaction Gets the current (active) transaction.

Get-WmiObject Gets instances of Windows Management Instrumentation (WMI)


classes or information about the
available classes.

Invoke-Item Performs the default action on the specified item.

Invoke-WmiMethod Calls WMI methods.

Join-Path Combines a path and a 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.

Move-Item Moves an item from one location to another.

Move-ItemProperty Moves a property from one location to another.

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.

New-PSDrive Creates temporary and persistent drives that are associated with
a location in an item data store.

New-Service Creates a new Windows service.

New-WebServiceProxy Creates a Web service proxy object that lets you use and manage
the Web service in PowerShell.

Pop-Location Changes the current location to the location most recently


pushed onto the stack.

Push-Location Adds the current location to the top of a location stack.

Register-WmiEvent Subscribes to a Windows Management Instrumentation (WMI)


event.

Remove-Computer Removes the local computer from its domain.

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-PSDrive Deletes temporary PowerShell drives and disconnects mapped


network drives.

Remove-WmiObject Deletes an instance of an existing Windows Management


Instrumentation (WMI) class.

Rename-Computer Renames a computer.

Rename-Item Renames an item in a PowerShell provider namespace.

Rename-ItemProperty Renames a property of an item.

Reset- Resets the machine account password for the computer.


ComputerMachinePassword

Resolve-Path Resolves the wildcard characters in a path, and displays the path
contents.

Restart-Computer Restarts 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.

Set-Clipboard Sets the current Windows clipboard entry.

Set-Content Writes new content or replaces existing content in a file.

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-Service Starts, stops, and suspends a service, and changes its properties.

Set-TimeZone Sets the system time zone to a specified time zone.

Set-WmiInstance Creates or updates an instance of an existing Windows


Management Instrumentation (WMI) class.

Show-ControlPanelItem Opens control panel items.

Show-EventLog Displays the event logs of the local or a remote computer in


Event Viewer.

Split-Path Returns the specified part of a path.

Start-Process Starts one or more processes on the local computer.

Start-Service Starts one or more stopped services.

Start-Transaction Starts a transaction.

Stop-Computer Stops (shuts down) local and remote computers.

Stop-Process Stops one or more running processes.

Stop-Service Stops one or more running services.

Suspend-Service Suspends (pauses) one or more running services.

Test-ComputerSecureChannel Tests and repairs the secure channel between the local computer
and its domain.

Test-Connection Sends ICMP echo request packets, or pings, to one or more


computers.

Test-Path Determines whether all elements of a path exist.

Undo-Transaction Rolls back the active transaction.

Use-Transaction Adds the script block to the active transaction.

Wait-Process Waits for the processes to be stopped before accepting more


input.

Write-EventLog Writes an event to an event log.


Add-Computer
Reference
Module: Microsoft.PowerShell.Management

Add the local computer to a domain or workgroup.

Syntax
PowerShell

Add-Computer

[-ComputerName <String[]>]

[-LocalCredential <PSCredential>]

[-UnjoinDomainCredential <PSCredential>]

-Credential <PSCredential>

[-DomainName] <String>

[-OUPath <String>]

[-Server <String>]

[-Unsecure]

[-Options <JoinOptions>]

[-Restart]

[-PassThru]

[-NewName <String>]

[-Force]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Add-Computer

[-ComputerName <String[]>]

[-LocalCredential <PSCredential>]

[-Credential <PSCredential>]

[-WorkgroupName] <String>

[-Restart]

[-PassThru]

[-NewName <String>]

[-Force]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Add-Computer cmdlet adds the local computer or remote computers to a domain or
workgroup, or
moves them 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.

Examples

Example 1: Add a local computer to a domain then restart


the computer
PowerShell

Add-Computer -DomainName Domain01 -Restart

This command adds the local computer to the Domain01 domain and then restarts the
computer to make
the change effective.

Example 2: Add a local computer to a workgroup


PowerShell

Add-Computer -WorkgroupName WORKGROUP-A

This command adds the local computer to the Workgroup-A workgroup.

Example 3: Add a local computer to a domain


PowerShell

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: Add a local computer to a domain using the
OUPath parameter
PowerShell

Add-Computer -DomainName Domain02 -OUPath


"OU=testOU,DC=domain,DC=Domain,DC=com"

This command adds the local computer to the Domain02 domain. It uses the OUPath
parameter to specify
the organizational unit for the new accounts.

Example 5: Add a local computer to a domain using


credentials
PowerShell

Add-Computer -ComputerName Server01 -LocalCredential Server01\Admin01 -


DomainName Domain02 -Credential Domain02\Admin02 -Restart -Force

This command adds the Server01 computer to the Domain02 domain. It uses the
LocalCredential
parameter to specify a user account that has permission to connect to
the Server01 computer. It uses
the Credential parameter to specify a user account that
has permission to join computers to the
domain. It uses the Restart parameter to restart
the computer after the join operation completes
and the Force parameter to suppress
user confirmation messages.

Example 6: Move a group of computers to a new domain


PowerShell

Add-Computer -ComputerName Server01, Server02, localhost -DomainName


Domain02 -LocalCredential Domain01\User01 -UnjoinDomainCredential
Domain01\Admin01 -Credential Domain02\Admin01 -Restart

This command moves the Server01 and Server02 computers, and the local computer,
from Domain01 to
Domain02.

It uses the LocalCredential parameter to specify a user account that has permission to
connect
to the three affected computers. It uses the UnjoinDomainCredential
parameter to specify a user
account that has permission to unjoin the computers from
the Domain01 domain and the Credential
parameter to specify a user account that has
permission to join the computers to the Domain02
domain. It uses the Restart
parameter to restart all three computers after the move is complete.

Example 7: Move a computer to a new domain and


change the name of the computer
PowerShell

Add-Computer -ComputerName Server01 -DomainName Domain02 -NewName Server044


-Credential Domain02\Admin01 -Restart

This command moves the Server01 computer to the Domain02 and changes the
machine name to Server044.

The command uses the credential of the current user to connect to the Server01
computer and unjoin
it from its current domain. It uses the Credential parameter to
specify a user account that has
permission to join the computer to the Domain02
domain.

Example 8: Add computers listed in a file to a new


domain
PowerShell

Add-Computer -ComputerName (Get-Content Servers.txt) -DomainName Domain02 -


Credential Domain02\Admin02 -Options Win9xUpgrade -Restart

This command adds the computers that are listed in the Servers.txt file to the
Domain02 domain. It
uses the Options parameter to specify the Win9xUpgrade option.
The Restart parameter
restarts all of the newly added computers after the join operation
completes.

Example 9: Add a computer to a domain using predefined


computer credentials
This first command should be run by an administrator from a computer that is already
joined to
domain Domain03 :

PowerShell
New-ADComputer -Name "Server02" -AccountPassword (ConvertTo-SecureString -
String 'TempJoinPA$$' -AsPlainText -Force)

# Then this command is run from `Server02` which is not yet domain-joined:

$joinCred = New-Object pscredential -ArgumentList ([pscustomobject]@{

UserName = $null

Password = (ConvertTo-SecureString -String 'TempJoinPA$$' -AsPlainText -


Force)[0]

})

Add-Computer -Domain "Domain03" -Options UnsecuredJoin,PasswordPass -


Credential $joinCred

This combination of commands creates a new computer account with a predefined


name and temporary
join password in a domain using an existing domain-joined
computer. Then separately, a computer with
the predefined name joins the domain
using only the computer name and the temporary join password.
The predefined
password is only used to support the join operation and is replaced as part of normal
computer account procedures after the computer completes the join.

Parameters
-ComputerName

Specifies the computers to add to a domain or workgroup.


The default is the local
computer.

Type the NetBIOS name, an Internet Protocol (IP) address, or a fully qualified domain
name of each
of the remote 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 Add-Computer even if your computer is not configured
to run remote commands.

This parameter is introduced in Windows PowerShell 3.0.

Type: String[]

Position: Named

Default value: Local computer

Accept pipeline input: True

Accept wildcard characters: False


-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Credential

Specifies a user account that has permission to join the computers to a new domain.
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 specify a user account that has permission to remove the computer from its
current domain, use
the UnjoinDomainCredential parameter. To specify a user
account that has permission to connect
to a remote computer, use the
LocalCredential parameter.

Type: PSCredential

Aliases: DomainCredential

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-DomainName

Specifies the domain to which the computers are added. This parameter is required
when adding the
computers to a domain.
Type: String

Aliases: DN, Domain

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Force

Suppresses the user confirmation prompt. Without this parameter, Add-Computer


requires you to
confirm the addition of each computer.

This parameter is introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-LocalCredential

Specifies a user account that has permission to connect to the computers that are
specified by the
ComputerName parameter. 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 specify a user account that has permission to add the computers to a new
domain, use the
Credential parameter. To specify a user account that has permission
to remove the computers from
their current domain, use the
UnjoinDomainCredential parameter.

This parameter is introduced in Windows PowerShell 3.0.

Type: PSCredential
Position: Named

Default value: Current user

Accept pipeline input: False

Accept wildcard characters: False

-NewName

Specifies a new name for the computer in the new domain. This parameter is valid
only when one
computer is being added or moved.

This parameter is introduced in Windows PowerShell 3.0.

Type: String

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Options

Specifies advanced options for the Add-Computer join operation. Enter one or more
values in a
comma-separated string.

The acceptable values for this parameter are:

AccountCreate: Creates a domain account. The Add-Computer cmdlet


automatically creates a
domain account when it adds a computer to a domain.
This option is included for completeness.

Win9XUpgrade: Indicates that the join operation is part of a Windows


operating system upgrade.

UnsecuredJoin: Performs an unsecured join. To request an unsecured join, use


the Unsecure
parameter or this option. If you want to pass a machine
password, then you must use this option in
combination with PasswordPass
option.

PasswordPass: Sets the machine password to the value of the


Credential(DomainCredential)
parameter after performing an unsecured join.
This option also indicates that the value of the
Credential (DomainCredential)
parameter is a machine password, not a user password. This option
is valid only
when the UnsecuredJoin option is specified. When using this option, the
credential
provided to the -Credential parameter must have a null username.

JoinWithNewName: Renames the computer name in the new domain to the


name specified by the
NewName parameter. When you use the NewName
parameter, this option is set automatically. This
option is designed to be used
with the Rename-Computer cmdlet. If you use the Rename-Computer
cmdlet to
rename the computer, but do not restart the computer to make the change
effective, you
can use this parameter to join the computer to a domain with its
new name.

JoinReadOnly: Uses an existing machine account to join the computer to a


read-only domain
controller. The machine account must be added to the
allowed list for password replication policy
and the account password must be
replicated to the read-only domain controller prior to the join
operation.

InstallInvoke: Sets the create (0x2) and delete (0x4) flags of the FJoinOptions
parameter
of the JoinDomainOrWorkgroup method. For more information
about the JoinDomainOrWorkgroup
method, see
JoinDomainOrWorkgroup
method of the Win32_ComputerSystem class.
For more information about
these options, see
NetJoinDomain function.

This parameter was introduced in Windows PowerShell 3.0.

Type: JoinOptions

Accepted values: AccountCreate, Win9XUpgrade, UnsecuredJoin, PasswordPass,


DeferSPNSet, JoinWithNewName, JoinReadOnly, InstallInvoke

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-OUPath

Specifies an organizational unit (OU) for the domain account. Enter the full
distinguished name of
the OU in quotation marks. The default value is the default
OU for machine objects in the domain.

Type: String
Aliases: OU

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-PassThru

Returns an object representing the item with which you are working. By default, this
cmdlet does not
generate any output.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Restart

Restarts the computers that were added to the domain or workgroup. A restart is
often required to
make the change effective.

This parameter is introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Server

Specifies the name of a domain controller that adds the computer to the domain.
Enter the name in
DomainName\ComputerName format. By default, no domain
controller is specified.
Type: String

Aliases: DC

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-UnjoinDomainCredential

Specifies a user account that has permission to remove the computers from their
current domains. 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.

Use this parameter when you are moving computers to a different domain. To
specify a user account
that has permission to join the new domain, use the
Credential parameter. To specify a user
account that has permission to connect to a
remote computer, use the LocalCredential parameter.

This parameter is introduced in Windows PowerShell 3.0.

Type: PSCredential

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Unsecure

Performs an unsecure join to the specified domain.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs.


The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-WorkgroupName

Specifies the name of a workgroup to which the computers are added. The default
value is
"WORKGROUP".

Type: String

Aliases: WGN

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe computer names and new names to the Add-Computer Cmdlet.

Outputs
ComputerChangeInfo
When you use the PassThru parameter, Add-Computer returns a ComputerChangeInfo
object.
Otherwise, this cmdlet does not generate any output.

Notes
In Windows PowerShell 2.0, the Server parameter of Add-Computer fails even when
the server
is present. In Windows PowerShell 3.0, the implementation of the Server
parameter is changed
so that it works reliably.

Related Links
Checkpoint-Computer
Remove-Computer
Restart-Computer
Rename-Computer
Restore-Computer
Stop-Computer
Test-Connection
Add-Content
Reference
Module: Microsoft.PowerShell.Management

Adds content to the specified items, such as adding words to a file.

Syntax
PowerShell

Add-Content

[-Path] <string[]>

[-Value] <Object[]>

[-PassThru]

[-Filter <string>]

[-Include <string[]>]

[-Exclude <string[]>]

[-Force]

[-Credential <pscredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[-NoNewline]

[-Encoding <FileSystemCmdletProviderEncoding>]

[-Stream <string>]

[<CommonParameters>]

PowerShell

Add-Content

[-Value] <Object[]>

-LiteralPath <string[]>

[-PassThru]

[-Filter <string>]

[-Include <string[]>]

[-Exclude <string[]>]

[-Force]

[-Credential <pscredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[-NoNewline]

[-Encoding <FileSystemCmdletProviderEncoding>]

[-Stream <string>]

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

If you need to create files or directories for the following examples, see New-Item.

Examples

Example 1: Add a string to all text files with an exception


This example appends a value to text files in the current directory but excludes files
based on
their file name.

PowerShell

Add-Content -Path .\*.txt -Exclude help* -Value 'End of file'

The Path parameter specifies all .txt files in the current directory, but the Exclude
parameter ignores file names that match the specified pattern. The Value parameter
specifies the
text string that is written to the files.

Use Get-Content to display the contents of these files.

Example 2: Add a date to the end of the specified files


This example appends the date to files in the current directory and displays the date in
the
PowerShell console.

PowerShell

Add-Content -Path .\DateTimeFile1.log, .\DateTimeFile2.log -Value (Get-Date)


-PassThru

Get-Content -Path .\DateTimeFile1.log

Tuesday, May 14, 2019 8:24:27 AM

Tuesday, May 14, 2019 8:24:27 AM

5/14/2019 8:24:27 AM

The Add-Content cmdlet creates two new files in the current directory. The Value
parameter
contains the output of the Get-Date cmdlet. The PassThru parameter outputs
the added contents
to the pipeline. Because there is no other cmdlet to receive the
output, it is displayed in the
PowerShell console. The Get-Content cmdlet displays the
updated file, DateTimeFile1.log .

Example 3: Add the contents of a specified file to another


file
This example gets the content from a file and stores the content in a variable. The
variable is
used to append the content into another file.

PowerShell

$From = Get-Content -Path .\CopyFromFile.txt

Add-Content -Path .\CopyToFile.txt -Value $From

Get-Content -Path .\CopyToFile.txt

The Get-Content cmdlet gets the contents of CopyFromFile.txt and stores the
contents in the
$From variable.
The Add-Content cmdlet updates the CopyToFile.txt file using the contents of the
$From
variable.

The Get-Content cmdlet displays CopyToFile.txt.

Example 4: Add the contents of a specified file to another


file using the pipeline
This example gets the content from a file and pipes it to the Add-Content cmdlet.

PowerShell

Get-Content -Path .\CopyFromFile.txt | Add-Content -Path .\CopyToFile.txt

Get-Content -Path .\CopyToFile.txt

The Get-Content cmdlet gets the contents of CopyFromFile.txt . The results are piped to
the
Add-Content cmdlet, which updates the CopyToFile.txt .
The last Get-Content
cmdlet displays CopyToFile.txt .

Example 5: Create a new file and copy content


This example creates a new file and copies an existing file's content into the new file.

PowerShell
Add-Content -Path .\NewFile.txt -Value (Get-Content -Path
.\CopyFromFile.txt)

Get-Content -Path .\NewFile.txt

The Add-Content cmdlet uses the Path and Value parameters to create a new file in
the
current directory.
The Get-Content cmdlet gets the contents of an existing file, CopyFromFile.txt
and
passes it to the Value parameter. The parentheses around the Get-Content cmdlet
ensure
that the command finishes before the Add-Content command begins.
The Get-Content cmdlet displays the contents of the new file, NewFile.txt .

Example 6: Add content to a read-only file


This command adds a value to the file even if the IsReadOnly file attribute is set to True.
The steps to create a read-only file are included in the example.

PowerShell

New-Item -Path .\IsReadOnlyTextFile.txt -ItemType File

Set-ItemProperty -Path .\IsReadOnlyTextFile.txt -Name IsReadOnly -Value


$True

Get-ChildItem -Path .\IsReadOnlyTextFile.txt

Add-Content -Path .\IsReadOnlyTextFile.txt -Value 'Add value to read-only


text file' -Force

Get-Content -Path .\IsReadOnlyTextFile.txt

Mode LastWriteTime Length Name

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

-ar-- 1/28/2019 13:35 0 IsReadOnlyTextFile.txt

The New-Item cmdlet uses the Path and ItemType parameters to create the file
IsReadOnlyTextFile.txt in the current directory.

The Set-ItemProperty cmdlet uses the Name and Value parameters to change the
file's
IsReadOnly property to True.
The Get-ChildItem cmdlet shows the file is empty ( 0 ) and has the read-only
attribute ( r ).
The Add-Content cmdlet uses the Path parameter to specify the file. The Value
parameter
includes the text string to append to the file. The Force parameter
writes the text to the
read-only file.
The Get-Content cmdlet uses the Path parameter to display the file's contents.

To remove the read-only attribute, use the Set-ItemProperty command with the Value
parameter
set to False .
Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Credential

7 Note

This parameter is not supported by any providers installed with PowerShell.


To
impersonate another user, or elevate your credentials when running this cmdlet,
use Invoke-Command.

Type: PSCredential

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Encoding

Specifies the type of encoding for the target file. The default value is Default .

The acceptable values for this parameter are as follows:

Ascii Uses ASCII (7-bit) character set.

BigEndianUnicode Uses UTF-16 with the big-endian byte order.


BigEndianUTF32 Uses UTF-32 with the big-endian byte order.
Byte Encodes a set of characters into a sequence of bytes.

Default Uses the encoding that corresponds to the system's active code page
(usually ANSI).
Oem Uses the encoding that corresponds to the system's current OEM code
page.
String Same as Unicode.

Unicode Uses UTF-16 with the little-endian byte order.


Unknown Same as Unicode.

UTF7 Uses UTF-7.


UTF8 Uses UTF-8.

UTF32 Uses UTF-32 with the little-endian byte order.

Encoding is a dynamic parameter that the FileSystem provider adds to the Add-
Content cmdlet. This
parameter works only in file system drives.

Type: FileSystemCmdletProviderEncoding

Accepted values: ASCII, BigEndianUnicode, BigEndianUTF32, Byte, Default, OEM,


String, Unicode, Unknown, UTF7, UTF8, UTF32

Position: Named

Default value: Default

Accept pipeline input: False

Accept wildcard characters: False

-Exclude

Specifies, as a string array, an item or items that this cmdlet excludes in the
operation. The value
of this parameter qualifies the Path parameter. Enter a path
element or pattern, such as
*.txt . Wildcard characters 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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: True

-Filter

Specifies a filter to qualify the Path parameter. The


FileSystem provider is the only
installed PowerShell provider that supports the use of filters. You can find the syntax
for the
FileSystem filter language in
about_Wildcards. Filters are more efficient
than
other parameters, because the provider applies them when the cmdlet gets the
objects rather
than having PowerShell filter the objects after they are retrieved.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Force

Overrides the read-only attribute, allowing you to add content to a read-only file. For
example,
Force overrides the read-only attribute but it does not change file
permissions.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Include

Specifies, as a string array, an item or items that this cmdlet includes in the
operation. The value
of this parameter qualifies the Path parameter. Enter a path
element or pattern, such as
"*.txt" . Wildcard characters 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.

Type: String[]
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-LiteralPath

Specifies a path to one or more locations. 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
PowerShell not to interpret any characters
as escape sequences.

For more information, see


about_Quoting_Rules.

Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-NoNewline

Indicates that this cmdlet does not add a new line or carriage return to the content.

The string representations of the input objects are concatenated to form the output.
No spaces or
newlines are inserted between the output strings. No newline is added
after the last output string.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-PassThru

Returns an object representing the added content. By default, this cmdlet does not
generate any
output.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Path

Specifies the path to the items that receive the additional content. Wildcard
characters 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. If
you specify multiple paths, use commas to
separate the paths.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-Stream

Specifies an alternative data stream for content. If the stream does not exist, this
cmdlet creates
it. Wildcard characters are not supported.

Stream is a dynamic parameter that the FileSystem provider adds to Add-Content .


This
parameter works only in file system drives.

You can use the Add-Content cmdlet to change the content of any alternate data
stream, such as
Zone.Identifier . However, we do not recommend this as a way to
eliminate security checks that
block files that are downloaded from the Internet. If
you verify that a downloaded file is safe, use
the Unblock-File cmdlet.

This parameter was introduced in PowerShell 3.0.


Type: String

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.

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Value

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.
You can use a Get-Content command to get the content and pass it to the
Value parameter.

Type: Object[]

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
Object

You can pipe values to Set-Content .

PSCredential

You can pipe credentials to Set-Content .

Outputs
None

By default, this cmdlet returns no output.

String

When you use the PassThru parameter, this cmdlet returns a System.String object
representing the content.

Notes
Windows PowerShell includes the following aliases for Add-Content :

ac

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

Related Links
about_Aliases
about_Providers
about_Transactions
Clear-Content
Get-Content
Get-Item
New-Item
Set-Content
Checkpoint-Computer
Reference
Module: Microsoft.PowerShell.Management

Creates a system restore point on the local computer.

Syntax
PowerShell

Checkpoint-Computer

[-Description] <String>
[[-RestorePointType] <String>]

[<CommonParameters>]

Description
The Checkpoint-Computer cmdlet creates a system restore point on the local computer.

System restore points and the Checkpoint-Computer cmdlet are supported only on client
operating systems, such as Windows 8, Windows 7, Windows Vista, and Windows XP.

Beginning in Windows 8, Checkpoint-Computer cannot create more than one checkpoint


each day.

Examples

Example 1: Create a system restore point


PowerShell

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: Create a system MODIFY_SETTINGS restore


point
PowerShell

Checkpoint-Computer -Description "ChangeNetSettings" -RestorePointType


MODIFY_SETTINGS

This command creates a MODIFY_SETTINGS system restore point called


"ChangeNetSettings".

Parameters
-Description

Specifies a descriptive name for the restore point.


This parameter is required.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RestorePointType

Specifies the type of restore point.


The default is APPLICATION_INSTALL.

The acceptable values for this parameter are:

APPLICATION_INSTALL
APPLICATION_UNINSTALL
DEVICE_DRIVER_INSTALL
MODIFY_SETTINGS
CANCELLED_OPERATION

Type: String

Aliases: RPT

Accepted values: APPLICATION_INSTALL, APPLICATION_UNINSTALL,


DEVICE_DRIVER_INSTALL, MODIFY_SETTINGS,
CANCELLED_OPERATION

Position: 1
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

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.

Beginning in Windows 8, Checkpoint-Computer cannot create more than one


system restore point each day. If you try to create a new restore point before the
24-hour period has elapsed, Windows PowerShell generates the following error:

"A new system restore point cannot be created because one has already been
created within the past 24 hours. Please try again later."

Related Links
Disable-ComputerRestore
Enable-ComputerRestore
Get-ComputerRestorePoint
Restore-Computer
Clear-Content
Reference
Module: Microsoft.PowerShell.Management

Deletes the contents of an item, but does not delete the item.

Syntax
PowerShell

Clear-Content

[-Path] <String[]>

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Force]

[-Credential <PSCredential>]
[-WhatIf]

[-Confirm]

[-UseTransaction]

[-Stream <String>]

[<CommonParameters>]

PowerShell

Clear-Content

-LiteralPath <String[]>

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Force]

[-Credential <PSCredential>]
[-WhatIf]

[-Confirm]

[-UseTransaction]

[-Stream <String>]

[<CommonParameters>]

PowerShell

Clear-Content

[-Path] <String[]>

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Force]

[-Credential <PSCredential>]
[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

PowerShell

Clear-Content

-LiteralPath <String[]>

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Force]

[-Credential <PSCredential>]
[-WhatIf]

[-Confirm]

[-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 items with contents, instead of

items with values.

Examples

Example 1: Delete all content from a directory


PowerShell

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: Delete content of all files with a wildcard


PowerShell

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: Clear all data from a stream


This example shows how the Clear-Content cmdlet clears the content from an alternate
data stream
while leaving the stream intact.

The first command uses the Get-Content cmdlet to get the content of the
Zone.Identifier stream
in the Copy-Script.ps1 file, which was downloaded from the
internet.

The second command uses the Clear-Content cmdlet to clear the content.

The third command repeats the first command. It verifies that the content is cleared, but
the stream
remains. If the stream were deleted, the command would generate an error.

You can use a method like this one to clear the content of an alternate data stream.
However, it is
not the recommended way to eliminate security checks that block files
that are downloaded from the
Internet. If you verify that a downloaded file is safe, use
the Unblock-File cmdlet.

PowerShell

Get-Content C:\Test\Copy-Script.ps1 -Stream Zone.Identifier

[ZoneTransfer]

ZoneId=3

Clear-Content C:\Test\Copy-Script.ps1 -Stream Zone.Identifier

Get-Content C:\Test\Copy-Script.ps1 -Stream Zone.Identifier

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.


Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Credential

7 Note

This parameter is not supported by any providers installed with PowerShell. To


impersonate another
user, or elevate your credentials when running this cmdlet,
use Invoke-Command .

Type: PSCredential

Position: Named

Default value: Current user

Accept pipeline input: True

Accept wildcard characters: False

-Exclude

Specifies, as a string array, strings that this cmdlet omits from the path to the
content. The value
of this parameter qualifies the Path parameter. Enter a path
element or pattern, such as
*.txt . Wildcards are permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Filter
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 PowerShell
filter the objects after they are retrieved.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Force

Forces the command to run without asking for user confirmation.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Include

Specifies, as a string array, content that this cmdlet clears. The value of this
parameter qualifies
the Path parameter. Enter a path element or pattern, such as
*.txt . Wildcards are permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-LiteralPath
Specifies the paths to the items from which content is deleted. Unlike the Path
parameter, 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 having PowerShell not to interpret
any characters as escape sequences.

Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Path

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.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-Stream

This is a dynamic parameter made available by the FileSystem provider.

Specifies an alternative data stream for content. If the stream does not exist, this
cmdlet creates
it. Wildcard characters are not supported.

You can use the Clear-Content cmdlet to change the content of any alternate data
stream, such as
Zone.Identifier . However, we do not recommend this as a way to
eliminate security checks that
block files that are downloaded from the internet. If
you verify that a downloaded file is safe,
use the Unblock-File cmdlet.
This parameter was introduced in Windows PowerShell 3.0.

For more information, see


about_FileSystem_Provider.

Type: String

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.

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
Windows PowerShell includes the following aliases for Clear-Content :

clc

You can use Clear-Content with the PowerShell FileSystem provider and with other
providers that
manipulate content. To clear items that are not considered to be content,
such as items managed by
the 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.

Related Links
Add-Content
Get-Content
Get-Item
Set-Content
about_Providers
Clear-EventLog
Reference
Module: Microsoft.PowerShell.Management

Clears all entries from specified event logs on the local or remote computers.

Syntax
PowerShell

Clear-EventLog

[-LogName] <String[]>

[[-ComputerName] <String[]>]
[-WhatIf]

[-Confirm]

[<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 the Get-WinEvent cmdlet.

Examples

Example 1: Clear specific event log types from the local


computer
PowerShell

Clear-EventLog "Windows PowerShell"

This command clears the entries from the Windows PowerShell event log on the local
computer.
Example 2: Clear specific multiple log types from the local
and remote computers
PowerShell

Clear-EventLog -LogName ODiag, OSession -ComputerName localhost, Server02

This command clears 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: Clear all logs on the specified computers then


display the event log list
PowerShell

Clear-EventLog -LogName application, system -confirm

This command prompts you for confirmation before deleting the entries in the specified
event logs.

Example 4: Clear all logs on the specified computers then


display the event log list
PowerShell

function clear-all-event-logs ($computerName="localhost")

$logs = Get-EventLog -ComputerName $computername -List | ForEach-Object


{$_.Log}

$logs | ForEach-Object {Clear-EventLog -ComputerName $computername -


LogName $_ }

Get-EventLog -ComputerName $computername -list

clear-all-event-logs -ComputerName 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

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.

Parameters
-ComputerName

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.

Type: String[]

Aliases: Cn

Position: 1

Default value: Local computer

Accept pipeline input: True

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf
Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-LogName

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.

) Important

This parameter is supposed to accept values from the pipeline by property


name. However, there is
a bug that prevents this from working. You must pass a
value using the parameter directly.

Type: String[]

Aliases: LN

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


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.

Related Links
Get-EventLog
Limit-EventLog
New-EventLog
Remove-EventLog
Show-EventLog
Write-EventLog
Clear-Item
Reference
Module: Microsoft.PowerShell.Management

Clears the contents of an item, but does not delete the item.

Syntax
PowerShell

Clear-Item

[-Path] <String[]>

[-Force]

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Credential <PSCredential>]
[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

PowerShell

Clear-Item

-LiteralPath <String[]>

[-Force]

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Credential <PSCredential>]
[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

Description
The Clear-Item cmdlet clears the content of an item, but it does not delete the item.
For
example, the Clear-Item cmdlet 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
PowerShell provider.
This cmdlet is similar to Clear-Content , but it works on aliases and
variables, instead of files.
Examples

Example 1: Clear the value of a variable


This command clears the value of the variable named TestVar1 .
The variable remains
and is valid, but its value is set to $null .
The variable name is prefixed with Variable: to
indicate the PowerShell Variable provider.

The alternate commands show that, to get the same result, you can switch to the
PowerShell
Variable: drive and then run the Clear-Item command.

PowerShell

Clear-Item Variable:TestVar1

Set-Location Variable:

PS Variable:\> Clear-Item TestVar1

Example 2: Clear all registry entries


This command clears 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 the Remove-ItemProperty cmdlet.


To delete the value of a registry entry, use the Clear-ItemProperty cmdlet .

PowerShell

Clear-Item HKLM:\Software\MyCompany\MyKey -Confirm

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf
Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Credential

7 Note

This parameter is not supported by any providers installed with PowerShell.


To
impersonate another user, or elevate your credentials when running this cmdlet,
use Invoke-Command.

Type: PSCredential

Position: Named

Default value: Current user

Accept pipeline input: True

Accept wildcard characters: False

-Exclude

Specifies, as a string array, an item or items that this cmdlet excludes in the
operation. The value
of this parameter qualifies the Path parameter. Enter a path
element or pattern, such as
*.txt . Wildcard characters 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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True


-Filter

Specifies a filter to qualify the Path parameter. The


FileSystem provider is the only
installed PowerShell provider that supports the use of filters. You can find the syntax
for the
FileSystem filter language in
about_Wildcards. Filters are more
efficient than
other parameters, because the provider applies them when the cmdlet gets the
objects
rather than having PowerShell filter the objects after they are retrieved.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Force

Indicates that the cmdlet clears 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.
The cmdlet cannot
override security restrictions, even when the Force parameter is used.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Include

Specifies, as a string array, an item or items that this cmdlet includes in the
operation. The value
of this parameter qualifies the Path parameter. Enter a path
element or pattern, such as
"*.txt" . Wildcard characters 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.

Type: String[]
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-LiteralPath

Specifies a path to one or more locations. 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
PowerShell not to interpret any characters
as escape sequences.

For more information, see about_Quoting_Rules.

Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Path

Specifies the path to the items being cleared.


Wildcard characters are permitted.
This
parameter is required, but the parameter name Path is optional.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-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.
Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs.


The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a path string to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
Windows PowerShell includes the following aliases for Clear-Item :

cli
The Clear-Item cmdlet is supported only by several 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. To list the
providers available in your session, type Get-PsProvider .
For more information, see
about_Providers.

You cannot use Clear-Item to delete the contents of a file, because the PowerShell
FileSystem
provider does not support this cmdlet. To clear files, use the Clear-
Content .

Related Links
Copy-Item
Get-Item
Invoke-Item
Move-Item
New-Item
Remove-Item
Rename-Item
Set-Item
about_Providers
Clear-ItemProperty
Reference
Module: Microsoft.PowerShell.Management

Clears the value of a property but does not delete the property.

Syntax
PowerShell

Clear-ItemProperty

[-Path] <String[]>

[-Name] <String>

[-PassThru]

[-Force]

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Credential <PSCredential>]
[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

PowerShell

Clear-ItemProperty

-LiteralPath <String[]>

[-Name] <String>

[-PassThru]

[-Force]

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Credential <PSCredential>]
[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

Description
The Clear-ItemProperty cmdlet clears 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.
Examples

Example 1: Clear the value of registry key


This command clears the data in the "Options" registry value in the "MyApp" subkey of
HKEY_LOCAL_MACHINE\Software\MyCompany .

PowerShell

Clear-ItemProperty -Path "HKLM:\Software\MyCompany\MyApp" -Name "Options"

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Credential

7 Note

This parameter is not supported by any providers installed with PowerShell.


To
impersonate another user, or elevate your credentials when running this cmdlet,
use Invoke-Command.

Type: PSCredential

Position: Named

Default value: Current user


Accept pipeline input: True

Accept wildcard characters: False

-Exclude

Specifies, as a string array, an item or items that this cmdlet excludes in the
operation. The value
of this parameter qualifies the Path parameter. Enter a path
element or pattern, such as
*.txt . Wildcard characters 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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Filter

Specifies a filter to qualify the Path parameter. The FileSystem


provider is the only
installed PowerShell provider that supports the use of filters. You can find
the syntax
for the FileSystem filter language in about_Wildcards.
Filters are more efficient than
other parameters, because the provider applies them when the cmdlet
gets the
objects rather than having PowerShell filter the objects after they are retrieved.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Force

Indicates that this cmdlet deletes properties from items that cannot otherwise be
accessed by the
user. Implementation varies from provider to provider.
For more
information, see about_Providers.
Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Include

Specifies, as a string array, an item or items that this cmdlet includes in the
operation. The value
of this parameter qualifies the Path parameter. Enter a path
element or pattern, such as
"*.txt" . Wildcard characters 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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-LiteralPath

Specifies a path to one or more locations. 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
PowerShell not to interpret any characters
as escape sequences.

For more information, see about_Quoting_Rules.

Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True


Accept wildcard characters: False

-Name

Specifies the name of the property to be cleared, such as the name of a registry
value.
Wildcard characters are permitted.

Type: String

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-PassThru

Returns an object representing the item with which you are working.
By default, this
cmdlet does not generate any output.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Path

Specifies the path to the property being cleared.


Wildcard characters are permitted.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

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

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs.


The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a path string to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

PSCustomObject

When you use the PassThru parameter, this cmdlet returns a PSCustomObject object
representing the cleared item property.
Notes
Windows PowerShell includes the following aliases for Clear-ItemProperty :

clp

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.

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.

Related Links
Copy-ItemProperty
Get-ItemProperty
Move-ItemProperty
New-ItemProperty
Rename-ItemProperty
about_Providers
Clear-RecycleBin
Reference
Module: Microsoft.PowerShell.Management

Clears the contents of a recycle bin.

Syntax
PowerShell

Clear-RecycleBin

[[-DriveLetter] <String[]>]

[-Force]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Clear-RecycleBin cmdlet deletes the content of a computer's recycle bin. This
action is like
using Windows Empty Recycle Bin.

Examples

1: Clear all recycle bins


In this example, all the local computer's recycle bins are cleared.

PowerShell

Clear-RecycleBin

Confirm

Are you sure you want to perform this action?

Performing the operation "Clear-RecycleBin" on target "All of the contents


of the Recycle Bin".

[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help
(default is "Y"):

Clear-RecycleBin prompts the user for confirmation to clear all recycle bins on the local
computer.
2: Clear a specified recycle bin
This example clears the recycle bin for a specified drive letter.

PowerShell

Clear-RecycleBin -DriveLetter C

Clear-RecycleBin uses the DriveLetter parameter to specify the recycle bin on the C

volume. The user is prompted for confirmation to run the command.

3: Clear all recycle bins without confirmation


This example doesn't prompt for confirmation to clear the local computer's recycle bins.

PowerShell

Clear-RecycleBin -Force

Clear-RecycleBin uses the Force parameter and doesn't prompt the user for

confirmation to
clear all recycle bins on the local computer.

An alternative is to replace -Force with -Confirm:$false .

Parameters
-Confirm

Prompts for user confirmation before running the cmdlet. The user is prompted for
confirmation even
if the Confirm parameter isn't specified.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-DriveLetter
Specifies the recycle bin to clear for a single drive letter or an array of drive letters.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Force

Specifies that the user isn't prompted for confirmation to clear a recycle bin. The
Force
parameter also overrides the WhatIf and Confirm parameters.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if Clear-RecycleBin runs. The cmdlet isn't run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Outputs
None

This cmdlet returns no output.


Complete-Transaction
Reference
Module: Microsoft.PowerShell.Management

Commits the active transaction.

Syntax
PowerShell

Complete-Transaction

[-WhatIf]

[-Confirm]

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

Examples

Example 1: Commit a transaction


PowerShell

Set-Location hkcu:\software

Start-Transaction

New-Item MyCompany -UseTransaction

Get-ChildItem m*

Hive: HKEY_CURRENT_USER\software

SKC VC Name Property

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

82 1 Microsoft {(default)}

Complete-Transaction

Get-ChildItem m*

Hive: HKEY_CURRENT_USER\Software

SKC VC Name Property

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

82 1 Microsoft {(default)}

0 0 MyCompany {}

This example shows what happens when you use 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 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 Get-ChildItem command shows that the
registry is changed.

Example 2: Commit a transaction that has more than one


subscriber
PowerShell

Set-Location hkcu:\software

Start-Transaction

New-Item MyCompany -UseTransaction

Hive: HKEY_CURRENT_USER\Software

SKC VC Name Property

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

0 0 MyCompany {}

Start-Transaction

Get-Transaction

RollbackPreference SubscriberCount Status

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

Error 2 Active

New-ItemProperty -Path MyCompany -Name MyKey -Value -UseTransaction

MyKey

-----

123

Complete-Transaction

Get-Transaction

RollbackPreference SubscriberCount Status

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

Error 1 Active

Get-ChildItem m*

Hive: HKEY_CURRENT_USER\Software

SKC VC Name Property

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

82 1 Microsoft {(default)}

Complete-Transaction

Get-ChildItem m*

Hive: HKEY_CURRENT_USER\Software

SKC VC Name Property

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

82 1 Microsoft {(default)}

0 1 MyCompany {MyKey}

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
cmdlet 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 cmdlet 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 Get-ChildItem m*
command.

The second Complete-Transaction command commits the entire transaction and


changes the data in the
registry. This is confirmed by a second Get-ChildItem m*
command, which shows the changes.

Example 3: Perform a transaction that does not change


any data
PowerShell

Set-Location hkcu:\software

Start-Transaction

New-Item MyCompany -UseTransaction

Get-ChildItem m*

Hive: HKEY_CURRENT_USER\Software

SKC VC Name Property

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

82 1 Microsoft {(default)}

Get-ChildItem m* -UseTransaction

Hive: HKEY_CURRENT_USER\Software

SKC VC Name Property

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

82 1 Microsoft {(default)}

0 0 MyCompany {}

Complete-Transaction

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 Get-ChildItem command shows the registry without the new
key.

However, when you add the UseTransaction parameter to the Get-ChildItem 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.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


Inputs
None

You cannot pipe objects to this cmdlet.

Outputs
None

This cmdlet does not generate any output.

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.

Related Links
Get-Transaction
Start-Transaction
Undo-Transaction
Use-Transaction
Get-ChildItem
New-Item
New-ItemProperty
Convert-Path
Reference
Module: Microsoft.PowerShell.Management

Converts a path from a PowerShell path to a PowerShell provider path.

Syntax
PowerShell

Convert-Path

[-Path] <String[]>

[-UseTransaction]

[<CommonParameters>]

PowerShell

Convert-Path

-LiteralPath <String[]>

[-UseTransaction]

[<CommonParameters>]

Description
The Convert-Path cmdlet converts a path from a PowerShell path to a PowerShell
provider path.

Examples

Example 1: Convert the working directory to a standard


file system path
This example converts the current working directory, which is represented by a dot ( . ),
to a
standard FileSystem path.

PowerShell

PS C:\> Convert-Path .

C:\
Example 2: Convert a provider path to a standard registry
path
This example converts the PowerShell provider path to a standard registry path.

PowerShell

PS C:\> Convert-Path HKLM:\Software\Microsoft

HKEY_LOCAL_MACHINE\Software\Microsoft

Example 3: Convert a path to a string


This example converts the path to the home directory of the current provider, which is
the
FileSystem provider, to a string.

PowerShell

PS C:\> Convert-Path ~

C:\Users\User01

Parameters
-LiteralPath

Specifies, as a string array, 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 PowerShell not
to interpret any characters as escape sequences.

Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Path
Specifies the PowerShell path to be converted.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

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.

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a path, but not a literal path, to this cmdlet.

Outputs
String

This cmdlet returns a string that contains the converted path.

Notes
Windows PowerShell includes the following aliases for Convert-Path :
cvpa

The cmdlets that contain the Path noun manipulate path names and return the names in
a concise
format that all 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.

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

Convert-Path only converts existing paths. It cannot be used to convert a location that
does not
exist yet.

Related Links
Join-Path
Resolve-Path
Split-Path
Test-Path
Get-PSProvider
Copy-Item
Reference
Module: Microsoft.PowerShell.Management

Copies an item from one location to another.

Syntax
PowerShell

Copy-Item

[-Path] <String[]>

[[-Destination] <String>]

[-Container]

[-Force]

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Recurse]

[-PassThru]

[-Credential <PSCredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[-FromSession <PSSession>]

[-ToSession <PSSession>]

[<CommonParameters>]

PowerShell

Copy-Item

-LiteralPath <String[]>

[[-Destination] <String>]

[-Container]

[-Force]

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Recurse]

[-PassThru]

[-Credential <PSCredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[-FromSession <PSSession>]

[-ToSession <PSSession>]

[<CommonParameters>]
PowerShell

Copy-Item

[-Path] <String[]>

[[-Destination] <String>]

[-Container]

[-Force]

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Recurse]

[-PassThru]

[-Credential <PSCredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

PowerShell

Copy-Item

-LiteralPath <String[]>

[[-Destination] <String>]

[-Container]

[-Force]

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Recurse]

[-PassThru]

[-Credential <PSCredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

Description
The Copy-Item cmdlet copies an item from one location to another location in the same
namespace.
For instance, it can copy a file to a folder, but it can't copy a file to a
certificate drive.

This cmdlet doesn't cut or delete the items being copied. The particular items that the
cmdlet can
copy depend on the PowerShell provider that exposes the item. For instance,
it can copy files and
directories in a file system drive and registry keys and entries in the
registry drive.
This cmdlet can copy and rename items in the same command. To rename an item,
enter the new name in
the value of the Destination parameter. To rename an item and
not copy it, use the Rename-Item
cmdlet.

Examples

Example 1: Copy a file to the specified directory


This example copies the mar1604.log.txt file to the C:\Presentation directory. The
original file
isn't deleted.

PowerShell

Copy-Item "C:\Wabash\Logfiles\mar1604.log.txt" -Destination


"C:\Presentation"

Example 2: Copy directory contents to an existing


directory
This example copies the contents of the C:\Logfiles directory into the existing
C:\Drawings
directory. The Logfiles directory isn't copied.

If the Logfiles directory has files in subdirectories, those subdirectories are copied with
their
file trees intact. By default, the Container parameter is set to True, which preserves
the
directory structure.

PowerShell

Copy-Item -Path "C:\Logfiles\*" -Destination "C:\Drawings" -Recurse

7 Note

If the path C:\Drawings doesn't exist the cmdlet copies all the files from the
Logfiles
folder into a single file C:\Drawings .

Example 3: Copy directory and contents to a new


directory
This example copies the contents of the C:\Logfiles source directory and creates a new
destination
directory. The new destination directory, \Logs is created in C:\Drawings .

To include the source directory's name, copy to an existing destination directory as


shown in
Example 2. Or, name the new destination directory with the same as the
source directory.

PowerShell

Copy-Item -Path "C:\Logfiles" -Destination "C:\Drawings\Logs" -Recurse

7 Note

If the Path includes \* , all the directory's file contents, including the subdirectory
trees, are copied to the new destination directory. For example:

Copy-Item -Path "C:\Logfiles\*" -Destination "C:\Drawings\Logs" -Recurse

Example 4: Copy a file to the specified directory and


rename the file
This example uses the Copy-Item cmdlet to copy the Get-Widget.ps1 script from the
\\Server01\Share directory to the \\Server12\ScriptArchive directory. As part of the
copy
operation, the command changes the item name from Get-Widget.ps1 to Get-
Widget.ps1.txt , so it
can be safely attached to email messages.

PowerShell

Copy-Item "\\Server01\Share\Get-Widget.ps1" -Destination


"\\Server12\ScriptArchive\Get-Widget.ps1.txt"

Example 5: Copy a file to a remote computer


A session is created to the remote computer named Server01 with the credential of
Contoso\User01 and stores the results in the variable named $Session .

The Copy-Item cmdlet copies test.log from the D:\Folder001 folder to the
C:\Folder001_Copy
folder on the remote computer using the session information stored

in the $Session variable. The


original file isn't deleted.
PowerShell

$Session = New-PSSession -ComputerName "Server01" -Credential


"Contoso\User01"

Copy-Item "D:\Folder001\test.log" -Destination "C:\Folder001_Copy\" -


ToSession $Session

Example 6: Copy a folder to a remote computer


A session is created to the remote computer named Server01 with the credential of
Contoso\User01 and stores the results in the variable named $Session .

The Copy-Item cmdlet copies the D:\Folder002 folder to the C:\Folder002_Copy


directory on the
remote computer using the session information stored in the $Session
variable. Any subfolders or
files aren't copied without using the Recurse switch. The
operation creates the Folder002_Copy
folder if it doesn't already exist.

PowerShell

$Session = New-PSSession -ComputerName "Server02" -Credential


"Contoso\User01"

Copy-Item "D:\Folder002\" -Destination "C:\Folder002_Copy\" -ToSession


$Session

Example 7: Recursively copy the entire contents of a


folder to a remote computer
A session is created to the remote computer named Server01 with the credential of
Contoso\User01 and stores the results in the variable named $Session .

The Copy-Item cmdlet copies the entire contents from the D:\Folder003 folder to the
C:\Folder003_Copy directory on the remote computer using the session information

stored in the
$Session variable. The subfolders are copied with their file trees intact. The
operation creates
the Folder003_Copy folder if it doesn't already exist.

PowerShell

$Session = New-PSSession -ComputerName "Server04" -Credential


"Contoso\User01"

Copy-Item "D:\Folder003\" -Destination "C:\Folder003_Copy\" -ToSession


$Session -Recurse
Example 8: Copy a file to a remote computer and then
rename the file
A session is created to the remote computer named Server01 with the credential of
Contoso\User01 and stores the results in the variable named $Session .

The Copy-Item cmdlet copies scriptingexample.ps1 from the D:\Folder004 folder to the
C:\Folder004_Copy folder on the remote computer using the session information stored
in the
$Session variable. The original file isn't deleted.

PowerShell

$Session = New-PSSession -ComputerName "Server04" -Credential


"Contoso\User01"

Copy-Item "D:\Folder004\scriptingexample.ps1" -Destination


"C:\Folder004_Copy\scriptingexample_copy.ps1" -ToSession $Session

Example 9: Copy a remote file to the local computer


A session is created to the remote computer named Server01 with the credential of
Contoso\User01 and stores the results in the variable named $Session .

The Copy-Item cmdlet copies test.log from the remote C:\MyRemoteData\ to the local
D:\MyLocalData folder using the session information stored in the $Session variable.

The
original file isn't deleted.

PowerShell

$Session = New-PSSession -ComputerName "Server01" -Credential


"Contoso\User01"

Copy-Item "C:\MyRemoteData\test.log" -Destination "D:\MyLocalData\" -


FromSession $Session

Example 10: Copy the entire contents of a remote folder


to the local computer
A session is created to the remote computer named Server01 with the credential of
Contoso\User01 and stores the results in the variable named $Session .

The Copy-Item cmdlet copies the entire contents from the remote
C:\MyRemoteData\scripts folder
to the local D:\MyLocalData folder using the session
information stored in the $Session
variable. If the scripts folder has files in subfolders,
those subfolders are copied with their
file trees intact.

PowerShell

$Session = New-PSSession -ComputerName "Server01" -Credential


"Contoso\User01"

Copy-Item "C:\MyRemoteData\scripts" -Destination "D:\MyLocalData\" -


FromSession $Session

Example 11: Recursively copy the entire contents of a


remote folder to the local computer
A session is created to the remote computer named Server01 with the credential of
Contoso\User01 and stores the results in the variable named $Session .

The Copy-Item cmdlet copies the entire contents from the remote
C:\MyRemoteData\scripts folder
to the local D:\MyLocalData\scripts folder using the
session information stored in the $Session
variable. Because the Recurse parameter is
used, the operation creates the scripts folder if it
doesn't already exist. If the scripts
folder has files in subfolders, those subfolders are
copied with their file trees intact.

PowerShell

$Session = New-PSSession -ComputerName "Server01" -Credential


"Contoso\User01"

Copy-Item "C:\MyRemoteData\scripts" -Destination "D:\MyLocalData\scripts" -


FromSession $Session -Recurse

Example 12: Recursively copy files from a folder tree into


the current folder
This example shows how to copy files from a multilevel folder structure into a single flat
folder.
The first three commands show the existing folder structure and the contents of
two files, both
names file3.txt .

PowerShell

PS C:\temp\test> (Get-ChildItem C:\temp\tree -Recurse).FullName

C:\temp\tree\subfolder

C:\temp\tree\file1.txt

C:\temp\tree\file2.txt

C:\temp\tree\file3.txt

C:\temp\tree\subfolder\file3.txt

C:\temp\tree\subfolder\file4.txt

C:\temp\tree\subfolder\file5.txt

PS C:\temp\test> Get-Content C:\temp\tree\file3.txt

This is file3.txt in the root folder

PS C:\temp\test> Get-Content C:\temp\tree\subfolder\file3.txt

This is file3.txt in the subfolder

PS C:\temp\test> Copy-Item -Path C:\temp\tree -Filter *.txt -Recurse -


Container:$false

PS C:\temp\test> (Get-ChildItem . -Recurse).FullName

C:\temp\test\subfolder

C:\temp\test\file1.txt

C:\temp\test\file2.txt

C:\temp\test\file3.txt

C:\temp\test\file4.txt

C:\temp\test\file5.txt

PS C:\temp\test> Get-Content .\file3.txt

This is file3.txt in the subfolder

The Copy-Item cmdlet has the Container parameter set to $false . This causes the
contents of
the source folder to be copied but doesn't preserve the folder structure.
Notice that files with
the same name are overwritten in the destination folder.

Example 13: Using filters to copy items without recursion


This example shows the results using the Include parameter to select the items to be
copied.

This example uses the following folder structure containing the files to be copied:

D:\temp\tree\example.ps1

D:\temp\tree\example.txt
D:\temp\tree\examples\

D:\temp\tree\examples\example_1.txt
D:\temp\tree\examples\example_2.txt

D:\temp\tree\examples\subfolder\

D:\temp\tree\examples\subfolder\test.txt

In this example, Copy-Item is called with a wildcard for both the Path and Include
parameters. Specifying a wildcard for the Path parameter ensures that it processes all
files and
folders that match D:\temp\tree\* . The Include parameter filters the list of
items to process,
limiting the operation to only those paths that begin with ex .
PowerShell

PS D:\temp\test\out> Copy-Item -Path D:\temp\tree\* -Include ex*

PS D:\temp\test\out> (Get-ChildItem -Recurse).FullName

D:\temp\out\examples

D:\temp\out\example.ps1

D:\temp\out\example.txt

The Include parameter is applied to the contents of D:\temp\tree folder to copy all
items that
match ex* . Notice that, without recursion, the D:\temp\out\examples folder is
copied, but none
of its contents are copied.

Example 14: Using filters to copy items with recursion


This example shows the results using the Include parameter to select the items to be
copied.

This example uses the following folder structure containing the files to be copied:

D:\temp\tree\example.ps1

D:\temp\tree\example.txt

D:\temp\tree\examples\
D:\temp\tree\examples\example_1.txt

D:\temp\tree\examples\example_2.txt
D:\temp\tree\examples\subfolder\

D:\temp\tree\examples\subfolder\test.txt

In this example, Copy-Item is called with a wildcard for both the Path and Include
parameters. Specifying a wildcard for the Path parameter ensures that it processes all
the files
and folders that match D:\temp\tree\* . The Include parameter filters the list of
items to
process, limiting the operation to only those paths that begin with ex .

PowerShell

D:\temp\out> Copy-Item -Path D:\temp\tree\* -Include ex* -Recurse

D:\temp\out> (Get-ChildItem -Recurse).FullName

D:\temp\out\examples

D:\temp\out\example.ps1

D:\temp\out\example.txt

D:\temp\out\examples\subfolder

D:\temp\out\examples\example_1.txt

D:\temp\out\examples\example_2.txt

D:\temp\out\examples\subfolder\test.txt
The Include parameter is applied to the contents of D:\temp\tree folder to copy all
items that
match ex* . Notice that, with recursion, the D:\temp\out\examples folder is
copied along with all
the files and subfolders. The copy includes files that do not match
the include filter. When using
Copy-Item , the filters only apply to the top-level specified
by the Path parameter. Then
recursion is applied to those matching items.

7 Note

The behavior of the Exclude parameter is the same as described in this example,
except that
it limits the operation to only those paths that don't match the pattern.

Example 15: Limit the files to recursively copy from a


wildcard-specified path
This example shows how to limit the files recursively copied from a wildcard-matching
path into
another folder. Example 13 shows that, because the Include parameter only
filters on the paths
resolved for a wildcard-specifying Path, the Include parameter can't
be used to limit the
files recursively copied from a folder. Instead, you can use Get-
ChildItem to find the items you
want to copy and pass those items to Copy-Item .

This example uses the following folder structure containing the files to be copied:

D:\temp\tree\example.ps1

D:\temp\tree\example.txt
D:\temp\tree\examples\

D:\temp\tree\examples\example_1.txt
D:\temp\tree\examples\example_2.txt

D:\temp\tree\examples\subfolder\

D:\temp\tree\examples\subfolder\test.txt

To copy all items that begin with ex* , use Get-ChildItem with the Recurse and Filter
parameters and pipe the results to Copy-Item .

PowerShell

D:\temp\out> Get-ChildItem -Path D:\temp\tree -Recurse -Filter ex* | Copy-


Item

D:\temp\out> (Get-ChildItem -Recurse).FullName

D:\temp\out\examples

D:\temp\out\example_1.txt

D:\temp\out\example_2.txt

D:\temp\out\example.ps1

D:\temp\out\example.txt

Unlike the Copy-Item , the Filter parameter for Get-ChildItem applies to the items
discovered
during recursion. This enables you to find, filter, and then copy items
recursively.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Container

Indicates that this cmdlet preserves container objects during the copy operation. By
default, the
Container parameter is set to True.

Type: SwitchParameter

Position: Named

Default value: True

Accept pipeline input: False

Accept wildcard characters: False

-Credential

7 Note
This parameter isn't supported by any providers installed with PowerShell.
To
impersonate another user, or elevate your credentials when running this cmdlet,
use Invoke-Command.

Type: PSCredential

Position: Named

Default value: Current user

Accept pipeline input: True

Accept wildcard characters: False

-Destination

Specifies the path to the new location. The default is the current directory.

To rename the item being copied, specify a new name in the value of the Destination
parameter.

Type: String

Position: 1

Default value: Current directory

Accept pipeline input: True

Accept wildcard characters: False

-Exclude

Specifies one or more path elements or patterns, such as "*.txt" , to limit this
cmdlet's
operation. The value of this parameter filters against the wildcard-matching
result of the Path
parameter, not the final results. This parameter is only effective
when the Path is specified
with one or more wildcards. Since this parameter only
filters on the paths resolved for the Path
parameter, it doesn't filter any items
discovered when recursing through child folders with the
Recurse parameter.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: True

-Filter

Specifies a filter to qualify the Path parameter. The


FileSystem provider is the only
installed PowerShell provider that supports the use of filters. You can find the syntax
for the
FileSystem filter language in
about_Wildcards. Filters are more efficient
than
other parameters, because the provider applies them when the cmdlet gets the
objects rather
than having PowerShell filter the objects after they're retrieved.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Force

Indicates that this cmdlet copies items that can't otherwise be changed, such as
copying over a
read-only file or alias.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-FromSession

This is a dynamic parameter made available by the FileSystem provider.

Specify the PSSession object from which a remote file is being copied. When you use
this
parameter, the Path and LiteralPath parameters refer to the local path on the
remote
machine.

For more information, see


about_FileSystem_Provider.

Type: PSSession
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Include

Specifies one or more path elements or patterns, such as "*.txt" , to limit this
cmdlet's
operation. The value of this parameter filters against the wildcard-matching
result of the Path
parameter, not the final results. This parameter is only effective
when the Path is specified
with one or more wildcards. Since this parameter only
filters on the paths resolved for the Path
parameter, it doesn't filter any items
discovered when recursing through child folders with the
Recurse parameter.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-LiteralPath

Specifies a path to one or more locations. The value of LiteralPath is used exactly as
it's
typed. No characters are interpreted as wildcards. If the path includes escape
characters, enclose
it in single quotation marks. Single quotation marks tell
PowerShell not to interpret any characters
as escape sequences.

For more information, see about_Quoting_Rules.

Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False


-PassThru

Returns an object that represents the item with which you're working. By default, this
cmdlet
doesn't generate any output.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Path

Specifies, as a string array, the path to the items to copy. Wildcard characters are
permitted.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-Recurse

Indicates that this cmdlet does a recursive copy.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-ToSession

This is a dynamic parameter made available by the FileSystem provider.


Specify the PSSession object to which a remote file is being copied. When you use
this
parameter, the Destination parameter refers to the local path on the remote
machine.

For more information, see


about_FileSystem_Provider.

Type: PSSession

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.

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet isn't run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


Inputs
String

You can pipe a string that contains a path to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

PSObject

When you use the PassThru parameter, this cmdlet returns an object representing the
copied
item.

Notes
Windows PowerShell includes the following aliases for Copy-Item :

copy

cp
cpi

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

Related Links
about_Providers
Clear-Item
Get-Item
Get-PSProvider
Invoke-Item
Move-Item
New-Item
Remove-Item
Rename-Item
Set-Item
Copy-ItemProperty
Reference
Module: Microsoft.PowerShell.Management

Copies a property and value from a specified location to another location.

Syntax
PowerShell

Copy-ItemProperty

[-Path] <String[]>

[-Name] <String>

[-Destination] <String>

[-PassThru]

[-Force]

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Credential <PSCredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

PowerShell

Copy-ItemProperty

-LiteralPath <String[]>

[-Name] <String>

[-Destination] <String>

[-PassThru]

[-Force]

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Credential <PSCredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

Description
The Copy-ItemProperty cmdlet copies a property and value from a specified location to
another location.
For instance, you can use this cmdlet to copy one or more registry
entries from one registry key to another registry key.

Examples

Example 1: Copy a property from a registry key to another


registry key
This command copies the property named "MyProperty" from the "MyApplication"
registry key to the "MyApplicationRev2" registry key.

PowerShell

Copy-ItemProperty -Path "MyApplication" -Destination


"HKLM:\Software\MyApplicationRev2" -Name "MyProperty"

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Credential

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 are prompted for a password.

2 Warning

This parameter is not supported by any providers installed with Windows


PowerShell.

Type: PSCredential

Position: Named

Default value: Current user

Accept pipeline input: True

Accept wildcard characters: False

-Destination

Specifies the path to the destination location.

Type: String

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Exclude

Specifies, as a string array, an item or items that this cmdlet excludes.


The value of
this parameter qualifies the Path parameter.
Enter a path element or pattern, such as
"*.txt".
Wildcard characters are permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True


-Filter

Specifies a filter in the format or language of the provider.


The value of this
parameter qualifies the Path parameter.

The syntax of the filter, including the use of wildcard characters, depends on the
provider.
Filters are more efficient than other parameters, because the provider
applies them when the cmdlet gets the objects rather than having PowerShell filter
the objects after they are retrieved.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Force

Forces the command to run without asking for user confirmation.


Implementation
varies from provider to provider.
For more information, see about_Providers.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Include

Specifies, as a string array, an item or items that this cmdlet includes in the
operation.
The value of this parameter qualifies the Path parameter.
Enter a path
element or pattern, such as "*.txt".
Wildcard characters are permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-LiteralPath

Specifies the path to the current location of the property.


Unlike the Path parameter,
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 PowerShell not to interpret any characters as escape
sequences.

Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies the name of the property to be copied.

Type: String

Aliases: PSProperty

Position: 2

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-PassThru

Returns an object representing the item with which you are working.
By default, this
cmdlet does not generate any output.

Type: SwitchParameter

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-Path

Specifies, as a string array, the path to the property to be copied.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

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.

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs.


The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False


Accept wildcard characters: False

Inputs
String

You can pipe a string that contains a path to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

PSCustomObject

When you use the PassThru parameter, this cmdlet returns a PSCustomObject
representing the
copied item property.

Notes
Windows PowerShell includes the following aliases for Copy-ItemProperty :

cpp

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

Related Links
Clear-ItemProperty
Get-ItemProperty
Move-ItemProperty
New-ItemProperty
Rename-ItemProperty
Set-ItemProperty
Get-PSProvider
about_Providers
Debug-Process
Reference
Module: Microsoft.PowerShell.Management

Debugs one or more processes running on the local computer.

Syntax
PowerShell

Debug-Process

[-Name] <String[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Debug-Process

[-Id] <Int32[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Debug-Process

-InputObject <Process[]>

[-WhatIf]

[-Confirm]

[<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 this cmdlet.

This cmdlet attaches the debugger that is currently registered for the process. Before
using this
cmdlet, verify that a debugger is downloaded and correctly configured.
Examples

Example 1: Attach a debugger to a process on the


computer
PowerShell

PS C:\> Debug-Process -Name "Windows Powershell"

This command attaches a debugger to the PowerShell process on the computer.

Example 2: Attach a debugger to all processes that begin


with the specified string
PowerShell

PS C:\> Debug-Process -Name "SQL*"

This command attaches a debugger to all processes that have names that begin with
SQL.

Example 3: Attach a debugger to multiple processes


PowerShell

PS C:\> Debug-Process "Winlogon", "Explorer", "Outlook"

This command attaches a debugger to the Winlogon, Explorer, and Outlook processes.

Example 4: Attach a debugger to multiple process IDs


PowerShell

PS C:\> Debug-Process -Id 1132, 2028

This command attaches a debugger to the processes that have process IDs 1132 and
2028.
Example 5: Use Get-Process to get a process then attach a
debugger to it
PowerShell

PS C:\> Get-Process "Windows 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: Attach a debugger to a current process on the


local computer
PowerShell

PS C:\> $PID | Debug-Process

This command attaches a debugger to the current PowerShell processes on the


computer.

The command 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: Attach a debugger to the specified process on


multiple computers
PowerShell

PS C:\> Get-Process -ComputerName "Server01", "Server02" -Name "MyApp" |


Debug-Process

This command attaches a debugger to the MyApp processes on the Server01 and
Server02 computers.
The command 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: Attach a debugger to a process that uses the


InputObject parameter
PowerShell

PS C:\> $P = Get-Process "Windows PowerShell"

PS C:\> 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 variable named $P .

The second command uses the InputObject parameter of the Debug-Process cmdlet to
submit the
process object in the $P variable.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Id

Specifies the process IDs of the processes to be debugged. The Id parameter name is
optional.

To find the process ID of a process, type Get-Process .


Type: Int32[]

Aliases: PID, ProcessId

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-InputObject

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 the Get-Process
cmdlet. You can also pipe process objects to this
cmdlet.

Type: Process[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies the names of the processes to be debugged. If there is more than one
process with the same
name, this cmdlet attaches a debugger to all processes with
that name. The Name parameter is
optional.

Type: String[]

Aliases: ProcessName

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
Int32

You can pipe a process ID to this cmdlet.

Process

You can pipe a process object to this cmdlet.

String

You can pipe a process name to this cmdlet.

Outputs
None

This cmdlet returns no 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 library.

Related Links
Debug-Process
Get-Process
Start-Process
Stop-Process
Wait-Process
Disable-ComputerRestore
Reference
Module: Microsoft.PowerShell.Management

Disables the System Restore feature on the specified file system drive.

Syntax
PowerShell

Disable-ComputerRestore

[-Drive] <String[]>

[-WhatIf]

[-Confirm]

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

System restore points and the ComputerRestore cmdlets are supported only on client
operating
systems, such as Windows 7, Windows Vista, and Windows XP.

Examples

Example 1: Disable System Restore on the specified drive


PowerShell

Disable-ComputerRestore -Drive "C:\"


This command disables System Restore on the C: drive.

Example 2: Disable System Restore on multiple drives


PowerShell

Disable-ComputerRestore "C:\", "D:\"

This command disables System Restore on the C: and D: drives. The command uses the
Drive
parameter, but it omits the Drive parameter name.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Drive

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.

Type: String[]

Position: 0
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You cannot pipe input to this cmdlet.

Outputs
None

This cmdlet does not generate any output.

Notes
To run this cmdlet 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.

Related Links
Checkpoint-Computer
Enable-ComputerRestore
Get-ComputerRestorePoint
Restart-Computer
Restore-Computer
Enable-ComputerRestore
Reference
Module: Microsoft.PowerShell.Management

Enables the System Restore feature on the specified file system drive.

Syntax
PowerShell

Enable-ComputerRestore

[-Drive] <String[]>

[-WhatIf]

[-Confirm]

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

System restore points and the ComputerRestore cmdlets are supported only on client
operating
systems, such as Windows 7, Windows Vista, and Windows XP.

Examples

Example 1: Enable System Restore on the specified drive


PowerShell

Enable-ComputerRestore -Drive "C:\"

This command enables System Restore on the C: drive of the local computer.
Example 2: Enable System Restore on multiple drives
PowerShell

Enable-ComputerRestore -Drive "C:\", "D:\"

This command enables System Restore on the C: and D: drives of the local computer.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Drive

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.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You cannot pipe objects to this cmdlet.

Outputs
None

This cmdlet does not generate any output.

Notes
To run this cmdlet 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.
Related Links
Checkpoint-Computer
Disable-ComputerRestore
Get-ComputerRestorePoint
Restart-Computer
Restore-Computer
Get-ChildItem
Reference
Module: Microsoft.PowerShell.Management

Gets the items and child items in one or more specified locations.

Syntax
PowerShell

Get-ChildItem

[[-Path] <string[]>]

[[-Filter] <string>]

[-Include <string[]>]

[-Exclude <string[]>]

[-Recurse]

[-Depth <uint32>]

[-Force]

[-Name]

[-UseTransaction]

[-Attributes <FlagsExpression[FileAttributes]>]

[-Directory]

[-File]

[-Hidden]

[-ReadOnly]

[-System]

[<CommonParameters>]

PowerShell

Get-ChildItem

[[-Filter] <string>]

-LiteralPath <string[]>

[-Include <string[]>]

[-Exclude <string[]>]

[-Recurse]

[-Depth <uint32>]

[-Force]

[-Name]

[-UseTransaction]

[-Attributes <FlagsExpression[FileAttributes]>]

[-Directory]

[-File]

[-Hidden]

[-ReadOnly]

[-System]

[<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 and use the Depth parameter
to limit the number
of levels to recurse.

Get-ChildItem doesn't display empty directories. When a Get-ChildItem command


includes the
Depth or Recurse parameters, empty directories aren't included in the
output.

Locations are exposed to Get-ChildItem by PowerShell providers. A location can be a


file system
directory, registry hive, or a certificate store. For more information, see
about_Providers.

Examples

Example 1: Get child items from a file system directory


This example gets the child items from a file system directory. The filenames and
subdirectory
names are displayed. For empty locations, the command doesn't return any
output and returns to the
PowerShell prompt.

The Get-ChildItem cmdlet uses the Path parameter to specify the directory C:\Test .
Get-ChildItem displays the files and directories in the PowerShell console.

PowerShell

Get-ChildItem -Path C:\Test

Directory: C:\Test

Mode LastWriteTime Length Name

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

d----- 2/15/2019 08:29 Logs

-a---- 2/13/2019 08:55 26 anotherfile.txt

-a---- 2/12/2019 15:40 118014 Command.txt

-a---- 2/1/2019 08:43 183 CreateTestFile.ps1

-ar--- 2/12/2019 14:31 27 ReadOnlyFile.txt

By default Get-ChildItem lists the mode (Attributes), LastWriteTime, file size


(Length),
and the Name of the item. The letters in the Mode property can be interpreted
as
follows:
l (link)

d (directory)
a (archive)

r (read-only)
h (hidden)

s (system).

For more information about the mode flags, see


about_Filesystem_Provider.

Example 2: Get child item names in a directory


This example lists only the names of items in a directory.

The Get-ChildItem cmdlet uses the Path parameter to specify the directory C:\Test .
The
Name parameter returns only the file or directory names from the specified path.
The names
returned are relative to the value of the Path parameter.

PowerShell

Get-ChildItem -Path C:\Test -Name

Logs

anotherfile.txt

Command.txt

CreateTestFile.ps1

ReadOnlyFile.txt

Example 3: Get child items in the current directory and


subdirectories
This example displays .txt files that are located in the current directory and its
subdirectories.

PowerShell

Get-ChildItem -Path C:\Test\*.txt -Recurse -Force

Directory: C:\Test\Logs\Adirectory

Mode LastWriteTime Length Name

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

-a---- 2/12/2019 16:16 20 Afile4.txt

-a-h-- 2/12/2019 15:52 22 hiddenfile.txt

-a---- 2/13/2019 13:26 20 LogFile4.txt

Directory: C:\Test\Logs\Backup

Mode LastWriteTime Length Name

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

-a---- 2/12/2019 16:16 20 ATextFile.txt

-a---- 2/12/2019 15:50 20 LogFile3.txt

Directory: C:\Test\Logs

Mode LastWriteTime Length Name

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

-a---- 2/12/2019 16:16 20 Afile.txt

-a-h-- 2/12/2019 15:52 22 hiddenfile.txt

-a---- 2/13/2019 13:26 20 LogFile1.txt

Directory: C:\Test

Mode LastWriteTime Length Name

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

-a---- 2/13/2019 08:55 26 anotherfile.txt

-a---- 2/12/2019 15:40 118014 Command.txt

-a-h-- 2/12/2019 15:52 22 hiddenfile.txt

-ar--- 2/12/2019 14:31 27 ReadOnlyFile.txt

The Get-ChildItem cmdlet uses the Path parameter to specify C:\Test\*.txt . Path uses
the
asterisk ( * ) wildcard to specify all files with the filename extension .txt . The
Recurse
parameter searches the Path directory its subdirectories, as shown in the
Directory:
headings. The Force parameter displays hidden files such as hiddenfile.txt
that have a mode of
h.

Example 4: Get child items using the Include parameter


In this example Get-ChildItem uses the Include parameter to find specific items from
the
directory specified by the Path parameter.

PowerShell

# When using the -Include parameter, if you don't include an asterisk in the
path

# the command returns no output.

Get-ChildItem -Path C:\Test\ -Include *.txt

Get-ChildItem -Path C:\Test\* -Include *.txt

Directory: C:\Test

Mode LastWriteTime Length Name

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

-a---- 2/13/2019 08:55 26 anotherfile.txt

-a---- 2/12/2019 15:40 118014 Command.txt

-ar--- 2/12/2019 14:31 27 ReadOnlyFile.txt

The Get-ChildItem cmdlet uses the Path parameter to specify the directory C:\Test. The
Path parameter includes a trailing asterisk ( * ) wildcard to specify the directory's
contents.
The Include parameter uses an asterisk ( * ) wildcard to specify all files with the
file name
extension .txt.

When the Include parameter is used, the Path parameter needs a trailing asterisk ( * )
wildcard to specify the directory's contents. For example, -Path C:\Test\* .

If the Recurse parameter is added to the command, the trailing asterisk ( * ) in the
Path
parameter is optional. The Recurse parameter gets items from the Path
directory and its
subdirectories. For example, -Path C:\Test\ -Recurse -Include
*.txt

If a trailing asterisk ( * ) isn't included in the Path parameter, the command doesn't
return
any output and returns to the PowerShell prompt. For example, -Path
C:\Test\ .

Example 5: Get child items using the Exclude parameter


The example's output shows the contents of the directory C:\Test\Logs. The output is a
reference
for the other commands that use the Exclude and Recurse parameters.

PowerShell

Get-ChildItem -Path C:\Test\Logs

Directory: C:\Test\Logs

Mode LastWriteTime Length Name

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

d----- 2/15/2019 13:21 Adirectory

d----- 2/15/2019 08:28 AnEmptyDirectory

d----- 2/15/2019 13:21 Backup

-a---- 2/12/2019 16:16 20 Afile.txt

-a---- 2/13/2019 13:26 20 LogFile1.txt

-a---- 2/12/2019 16:24 23 systemlog1.log

Get-ChildItem -Path C:\Test\Logs\* -Exclude A*

Directory: C:\Test\Logs

Mode LastWriteTime Length Name

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

d----- 2/15/2019 13:21 Backup

-a---- 2/13/2019 13:26 20 LogFile1.txt

-a---- 2/12/2019 16:24 23 systemlog1.log

The Get-ChildItem cmdlet uses the Path parameter to specify the directory
C:\Test\Logs . The
Exclude parameter uses the asterisk ( * ) wildcard to specify any files
or directories that
begin with A or a are excluded from the output.

When the Exclude parameter is used, a trailing asterisk ( * ) in the Path parameter is
optional. For example, -Path C:\Test\Logs or -Path C:\Test\Logs\* .

If a trailing asterisk ( * ) isn't included in the Path parameter, the contents of the
Path parameter are displayed. The exceptions are filenames or subdirectory names
that match
the Exclude parameter's value.
If a trailing asterisk ( * ) is included in the Path parameter, the command recurses
into the
Path parameter's subdirectories. The exceptions are filenames or
subdirectory names that match
the Exclude parameter's value.
If the Recurse parameter is added to the command, the recursion output is the
same whether or
not the Path parameter includes a trailing asterisk ( * ).

Example 6: Get the registry keys from a registry hive


This example gets all the registry keys from HKEY_LOCAL_MACHINE\HARDWARE .

Get-ChildItem uses the Path parameter to specify the registry key HKLM:\HARDWARE . The

hive's
path and top level of registry keys are displayed in the PowerShell console.

For more information, see


about_Registry_Provider.

PowerShell

Get-ChildItem -Path HKLM:\HARDWARE

Hive: HKEY_LOCAL_MACHINE\HARDWARE

Name Property

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

ACPI

DESCRIPTION

DEVICEMAP

RESOURCEMAP

UEFI

Get-ChildItem -Path HKLM:\HARDWARE -Exclude D*

Hive: HKEY_LOCAL_MACHINE\HARDWARE
Name Property

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

ACPI

RESOURCEMAP

The first command shows the contents of the HKLM:\HARDWARE registry key. The Exclude
parameter
tells Get-ChildItem not to return any subkeys that start with D* . Currently,
the Exclude
parameter only works on subkeys, not item properties.

Example 7: Get all certificates with code-signing authority


This example gets each certificate in the PowerShell Cert: drive that has code-signing
authority.

The Get-ChildItem cmdlet uses the Path parameter to specify the Cert: provider. The
Recurse parameter searches the directory specified by Path and its subdirectories. The
CodeSigningCert parameter gets only certificates that have code-signing authority.

PowerShell

Get-ChildItem -Path Cert:\* -Recurse -CodeSigningCert

For more information about the Certificate provider and the Cert: drive,
see
about_Certificate_Provider.

Example 8: Get items using the Depth parameter


This example displays the items in a directory and its subdirectories. The Depth
parameter
determines the number of subdirectory levels to include in the recursion.
Empty directories are
excluded from the output.

PowerShell

Get-ChildItem -Path C:\Parent -Depth 2

Directory: C:\Parent

Mode LastWriteTime Length Name

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

d----- 2/14/2019 10:24 SubDir_Level1

-a---- 2/13/2019 08:55 26 file.txt

Directory: C:\Parent\SubDir_Level1

Mode LastWriteTime Length Name

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

d----- 2/14/2019 10:24 SubDir_Level2

-a---- 2/13/2019 08:55 26 file.txt

Directory: C:\Parent\SubDir_Level1\SubDir_Level2

Mode LastWriteTime Length Name

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

d----- 2/14/2019 10:22 SubDir_Level3

-a---- 2/13/2019 08:55 26 file.txt

The Get-ChildItem cmdlet uses the Path parameter to specify C:\Parent. The Depth
parameter specifies two levels of recursion. Get-ChildItem displays the contents of the
directory
specified by the Path parameter and the two levels of subdirectories.

Example 9 - Get the link target for a junction point


The dir command in the Windows Command Shell shows the target location of a
filesystem junction
point. In PowerShell, this information is available from the Target
property of the filesystem
object returned by Get-ChildItem .

PowerShell

PS D:\> New-Item -ItemType Junction -Name tmp -Target $env:TEMP

PS D:\> Get-ChildItem | select name,*target

Name Target

---- ------

tmp {C:\Users\user1\AppData\Local\Temp}

Parameters
-Attributes

Gets files and folders with the specified attributes. This parameter supports all
attributes and
lets you specify complex combinations of attributes.

For example, to get non-system files (not directories) that are encrypted or
compressed, type:

Get-ChildItem -Attributes !Directory+!System+Encrypted,


!Directory+!System+Compressed
To find files and folders with commonly used attributes, use the Attributes
parameter. Or, the
parameters Directory, File, Hidden, ReadOnly, and System.

The Attributes parameter supports the following properties:

Archive
Compressed
Device
Directory
Encrypted
Hidden
IntegrityStream
Normal
NoScrubData
NotContentIndexed
Offline
ReadOnly
ReparsePoint
SparseFile
System
Temporary

For a description of these attributes, see the FileAttributes Enumeration.

To combine attributes, use the following operators:

! (NOT)

+ (AND)

, (OR)

Don't use spaces between an operator and its attribute. Spaces are accepted after
commas.

For common attributes, use the following abbreviations:

D (Directory)

H (Hidden)
R (Read-only)

S (System)

Type: FlagsExpression<T>[FileAttributes]

Accepted values: Archive, Compressed, Device, Directory, Encrypted, Hidden,


IntegrityStream, Normal, NoScrubData, NotContentIndexed,
Offline, ReadOnly, ReparsePoint, SparseFile, System,
Temporary

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Depth

This parameter was added in PowerShell 5.0 and enables you to control the depth of
recursion. By
default, Get-ChildItem displays the contents of the parent directory.
The Depth parameter
determines the number of subdirectory levels that are
included in the recursion and displays the
contents.

For example, Depth 2 includes the Path parameter's directory, first level of
subdirectories,
and second level of subdirectories. By default directory names and
filenames are included in the
output.

7 Note

On a Windows computer from PowerShell or cmd.exe, you can display a


graphical view of a
directory structure with the tree.com command.

Type: UInt32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Directory

To get a list of directories, use the Directory parameter or the Attributes parameter
with
the Directory property. You can use the Recurse parameter with Directory.

Type: SwitchParameter

Aliases: ad, d
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Exclude

Specifies an array of one or more string patterns to be matched as the cmdlet gets
child items. Any
matching item is excluded from the output. Enter a path element or
pattern, such as *.txt or A* .
Wildcard characters are accepted.

A trailing asterisk ( * ) in the Path parameter is optional. For example, -Path


C:\Test\Logs
or -Path C:\Test\Logs\* . If a trailing asterisk ( * ) is included, the

command recurses into the


Path parameter's subdirectories. Without the asterisk
( * ), the contents of the Path
parameter are displayed. More details are included in
Example 5 and the Notes section.

The Include and Exclude parameters can be used together. However, the exclusions
are applied
after the inclusions, which can affect the final output.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-File

To get a list of files, use the File parameter. You can use the Recurse parameter with
File.

Type: SwitchParameter

Aliases: af

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-Filter

Specifies a filter to qualify the Path parameter. The


FileSystem provider is the only
installed PowerShell provider that supports filters. Filters are more efficient than
other
parameters. The provider applies filter when the cmdlet gets the objects rather
than having
PowerShell filter the objects after they're retrieved. The filter string is
passed to the .NET API
to enumerate files. The API only supports * and ? wildcards.

Type: String

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Force

Allows the cmdlet to get items that otherwise can't be accessed by the user, such as
hidden or
system files. The Force parameter doesn't override security restrictions.
Implementation varies
among providers. For more information, see
about_Providers.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Hidden

To get only hidden items, use the Hidden parameter or the Attributes parameter
with the
Hidden property. By default, Get-ChildItem doesn't display hidden items.
Use the Force
parameter to get hidden items.

Type: SwitchParameter

Aliases: ah, h

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Include

Specifies an array of one or more string patterns to be matched as the cmdlet gets
child items. Any
matching item is included in the output. Enter a path element or
pattern, such as "*.txt" .
Wildcard characters 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.

The Include and Exclude parameters can be used together. However, the exclusions
are applied
after the inclusions, which can affect the final output.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-LiteralPath

Specifies a path to one or more locations. The value of LiteralPath is used exactly as
it's
typed. No characters are interpreted as wildcards. If the path includes escape
characters, enclose
it in single quotation marks. Single quotation marks tell
PowerShell to not interpret any characters
as escape sequences.

For more information, see about_Quoting_Rules.

Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True


Accept wildcard characters: False

-Name

Gets only the names of the items in the location. The output is a string object that
can be sent
down the pipeline to other commands. The names returned are relative
to the value of the Path
parameter.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Path

Specifies a path to one or more locations. Wildcards are accepted. The default
location is the
current directory ( . ).

Type: String[]

Position: 0

Default value: Current directory

Accept pipeline input: True

Accept wildcard characters: True

-ReadOnly

To get only read-only items, use the ReadOnly parameter or the Attributes
parameter
ReadOnly property.

Type: SwitchParameter

Aliases: ar

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-Recurse

Gets the items in the specified locations and in all child items of the locations.

Type: SwitchParameter

Aliases: s

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-System

Gets only system files and directories. To get only system files and folders, use the
System
parameter or Attributes parameter System property.

Type: SwitchParameter

Aliases: as

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.

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False


Accept wildcard characters: False

Inputs
String

You can pipe a string that contains a path to this cmdlet.

Outputs
AliasInfo

The cmdlet outputs this type when accessing the Alias: drive.

X509StoreLocation

X509Store

X509Certificate2

The cmdlet outputs these types when accessing the Cert: drive.

DictionaryEntry

The cmdlet outputs this type when accessing the Env: drive.

DirectoryInfo

FileInfo

The cmdlet outputs these types when accessing the Filesystem drives.

FunctionInfo

FilterInfo

The cmdlet outputs these types when accessing the Function: drives.

RegistryKey

The cmdlet outputs this type when accessing the Registry drives.

PSVariable

The cmdlet outputs this type when accessing the Variable: drives.
Microsoft.WSMan.Management.WSManConfigContainerElement

Microsoft.WSMan.Management.WSManConfigLeafElement

The cmdlet outputs these types when accessing the WSMan: drives.

String

When you use the Name parameter, this cmdlet returns the object names as strings.

Notes
Windows PowerShell includes the following aliases for Get-ChildItem :

ls

dir
gci

Get-ChildItem doesn't get hidden items by default. To get hidden items, use the Force
parameter.

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.

Related Links
about_Certificate_Provider
about_Providers
about_Quoting_Rules
about_Registry_Provider
ForEach-Object
Get-Alias
Get-Item
Get-Location
Get-Process
Get-PSProvider
Split-Path
Get-Clipboard
Reference
Module: Microsoft.PowerShell.Management

Gets the current Windows clipboard entry.

Syntax
PowerShell

Get-Clipboard

[-Format <ClipboardFormat>]

[-TextFormatType <TextDataFormat>]

[-Raw]

[<CommonParameters>]

Description
The Get-Clipboard cmdlet gets the current Windows clipboard entry. Multiple lines of
text are
returned as an array of strings similar to Get-Content .

Examples

Example 1: Get the content of the clipboard and display it


to the command-line
In this example we have right-clicked on an image in a browser and chose the Copy
action. The
following command displays the link, as a URL, of the image that is stored in
the clipboard.

PowerShell

Get-Clipboard

https://en.wikipedia.org/wiki/PowerShell

Example 2: Get the content of the clipboard in a specific


format
In this example we copied files to the clipboard in Windows Explorerby selecting them
and pressing
Ctrl-C . Using the following command, you can access the contents of the
clipboard as a
list of files:

PowerShell

Get-Clipboard -Format FileDropList

Directory: C:\Git\PS-Docs\PowerShell-Docs\wmf

Mode LastWriteTime Length Name

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

-a---- 5/7/2019 1:11 PM 10010 TOC.yml

-a---- 11/18/2016 10:10 AM 53 md.style

-a---- 5/6/2019 9:32 AM 4177 overview.md

-a---- 6/28/2018 2:28 PM 345 README.md

Parameters
-Format

Specifies the type, or format, of the clipboard. The acceptable values for this
parameter are:

Text
FileDropList
Image
Audio

Type: ClipboardFormat

Accepted values: Text, FileDropList, Image, Audio

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Raw

Gets the entire contents of the clipboard. Multiline text is returned as a single
multiline string
rather than an array of strings.
Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-TextFormatType

Specifies the text data format type of the clipboard. The acceptable values for this
parameter are:

Text
UnicodeText
Rtf
Html
CommaSeparatedValue

Type: TextDataFormat

Accepted values: Text, UnicodeText, Rtf, Html, CommaSeparatedValue

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
String

FileInfo

Stream
Image

Notes
Windows PowerShell includes the following aliases for Get-Clipboard :

gcb

Related Links
Set-Clipboard
Get-ComputerInfo
Reference
Module: Microsoft.PowerShell.Management

Gets a consolidated object of system and operating system properties.

Syntax
PowerShell

Get-ComputerInfo

[[-Property] <String[]>]

[<CommonParameters>]

Description
The Get-ComputerInfo cmdlet gets a consolidated object of system and operating
system properties.
This cmdlet was introduced in Windows PowerShell 5.1.

Examples

Example 1: Get all computer properties


This command gets all system and operating system properties from the computer.

PowerShell

Get-ComputerInfo

Example 2: Get all computer version properties


This command gets all version properties from the computer.

PowerShell

Get-ComputerInfo -Property "*version"

WindowsCurrentVersion : 6.3

WindowsVersion : 2009

BiosBIOSVersion : {LENOVO - 1380, N1FET64W (1.38 ),


Lenovo - 1380}

BiosEmbeddedControllerMajorVersion : 1

BiosEmbeddedControllerMinorVersion : 17

BiosSMBIOSBIOSVersion : N1FET64W (1.38 )

BiosSMBIOSMajorVersion : 2

BiosSMBIOSMinorVersion : 8

BiosSystemBiosMajorVersion : 1

BiosSystemBiosMinorVersion : 38

BiosVersion : LENOVO - 1380

OsVersion : 10.0.19043

OsCSDVersion :

OsServicePackMajorVersion : 0

OsServicePackMinorVersion : 0

Parameters
-Property

Specifies, as a string array, the computer properties in which this cmdlet displays.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

Inputs
String[]

You can pipe a string containing the name of a property to this cmdlet.

Outputs
Microsoft.PowerShell.Management.ComputerInfo

This cmdlet returns a ComputerInfo object.

Notes
Windows PowerShell includes the following aliases for Get-ComputerInfo :

gin
Get-ComputerRestorePoint
Reference
Module: Microsoft.PowerShell.Management

Gets the restore points on the local computer.

Syntax
PowerShell

Get-ComputerRestorePoint

[[-RestorePoint] <Int32[]>]

[<CommonParameters>]

PowerShell

Get-ComputerRestorePoint

-LastStatus

[<CommonParameters>]

Description
The Get-ComputerRestorePoint cmdlet gets the local computer's system restore points.
And, it can
display the status of the most recent attempt to restore the computer.

You can use the information from Get-ComputerRestorePoint to select a restore point.
For example,
use a sequence number to identify a restore point for the Restore-
Computer cmdlet.

System restore points and the Get-ComputerRestorePoint cmdlet are supported only on
client
operating systems such as Windows 10.

Examples

Example 1: Get all system restore points


In this example, Get-ComputerRestorePoint gets all the local computer's system restore
points.
PowerShell

Get-ComputerRestorePoint

CreationTime Description SequenceNumber


EventType RestorePointType

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


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

7/30/2019 09:17:24 Windows Update 4


BEGIN_SYSTEM_C... 17

8/5/2019 08:15:37 Installed PowerShell 7-prev... 5


BEGIN_SYSTEM_C... APPLICATION_INSTALL

8/7/2019 12:56:45 Installed PowerShell 6-x64 6


BEGIN_SYSTEM_C... APPLICATION_INSTALL

Example 2: Get specific sequence numbers


This example gets system restore points for specific sequence numbers.

PowerShell

Get-ComputerRestorePoint -RestorePoint 4, 5

CreationTime Description SequenceNumber


EventType RestorePointType

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


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

7/30/2019 09:17:24 Windows Update 4


BEGIN_SYSTEM_C... 17

8/5/2019 08:15:37 Installed PowerShell 7-prev... 5


BEGIN_SYSTEM_C... APPLICATION_INSTALL

Get-ComputerRestorePoint uses the RestorePoint parameter to specify a comma-


separated array of
sequence numbers.

Example 3: Display the status of a system restore


This example displays the status of the most recent system restore on the local
computer.

PowerShell

Get-ComputerRestorePoint -LastStatus

The last attempt to restore the computer failed.


Get-ComputerRestorePoint uses the LastStatus parameter to display the result of the

most
recent system restore.

Example 4: Use an expression to convert the


CreationTime
Get-ComputerRestorePoint outputs the CreationTime as a Windows Management

Instrumentation
(WMI) date and time string.

In this example, a variable stores an expression that converts the CreationTime string to
a
DateTime object. To view CreationTime strings before they're converted, use a
command such
as ((Get-ComputerRestorePoint).CreationTime) . For more information
about the WMI date and time
string, see CIM_DATETIME.

PowerShell

$date = @{Label="Date"; Expression={$_.ConvertToDateTime($_.CreationTime)}}

Get-ComputerRestorePoint | Select-Object -Property SequenceNumber, $date,


Description

SequenceNumber Date Description

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

4 7/30/2019 09:17:24 Windows Update

5 8/5/2019 08:15:37 Installed PowerShell 7-preview-x64

6 8/7/2019 12:56:45 Installed PowerShell 6-x64

The $date variable stores a hash table with the expression that uses the
ConvertToDateTime
method. The expression converts the CreationTime property's
value from a WMI string to a
DateTime object.

Get-ComputerRestorePoint sends the system restore point objects down the pipeline.

Select-Object
uses the Property parameter to specify the properties to display. For
each object in the
pipeline, the expression in $date converts the CreationTime and
outputs the result in the
Date property.

Example 5: Use a property to get a sequence number


This example gets a sequence number by using the SequenceNumber property and an
array index. The
output only contains the sequence number.

PowerShell

((Get-ComputerRestorePoint).SequenceNumber)[-1]

Get-ComputerRestorePoint uses the SequenceNumber property with an array index. The

array index
of -1 gets the most recent sequence number in the array.

Parameters
-LastStatus

Indicates that Get-ComputerRestorePoint gets the status of the most recent system
restore
operation.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-RestorePoint

Specifies the sequence numbers of the system restore points. You can specify either
a single
sequence number or a comma-separated array of sequence numbers.

If the RestorePoint parameter isn't specified, Get-ComputerRestorePoint returns all


the local
computer's system restore points.

Type: Int32[]

Position: 0

Default value: All restore points

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None
You can't send objects down the pipeline to Get-ComputerRestorePoint .

Outputs
ManagementObject

Get-ComputerRestorePoint returns a SystemRestore object, which is an instance of the


Windows
Management Instrumentation (WMI) SystemRestore class.

When you use the LastStatus parameter, Get-ComputerRestorePoint returns a string.

Notes
To run a Get-ComputerRestorePoint command on Windows Vista and later versions of
Windows, open
PowerShell with the Run as administrator option.

Get-ComputerRestorePoint uses the WMI SystemRestore class.

Related Links
about_Hash_Tables
about_Arrays
Checkpoint-Computer
Disable-ComputerRestore
Enable-ComputerRestore
Restart-Computer
Restore-Computer
SystemRestore
Get-Content
Reference
Module: Microsoft.PowerShell.Management

Gets the content of the item at the specified location.

Syntax
PowerShell

Get-Content

[-ReadCount <Int64>]

[-TotalCount <Int64>]

[-Tail <Int32>]

[-Path] <String[]>

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Force]

[-Credential <PSCredential>]

[-UseTransaction]

[-Delimiter <String>]

[-Wait]

[-Raw]

[-Encoding <FileSystemCmdletProviderEncoding>]

[-Stream <String>]

[<CommonParameters>]

PowerShell

Get-Content

[-ReadCount <Int64>]

[-TotalCount <Int64>]

[-Tail <Int32>]

-LiteralPath <String[]>

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Force]

[-Credential <PSCredential>]

[-UseTransaction]

[-Delimiter <String>]

[-Wait]

[-Raw]

[-Encoding <FileSystemCmdletProviderEncoding>]

[-Stream <String>]

[<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 or the content of a function. For files, the content is read
one line at a time
and returns a collection of objects, each of which represents a line of
content.

Beginning in PowerShell 3.0, Get-Content can also get a specified number of lines from
the
beginning or end of an item.

Examples

Example 1: Get the content of a text file


This example gets the content of a file in the current directory. The LineNumbers.txt file
contains 100 lines in the format, This is Line X and is used in several examples.

PowerShell

1..100 | ForEach-Object { Add-Content -Path .\LineNumbers.txt -Value "This


is line $_." }

Get-Content -Path .\LineNumbers.txt

This is Line 1

This is Line 2

...

This is line 99.

This is line 100.

The array values 1-100 are sent down the pipeline to the ForEach-Object cmdlet.
ForEach-Object
uses a script block with the Add-Content cmdlet to create the

LineNumbers.txt file. The variable


$_ represents the array values as each object is sent
down the pipeline. The Get-Content cmdlet
uses the Path parameter to specify the
LineNumbers.txt file and displays the content in the
PowerShell console.

Example 2: Limit the number of lines Get-Content returns


This command gets the first five lines of a file. The TotalCount parameter is used to gets
the
first five lines of content. This example uses the LineNumbers.txt file that was
created in
Example 1.

PowerShell
Get-Content -Path .\LineNumbers.txt -TotalCount 5

This is Line 1

This is Line 2

This is Line 3

This is Line 4

This is Line 5

Example 3: Get a specific line of content from a text file


This command gets a specific number of lines from a file and then displays only the last
line of
that content. The TotalCount parameter gets the first 25 lines of content. This
example uses the
LineNumbers.txt file that was created in Example 1.

PowerShell

(Get-Content -Path .\LineNumbers.txt -TotalCount 25)[-1]

This is Line 25

The Get-Content command is wrapped in parentheses so that the command completes


before going to
the next step. Get-Content returns an array of lines, this allows you to
add the index notation
after the parenthesis to retrieve a specific line number. In this
case, the [-1] index specifies
the last index in the returned array of 25 retrieved lines.

Example 4: Get the last line of a text file


This command gets the last line of content from a file. This example uses the
LineNumbers.txt file
that was created in Example 1.

PowerShell

Get-Item -Path .\LineNumbers.txt | Get-Content -Tail 1

This is Line 100

This example uses the Get-Item cmdlet to demonstrate that you can pipe files into the
Get-Content parameter. The Tail parameter gets the last line of the file. This method is
faster than retrieving all of the lines and using the [-1] index notation.

Example 5: Get the content of an alternate data stream


This example describes how to use the Stream parameter to get the content of an
alternate data
stream for files stored on a Windows NTFS volume. In this example, the
Set-Content cmdlet is used
to create sample content in a file named Stream.txt .

PowerShell

Set-Content -Path .\Stream.txt -Value 'This is the content of the Stream.txt


file'

# Specify a wildcard to the Stream parameter to display all streams of the


recently created file.

Get-Item -Path .\Stream.txt -Stream *

PSPath :
Microsoft.PowerShell.Core\FileSystem::C:\Test\Stream.txt::$DATA

PSParentPath : Microsoft.PowerShell.Core\FileSystem::C:\Test

PSChildName : Stream.txt::$DATA
PSDrive : C

PSProvider : Microsoft.PowerShell.Core\FileSystem

PSIsContainer : False

FileName : C:\Test\Stream.txt

Stream : :$DATA

Length : 44

# Retrieve the content of the primary, or $DATA stream.

Get-Content -Path .\Stream.txt -Stream $DATA

This is the content of the Stream.txt file

# Use the Stream parameter of Add-Content to create a new Stream containing


sample content.

Add-Content -Path .\Stream.txt -Stream NewStream -Value 'Added a stream


named NewStream to Stream.txt'

# Use Get-Item to verify the stream was created.

Get-Item -Path .\Stream.txt -Stream *

PSPath :
Microsoft.PowerShell.Core\FileSystem::C:\Test\Stream.txt::$DATA

PSParentPath : Microsoft.PowerShell.Core\FileSystem::C:\Test

PSChildName : Stream.txt::$DATA
PSDrive : C

PSProvider : Microsoft.PowerShell.Core\FileSystem

PSIsContainer : False

FileName : C:\Test\Stream.txt

Stream : :$DATA

Length : 44

PSPath :
Microsoft.PowerShell.Core\FileSystem::C:\Test\Stream.txt:NewStream

PSParentPath : Microsoft.PowerShell.Core\FileSystem::C:\Test

PSChildName : Stream.txt:NewStream

PSDrive : C

PSProvider : Microsoft.PowerShell.Core\FileSystem

PSIsContainer : False

FileName : C:\Test\Stream.txt

Stream : NewStream

Length : 46

# Retrieve the content of your newly created Stream.

Get-Content -Path .\Stream.txt -Stream NewStream

Added a stream named NewStream to Stream.txt

The Stream parameter is a dynamic parameter of the


FileSystem provider.
By default
Get-Content only retrieves data from the default, or :$DATA stream. Streams can be

used to store hidden data such as attributes, security settings, or other data.

Example 6: Get raw content


The commands in this example get the contents of a file as one string, instead of an
array of
strings. By default, without the Raw dynamic parameter, content is returned as
an array of
newline-delimited strings. This example uses the LineNumbers.txt file that
was created in Example
1.

PowerShell

$raw = Get-Content -Path .\LineNumbers.txt -Raw

$lines = Get-Content -Path .\LineNumbers.txt

Write-Host "Raw contains $($raw.Count) lines."

Write-Host "Lines contains $($lines.Count) lines."

Raw contains 1 lines.

Lines contains 100 lines.

Example 7: Use Filters with Get-Content


You can specify a filter to the Get-Content cmdlet. When using filters to qualify the Path
parameter, you need to include a trailing asterisk ( * ) to indicate the contents of the
path.

The following command gets the content of all *.log files in the C:\Temp directory.

PowerShell

Get-Content -Path C:\Temp\* -Filter *.log

Example 8: Get file contents as a byte array


This example demonstrates how to get the contents of a file as a [byte[]] as a single
object.

PowerShell

$byteArray = Get-Content -Path C:\temp\test.txt -Encoding Byte -Raw

Get-Member -InputObject $bytearray

TypeName: System.Byte[]

Name MemberType Definition

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

Count AliasProperty Count = Length

Add Method int IList.Add(System.Object value)

The first command uses the Encoding parameter to get the stream of bytes from the
file.
The Raw parameter ensures that the bytes are returned as a [System.Byte[]] . If the
Raw
parameter was absent, the return value is a stream of bytes, which is interpreted by
PowerShell as [System.Object[]] .

Parameters
-Credential

7 Note

This parameter is not supported by any providers installed with PowerShell.


To
impersonate another user, or elevate your credentials when running this cmdlet,
use Invoke-Command.

Type: PSCredential

Position: Named

Default value: Current user

Accept pipeline input: True

Accept wildcard characters: False

-Delimiter

Specifies the delimiter that Get-Content uses to divide the file into objects while it
reads. The
default is \n , the end-of-line character. When reading a text file, Get-
Content returns a
collection of string objects, each of which ends with an end-of-line

character. When you enter a


delimiter that does not exist in the file, Get-Content
returns the entire file as a single,
undelimited object.

You can use this parameter to split a large file into smaller files by specifying a file
separator,
as the delimiter. The delimiter is preserved (not discarded) and becomes
the last item in each file
section.

Delimiter is a dynamic parameter that the FileSystem provider adds to the Get-
Content
cmdlet. This parameter works only in file system drives.

7 Note

Currently, when the value of the Delimiter parameter is an empty string, Get-
Content does
not return anything. This is a known issue. To force Get-Content to

return the entire file as


a single, undelimited string. Enter a value that does not
exist in the file.

Type: String

Position: Named

Default value: End-of-line character

Accept pipeline input: False

Accept wildcard characters: False

-Encoding

Specifies the type of encoding for the target file. The default value is Default .

The acceptable values for this parameter are as follows:

Ascii Uses ASCII (7-bit) character set.


BigEndianUnicode Uses UTF-16 with the big-endian byte order.

BigEndianUTF32 Uses UTF-32 with the big-endian byte order.


Byte Encodes a set of characters into a sequence of bytes.

Default Uses the encoding that corresponds to the system's active code page

(usually ANSI).
Oem Uses the encoding that corresponds to the system's current OEM code

page.
String Same as Unicode .
Unicode Uses UTF-16 with the little-endian byte order.

Unknown Same as Unicode .


UTF7 Uses UTF-7.

UTF8 Uses UTF-8.


UTF32 Uses UTF-32 with the little-endian byte order.

Encoding is a dynamic parameter that the FileSystem provider adds to the Get-
Content cmdlet.
This parameter works only in file system drives.

When reading from and writing to binary files, use a value of Byte for the Encoding
dynamic
parameter and a value of 0 for the ReadCount parameter. A ReadCount
value of 0 reads the
entire file in a single read operation and converts it into a single
object (PSObject). The default
ReadCount value, 1, reads one byte in each read
operation and converts each byte into a separate
object, which causes errors when
you use the Set-Content cmdlet to write the bytes to a file.

Type: FileSystemCmdletProviderEncoding

Accepted values: ASCII, BigEndianUnicode, BigEndianUTF32, Byte, Default, OEM,


String, Unicode, Unknown, UTF7, UTF8, UTF32

Position: Named

Default value: Default

Accept pipeline input: False

Accept wildcard characters: False

-Exclude

Specifies, as a string array, an item or items that this cmdlet excludes in the
operation.
The value of this parameter qualifies the Path parameter.

Enter a path element or pattern, such as *.txt .


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

Type: String[]

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: True

-Filter

Specifies a filter to qualify the Path parameter. The FileSystem


provider is the only
installed PowerShell provider that supports the use of filters. You can find
the syntax
for the FileSystem filter language in about_Wildcards.
Filters are more efficient than
other parameters, because the provider applies them when the cmdlet
gets the
objects rather than having PowerShell filter the objects after they are retrieved.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Force

Force will override a read-only attribute or create directories to complete a file path.
The
Force parameter does not attempt to change file permissions or override
security restrictions.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Include

Specifies, as a string array, an item or items that this cmdlet includes in the
operation. The value
of this parameter qualifies the Path parameter. Enter a path
element or pattern, such as
"*.txt" . Wildcard characters 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.
Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-LiteralPath

Specifies a path to one or more locations. 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
PowerShell not to interpret any characters
as escape sequences.

For more information, see about_Quoting_Rules.

Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Path

Specifies the path to an item where Get-Content gets the content. Wildcard
characters 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.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-Raw
Ignores newline characters and returns the entire contents of a file in one string with
the newlines
preserved. By default, newline characters in a file are used as delimiters
to separate the input
into an array of strings. This parameter was introduced in
PowerShell 3.0.

Raw is a dynamic parameter that the FileSystem provider adds to the Get-Content
cmdlet
This parameter works only in file system drives.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ReadCount

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

Type: Int64

Position: Named

Default value: 1

Accept pipeline input: True

Accept wildcard characters: False

-Stream

Gets the contents of the specified alternate NTFS file stream from the file. Enter the
stream name.
Wildcards are not supported.

Stream is a dynamic parameter that the FileSystem provider adds to the Get-
Content cmdlet.
This parameter works only in file system drives on Windows systems.
This parameter was introduced in
Windows PowerShell 3.0.
Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Tail

Specifies the number of lines from the end of a file or other item. You can use the
Tail
parameter name or its alias, Last. This parameter was introduced in PowerShell
3.0.

Type: Int32

Aliases: Last

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-TotalCount

Specifies the number of lines from the beginning of a file or other item. The default
is -1 (all
lines).

You can use the TotalCount parameter name or its aliases, First or Head.

Type: Int64

Aliases: First, Head

Position: Named

Default value: -1

Accept pipeline input: True

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.

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Wait

Keeps the file open after all existing lines have been output. While waiting, Get-
Content checks
the file once each second and outputs new lines if present. You can
interrupt Wait by pressing
CTRL+C. Waiting also ends if the file gets deleted, in
which case a non-terminating error is
reported.

Wait is a dynamic parameter that the FileSystem provider adds to the Get-Content
cmdlet. This
parameter works only in file system drives. Wait cannot be combined
with Raw.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
Int64

You can pipe the read count or total count to this cmdlet.

String[]

You can pipe paths to this cmdlet.

PSCredential
You can pipe credentials to this cmdlet.

Outputs
Byte

When you use the AsByteStream parameter, this cmdlet returns the content as bytes.

String

By default, this cmdlet returns the content as an array of strings, one per line. When you
use the
Raw parameter, it returns a single string containing every line in the file.

Notes
Windows PowerShell includes the following aliases for Get-Content :

cat

gc
type

The Get-Content cmdlet is designed to work with the data exposed by any provider. To
get the
providers in your session, use the Get-PSProvider cmdlet. For more information,
see
about_Providers.

Related Links
about_Automatic_Variables
about_Providers
Add-Content
Clear-Content
ForEach-Object
Get-PSProvider
Set-Content
Get-ControlPanelItem
Reference
Module: Microsoft.PowerShell.Management

Gets control panel items.

Syntax
PowerShell

Get-ControlPanelItem

[[-Name] <String[]>]

[-Category <String[]>]

[<CommonParameters>]

PowerShell

Get-ControlPanelItem

-CanonicalName <String[]>

[-Category <String[]>]

[<CommonParameters>]

Description
The Get-ControlPanelItem cmdlet gets control panel items on the local computer. You
can use it
to find control panel items by name, category, or description, even on systems
that do not have a
user interface.

This cmdlet gets only the control panel items that can be opened on the system. On
computers that do
not have Control Panel or File Explorer, this cmdlet gets only control
panel items that can open
without these components.

This cmdlet was introduced in Windows PowerShell 3.0. It works only on Windows 8 and
Windows Server
2012 and newer.

Examples

Example 1: Get all control panel items


This command gets all control panel items on the local computer.
PowerShell

Get-ControlPanelItem

Name CanonicalName Category


Description

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


-----------

Action Center Microsoft.ActionCenter {System and


Security} Review recent messages and...

Administrative Tools Microsoft.AdministrativeTools {System and


Security} Configure administrative s...

AutoPlay Microsoft.AutoPlay {Hardware}


Change default settings fo...

BitLocker Drive Encryption Microsoft.BitLockerDriveEn... {System and


Security} Protect your computer usin...

Color Management Microsoft.ColorManagement {All Control


Panel Items} Change advanced color mana...

Credential Manager Microsoft.CredentialManager {User Accounts}


Manage your Windows Creden...

Date and Time Microsoft.DateAndTime {Clock,


Language, and Region} Set the date, time, and ti...

...

Example 2: Get control panel items by name


This example gets control panel items that have Program or App in their names.

PowerShell

Get-ControlPanelItem -Name "*Program*", "*App*"

Example 3: Get control panel items by category


This command gets all control panel items in categories that have Security in their
names.

PowerShell

Get-ControlPanelItem -Category "*Security*"

Example 4: Open a control panel item


This example opens the Windows Firewall control panel item on the local computer.
PowerShell

Get-ControlPanelItem -Name "Windows Firewall" | Show-ControlPanelItem

The Get-ControlPanelItem cmdlet gets the control panel item. The Show-
ControlPanelItem cmdlet
opens it.

Example 5: Get control panel items on a remote computer


This example gets the BitLocker Drive Encryption control panel item on the Server01
remote computer.
The Invoke-Command cmdlet runs the Get-ControlPanelItem cmdlet
remotely.

PowerShell

Invoke-Command -ComputerName "Server01" {Get-ControlPanelItem -Name


"BitLocker*" }

Example 6: Search the descriptions of control panel items


This example searches the Description property of the control panel items to get only
those that
contain the name Device.

PowerShell

Get-ControlPanelItem | Where-Object {$_.Description -like "*Device*"}

Name CanonicalName Category


Description

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


-

AutoPlay Microsoft.AutoPlay {Hardware} Change


default settings fo...

Devices and Printers Microsoft.DevicesAndPrinters {Hardware} View and


manage devices, p...

Sound Microsoft.Sound {Hardware} Configure


your audio devic...

The Get-ControlPanelItem cmdlet gets all control panel items. The Where-Object cmdlet
filters
the items by the value of the Description property.

Parameters
-CanonicalName

Specifies, as a string array, the control panel items by their canonical names or name
patterns that
this cmdlet gets. Wildcards are permitted. If you enter multiple names,
this cmdlet gets control
panel items that match any of the names, as though the
items in the name list were separated by an
"or" operator.

By default, this cmdlet gets all control panel items in the system.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Category

Specifies, as a string array, the categories of the control panel items in the specified
categories
that this cmdlet gets. Enter a category name or name pattern. Wildcards
are permitted. If you enter
multiple names, this cmdlet gets control panel items that
match any of the names, as though the
items in the name list were separated by an
"or" operator. By default, this cmdlet gets all control
panel items in the system.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Name

Specifies, as a string array, the names or name patterns of the control panel that this
cmdlet gets.
Wildcards are permitted. You can also pipe a name or name pattern to
this cmdlet.

Type: String[]

Position: 0
Default value: None

Accept pipeline input: True

Accept wildcard characters: True

Inputs
String

You can pipe a name or name pattern to this cmdlet.

Outputs
ControlPanelItem

This cmdlet gets control panel items on the local computer.

Related Links
Show-ControlPanelItem
Get-EventLog
Reference
Module: Microsoft.PowerShell.Management

Gets the events in an event log, or a list of the event logs, on the local computer or
remote
computers.

Syntax
PowerShell

Get-EventLog

[-LogName] <String>

[-ComputerName <String[]>]

[-Newest <Int32>]

[-After <DateTime>]

[-Before <DateTime>]

[-UserName <String[]>]

[[-InstanceId] <Int64[]>]

[-Index <Int32[]>]

[-EntryType <String[]>]

[-Source <String[]>]

[-Message <String>]

[-AsBaseObject]

[<CommonParameters>]

PowerShell

Get-EventLog

[-ComputerName <String[]>]

[-List]

[-AsString]

[<CommonParameters>]

Description
The Get-EventLog cmdlet gets events and event logs from local and remote computers.
By default,
Get-EventLog gets logs from the local computer. To get logs from remote
computers, use the
ComputerName parameter.

You can use the Get-EventLog parameters and property values to search for events. The
cmdlet gets
events that match the specified property values.
PowerShell cmdlets that contain the EventLog noun work only on Windows classic event
logs such as
Application, System, or Security. To get logs that use the Windows Event
Log technology in Windows
Vista and later Windows versions, use Get-WinEvent .

7 Note

Get-EventLog uses a Win32 API that is deprecated. The results may not be accurate.

Use the
Get-WinEvent cmdlet instead.

Examples

Example 1: Get event logs on the local computer


This example displays the list of event logs that are available on the local computer. The
names in
the Log column are used with the LogName parameter to specify which log is
searched for events.

PowerShell

Get-EventLog -List

Max(K) Retain OverflowAction Entries Log

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

15,168 0 OverwriteAsNeeded 20,792 Application

15,168 0 OverwriteAsNeeded 12,559 System

15,360 0 OverwriteAsNeeded 11,173 Windows PowerShell

The Get-EventLog cmdlet uses the List parameter to display the available logs.

Example 2: Get recent entries from an event log on the


local computer
This example gets recent entries from the System event log.

PowerShell

Get-EventLog -LogName System -Newest 5

Index Time EntryType Source InstanceID Message

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

13820 Jan 17 19:16 Error DCOM 10016 The


description for Event...

13819 Jan 17 19:08 Error DCOM 10016 The


description for Event...

13818 Jan 17 19:06 Information Service Control... 1073748864 The


start type of the Back...

13817 Jan 17 19:05 Error DCOM 10016 The


description for Event...

13815 Jan 17 19:03 Information Microsoft-Windows... 35 The time


service is now sync...

The Get-EventLog cmdlet uses the LogName parameter to specify the System event log.
The
Newest parameter returns the five most recent events.

Example 3: Find all sources for a specific number of


entries in an event log
This example shows how to find all of the sources that are included in the 1000 most
recent entries
in the System event log.

PowerShell

$Events = Get-EventLog -LogName System -Newest 1000

$Events | Group-Object -Property Source -NoElement | Sort-Object -Property


Count -Descending

Count Name

----- ----

110 DCOM

65 Service Control Manager

51 Microsoft-Windows-Kern...

14 EventLog

14 BTHUSB

13 Win32k

The Get-EventLog cmdlet uses the LogName parameter to specify the System log. The
Newest
parameter selects the 1000 most recent events. The event objects are stored in
the $Events
variable. The $Events objects are sent down the pipeline to the Group-
Object cmdlet.
Group-Object uses the Property parameter to group the objects by
source and counts the number
of objects for each source. The NoElement parameter
removes the group members from the output.
The Sort-Object cmdlet uses the
Property parameter to sort by the count of each source name.
The Descending
parameter sorts the list in order by count from highest to lowest.

Example 4: Get error events from a specific event log


This example gets error events from the System event log.
PowerShell

Get-EventLog -LogName System -EntryType Error

Index Time EntryType Source InstanceID Message

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

13296 Jan 16 13:53 Error DCOM 10016 The description for Event ID
'10016' in Source...

13291 Jan 16 13:51 Error DCOM 10016 The description for Event ID
'10016' in Source...

13245 Jan 16 11:45 Error DCOM 10016 The description for Event ID
'10016' in Source...

13230 Jan 16 11:07 Error DCOM 10016 The description for Event ID
'10016' in Source...

The Get-EventLog cmdlet uses the LogName parameter to specify the System log. The
EntryType parameter filters the events to show only Error events.

Example 5: Get events from an event log with an


InstanceId and Source value
This example gets events from the System log for a specific InstanceId and Source.

PowerShell

Get-EventLog -LogName System -InstanceId 10016 -Source DCOM

Index Time EntryType Source InstanceID Message

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

13245 Jan 16 11:45 Error DCOM 10016 The description for Event
ID '10016' in Source...
13230 Jan 16 11:07 Error DCOM 10016 The description for Event
ID '10016' in Source...
13219 Jan 16 10:00 Error DCOM 10016 The description for Event
ID '10016' in Source...

The Get-EventLog cmdlet uses the LogName parameter to specify the System log. The
InstanceID parameter selects the events with the specified Instance ID. The Source
parameter
specifies the event property.

Example 6: Get events from multiple computers


This command gets the events from the System event log on three computers: Server01,
Server02, and
Server03.

PowerShell
Get-EventLog -LogName System -ComputerName Server01, Server02, Server03

The Get-EventLog cmdlet uses the LogName parameter to specify the System log. The
ComputerName parameter uses a comma-separated string to list the computers from
which you want
to get the event logs.

Example 7: Get all events that include a specific word in


the message
This command gets all the events in the System event log that contain a specific word in
the event's
message. It's possible that your specified Message parameter's value is
included in the
message's content but isn't displayed on the PowerShell console.

PowerShell

Get-EventLog -LogName System -Message *description*

Index Time EntryType Source InstanceID Message

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

13821 Jan 17 19:17 Error DCOM 10016 The description


for Event ID '10016'...
13820 Jan 17 19:16 Error DCOM 10016 The description
for Event ID '10016'...
13819 Jan 17 19:08 Error DCOM 10016 The description
for Event ID '10016'...

The Get-EventLog cmdlet uses the LogName parameter to specify the System event log.
The
Message parameter specifies a word to search for in the message field of each
event.

Example 8: Display the property values of an event


This example shows how to display all of an event's properties and values.

PowerShell

$A = Get-EventLog -LogName System -Newest 1

$A | Select-Object -Property *

EventID : 10016

MachineName : localhost

Data : {}

Index : 13821

Category : (0)

CategoryNumber : 0

EntryType : Error

Message : The description for Event ID '10016' in Source


'DCOM'...

Source : DCOM

ReplacementStrings : {Local,...}

InstanceId : 10016

TimeGenerated : 1/17/2019 19:17:23

TimeWritten : 1/17/2019 19:17:23

UserName : username

Site :

Container :

The Get-EventLog cmdlet uses the LogName parameter to specify the System event log.
The
Newest parameter selects the most recent event object. The object is stored in the
$A
variable. The object in the $A variable is sent down the pipeline to the Select-

Object cmdlet.
Select-Object uses the Property parameter with an asterisk ( * ) to select
all of the object's
properties.

Example 9: Get events from an event log using a source


and event ID
This example gets events for a specified Source and Event ID.

PowerShell

Get-EventLog -LogName Application -Source Outlook | Where-Object {$_.EventID


-eq 63} |

Select-Object -Property Source, EventID, InstanceId, Message

Source EventID InstanceId Message

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

Outlook 63 1073741887 The Exchange web service request succeeded.

Outlook 63 1073741887 Outlook detected a change notification.

Outlook 63 1073741887 The Exchange web service request succeeded.

The Get-EventLog cmdlet uses the LogName parameter to specify the Application event
log. The
Source parameter specifies the application name, Outlook. The objects are sent
down the pipeline
to the Where-Object cmdlet. For each object in the pipeline, the
Where-Object cmdlet uses the
variable $_.EventID to compare the Event ID property to
the specified value. The objects are sent
down the pipeline to the Select-Object cmdlet.
Select-Object uses the Property parameter to
select the properties to display in the

PowerShell console.

Example 10: Get events and group by a property


PowerShell

Get-EventLog -LogName System -UserName NT* | Group-Object -Property UserName


-NoElement |

Select-Object -Property Count, Name

Count Name

----- ----

6031 NT AUTHORITY\SYSTEM

42 NT AUTHORITY\LOCAL SERVICE
4 NT AUTHORITY\NETWORK SERVICE

The Get-EventLog cmdlet uses the LogName parameter to specify the System log. The
UserName
parameter includes the asterisk ( * ) wildcard to specify a portion of the user
name. The event
objects are sent down the pipeline to the Group-Object cmdlet. Group-
Object uses the
Property parameter to specify that the UserName property is used to
group the objects and
count the number of objects for each user name. The NoElement
parameter removes the group
members from the output. The objects are sent down the
pipeline to the Select-Object cmdlet.
Select-Object uses the Property parameter to
select the properties to display in the
PowerShell console.

Example 11: Get events that occurred during a specific


date and time range
This example gets Error events from the System event log for a specified date and time
range. The
Before and After parameters set the date and time range but are excluded
from the output.

PowerShell

$Begin = Get-Date -Date '1/17/2019 08:00:00'

$End = Get-Date -Date '1/17/2019 17:00:00'

Get-EventLog -LogName System -EntryType Error -After $Begin -Before $End

Index Time EntryType Source InstanceID Message

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

13821 Jan 17 13:40 Error DCOM 10016 The description for


Event ID...

13820 Jan 17 13:11 Error DCOM 10016 The description for


Event ID...

...

12372 Jan 17 10:08 Error DCOM 10016 The description for


Event ID...

12371 Jan 17 09:04 Error DCOM 10016 The description for


Event ID...
The Get-Date cmdlet uses the Date parameter to specify a date and time. The DateTime
objects are stored in the $Begin and $End variables. The Get-EventLog cmdlet uses the
LogName parameter to specify the System log. The EntryType parameter specifies the
Error
event type. The date and time range is set by the After parameter and $Begin
variable and the
Before parameter and $End variable.

Parameters
-After

Gets events that occurred after a specified date and time. The After parameter date
and time are
excluded from the output. Enter a DateTime object, such as the value
returned by the Get-Date
cmdlet.

Type: DateTime

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-AsBaseObject

Indicates that this cmdlet 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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-AsString
Indicates that this cmdlet returns the output as strings, instead of objects.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Before

Gets events that occurred before a specified date and time. The Before parameter
date and time
are excluded from the output. Enter a DateTime object, such as the
value returned by the
Get-Date cmdlet.

Type: DateTime

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ComputerName

This parameter specifies a remote computer's NetBIOS name, Internet Protocol (IP)
address, or a
fully qualified domain name (FQDN).

If the ComputerName parameter isn't specified, Get-EventLog defaults to the local


computer. The parameter also accepts a dot ( . ) to specify the local computer.

The ComputerName parameter doesn't rely on Windows PowerShell remoting. You


can use
Get-EventLog with the ComputerName parameter even if your computer is
not configured to run
remote commands.

Type: String[]

Aliases: Cn

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-EntryType

Specifies, as a string array, the entry type of the events that this cmdlet gets.

The acceptable values for this parameter are:

Error
Information
FailureAudit
SuccessAudit
Warning

Type: String[]

Aliases: ET

Accepted values: Error, Information, FailureAudit, SuccessAudit, Warning

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Index

Specifies the index values to get from the event log. The parameter accepts a
comma-separated string
of values.

Type: Int32[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InstanceId
Specifies the Instance IDs to get from the event log. The parameter accepts a
comma-separated string
of values.

Type: Int64[]

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-List

Displays the list of event logs on the computer.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-LogName

Specifies the name of one event log. To find the log names use Get-EventLog -List .
Wildcard
characters are permitted. This parameter is required.

Type: String

Aliases: LN

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Message

Specifies a string in the event message. You can use this parameter to search for
messages that
contain certain words or phrases. Wildcards are permitted.
Type: String

Aliases: MSG

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Newest

Begins with the newest events and gets the specified number of events. The number
of events is
required, for example -Newest 100 . Specifies the maximum number of
events that are returned.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Source

Specifies, as a string array, sources that were written to the log that this cmdlet gets.
Wildcards
are permitted.

Type: String[]

Aliases: ABO

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-UserName
Specifies, as a string array, user names that are associated with events. Enter names
or name
patterns, such as User01 , User* , or Domain01\User* . Wildcards are
permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

Inputs
None

You cannot pipe input to Get-EventLog .

Outputs
System.Diagnostics.EventLogEntry. System.Diagnostics.EventLog. System.String

If the LogName parameter is specified, the output is a collection of


System.Diagnostics.EventLogEntry objects.

If only the List parameter is specified, the output is a collection of


System.Diagnostics.EventLog objects.

If both the List and AsString parameters are specified, the output is a collection of
System.String objects.

Notes
The cmdlets Get-EventLog and Get-WinEvent are not supported in the Windows
Preinstallation
Environment (Windows PE).

Related Links
Clear-EventLog
Get-WinEvent
Group-Object
Limit-EventLog
New-EventLog
Remove-EventLog
Select-Object
Show-EventLog
Write-EventLog
Get-HotFix
Reference
Module: Microsoft.PowerShell.Management

Gets the hotfixes that are installed on local or remote computers.

Syntax
PowerShell

Get-HotFix

[[-Id] <String[]>]

[-ComputerName <String[]>]

[-Credential <PSCredential>]

[<CommonParameters>]

PowerShell

Get-HotFix

[-Description <String[]>]

[-ComputerName <String[]>]

[-Credential <PSCredential>]

[<CommonParameters>]

Description
This cmdlet is only available on the Windows platform.

The Get-Hotfix cmdlet uses the Win32_QuickFixEngineering WMI class to list hotfixes
that are
installed on the local computer or specified remote computers.

Examples

Example 1: Get all hotfixes on the local computer


The Get-Hotfix cmdlet gets all hotfixes installed on the local computer.

PowerShell
Get-HotFix

Source Description HotFixID InstalledBy


InstalledOn

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


--

Server01 Update KB4495590 NT AUTHORITY\SYSTEM 5/16/2019


00:00:00

Server01 Security Update KB4470788 NT AUTHORITY\SYSTEM 1/22/2019


00:00:00

Server01 Update KB4480056 NT AUTHORITY\SYSTEM 1/24/2019


00:00:00

Example 2: Get hotfixes from multiple computers filtered


by a string
The Get-Hotfix command uses parameters to get hotfixes installed on remote
computers. The results
are filtered by a specified description string.

PowerShell

PS> Get-HotFix -Description Security* -ComputerName Server01, Server02 -


Credential Domain01\admin01

Get-Hotfix filters the output with the Description parameter and the string Security
that
includes the asterisk ( * ) wildcard. The ComputerName parameter includes a
comma-separated
string of remote computer names. The Credential parameter specifies
a user account that has
permission to access the remote computers and run commands.

Example 3: Verify if an update is installed and write


computer names to a file
The commands in this example verify whether a particular update installed. If the update
isn't
installed, the computer name is written to a text file.

PowerShell

PS> $A = Get-Content -Path ./Servers.txt

PS> $A | ForEach-Object { if (!(Get-HotFix -Id KB957095 -ComputerName $_))

{ Add-Content $_ -Path ./Missing-KB957095.txt }}

The $A variable contains computer names that were obtained by Get-Content from a
text file. The
objects in $A are sent down the pipeline to ForEach-Object . An if
statement uses the
Get-Hotfix cmdlet with the Id parameter and a specific Id number
for each computer name. If a
computer doesn't have the specified hotfix Id installed, the
Add-Content cmdlet writes the
computer name to a file.

Example 4: Get the most recent hotfix on the local


computer
This example gets the most recent hotfix installed on a computer.

PowerShell

(Get-HotFix | Sort-Object -Property InstalledOn)[-1]

Get-Hotfix sends the objects down the pipeline to the Sort-Object cmdlet. Sort-

Object sorts
objects by ascending order and uses the Property parameter to evaluate
each InstalledOn
date. The array notation [-1] selects the most recent installed hotfix.

Parameters
-ComputerName

Specifies a remote computer. Type the NetBIOS name, an Internet Protocol (IP)
address, or a fully
qualified domain name (FQDN) of a remote computer.

When the ComputerName parameter isn't specified, Get-Hotfix runs on the local
computer.

The ComputerName parameter doesn't rely on Windows PowerShell remoting. If


your computer isn't
configured to run remote commands, use the ComputerName
parameter.

Type: String[]

Aliases: CN, __Server, IPAddress

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False


-Credential

Specifies a user account that has permission to access the computer and run
commands. The default is
the current user

Type a user name, such as User01 or Domain01\User01, or enter a PSCredential


object
generated by the Get-Credential cmdlet. If you type a user name, you're
prompted to enter the
password.

Credentials are stored in a PSCredential


object and the password is stored as a
SecureString.

7 Note

For more information about SecureString data protection, see


How secure is
SecureString?.

Type: PSCredential

Position: Named

Default value: Current user

Accept pipeline input: False

Accept wildcard characters: False

-Description

Get-HotFix uses the Description parameter to specify hotfix types. Wildcards are
permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Id

Filters the Get-HotFix results for specific hotfix Ids. Wildcards aren't accepted.
Type: String[]

Aliases: HFID

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a string containing a computer name to this cmdlet.

Outputs
ManagementObject

This cmdlet returns objects representing the hotfixes on the computer.

Notes
This cmdlet is only available on Windows platforms.

The Win32_QuickFixEngineering WMI class represents


a small system-wide update,
commonly referred to as a quick-fix engineering (QFE) update, applied to
the current
operating system. This class returns only the updates supplied by Component Based
Servicing (CBS). These updates aren't listed in the registry. Updates supplied by
Microsoft Windows
Installer (MSI) or the Windows Update site aren't returned by
Win32_QuickFixEngineering. For more information, see
Win32_QuickFixEngineering
class.

The Get-HotFix output might vary on different operating systems.

Related Links
about_Arrays
Add-Content
Get-ComputerRestorePoint
Get-Credential
Win32_QuickFixEngineering class
Get-Item
Reference
Module: Microsoft.PowerShell.Management

Gets the item at the specified location.

Syntax
PowerShell

Get-Item

[-Path] <String[]>

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Force]

[-Credential <PSCredential>]

[-UseTransaction]

[-Stream <String[]>]

[<CommonParameters>]

PowerShell

Get-Item

-LiteralPath <String[]>

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Force]

[-Credential <PSCredential>]

[-UseTransaction]

[-Stream <String[]>]

[<CommonParameters>]

PowerShell

Get-Item

[-Path] <string[]>

[-Filter <string>]

[-Include <string[]>]

[-Exclude <string[]>]

[-Force]

[-Credential <pscredential>]

[-UseTransaction]

[-CodeSigningCert]

[-DocumentEncryptionCert]

[-SSLServerAuthentication]

[-DnsName <string>]

[-Eku <string[]>]

[-ExpiringInDays <int>]

[<CommonParameters>]

PowerShell

Get-Item

-LiteralPath <string[]>

[-Filter <string>]

[-Include <string[]>]

[-Exclude <string[]>]

[-Force]

[-Credential <pscredential>]

[-UseTransaction]

[-CodeSigningCert]

[-DocumentEncryptionCert]

[-SSLServerAuthentication]

[-DnsName <string>]

[-Eku <string[]>]

[-ExpiringInDays <int>]

[<CommonParameters>]

PowerShell

Get-Item

[-Path] <string[]>

[-Filter <string>]

[-Include <string[]>]

[-Exclude <string[]>]

[-Force]

[-Credential <pscredential>]

[-UseTransaction]

[<CommonParameters>]

PowerShell

Get-Item

-LiteralPath <string[]>

[-Filter <string>]

[-Include <string[]>]

[-Exclude <string[]>]

[-Force]

[-Credential <pscredential>]

[-UseTransaction]

[<CommonParameters>]
Description
The Get-Item cmdlet gets the item at the specified location. It doesn't get the contents
of the
item at the location unless you use a wildcard character ( * ) to request all the
contents of the
item.

This cmdlet is used by PowerShell providers to navigate through different types of data
stores.
Some parameters are only available for a specific provider. For more information,
see
about_Providers.

Examples

Example 1: Get the current directory


This example gets the current directory. The dot ('.') represents the item at the current
location
(not its contents).

PowerShell

Get-Item .

Directory: C:\

Mode LastWriteTime Length Name

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

d---- 7/26/2006 10:01 AM ps-test

Example 2: Get all the items in the current directory


This example gets all the items in the current directory. The wildcard character ( * )
represents
all the contents of the current item.

PowerShell

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

Example 3: Get the current directory of a drive


This example gets the current directory of the C: drive. The object that is retrieved
represents
only the directory, not its contents.

PowerShell

Get-Item C:

Example 4: Get items in the specified drive


This example gets the items in the C: drive. The wildcard character ( * ) represents all the
items
in the container, not just the container.

PowerShell

Get-Item C:\*

In PowerShell, use a single asterisk ( * ) to get contents, instead of the traditional *.* .
The
format is interpreted literally, so *.* wouldn't retrieve directories or filenames
without a dot.

Example 5: Get a property in the specified directory


This example gets the LastAccessTime property of the C:\Windows directory.
LastAccessTime
is just one property of file system directories. To see all the properties
of a directory, type
(Get-Item <directory-name>) | Get-Member .

PowerShell

(Get-Item C:\Windows).LastAccessTime

Example 6: Show the contents of a registry key


This example shows the contents of the Microsoft.PowerShell registry key. You can use
this
cmdlet with the PowerShell Registry provider to get registry keys and subkeys, but
you must use the
Get-ItemProperty cmdlet to get the registry values and data.
PowerShell

Get-Item
HKLM:\Software\Microsoft\Powershell\1\Shellids\Microsoft.Powershell\

Example 7: Get items in a directory that have an exclusion


This example gets items in the Windows directory with names that include a dot ( . ), but
don't
begin with w* .This example works only when the path includes a wildcard
character ( * ) to specify
the contents of the item.

PowerShell

Get-Item C:\Windows\*.* -Exclude "w*"

Parameters
-CodeSigningCert

This is a dynamic parameter made available by the Certificate provider.

To get certificates that have Code Signing in their EnhancedKeyUsageList property


value, use
the CodeSigningCert parameter.

For more information, see


about_Certificate_Provider.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Credential

7 Note

This parameter isn't supported by any providers installed with PowerShell.


To
impersonate another user, or elevate your credentials when running this cmdlet,
use Invoke-Command.

Type: PSCredential

Position: Named

Default value: Current user

Accept pipeline input: True

Accept wildcard characters: False

-DnsName

This is a dynamic parameter made available by the Certificate provider.

Specifies a domain name or name pattern to match with the DNSNameList property
of certificates
the cmdlet gets. The value of this parameter can either be Unicode or
ASCII . Punycode values
are converted to Unicode. Wildcard characters ( * ) are

permitted.

This parameter was reintroduced in PowerShell 7.1

For more information, see


about_Certificate_Provider.

Type: DnsNameRepresentation

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-DocumentEncryptionCert

This is a dynamic parameter made available by the Certificate provider.

To get certificates that have Document Encryption in their EnhancedKeyUsageList


property
value, use the DocumentEncryptionCert parameter.

For more information, see


about_Certificate_Provider.

Type: SwitchParameter

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Eku

This is a dynamic parameter made available by the Certificate provider.

Specifies text or a text pattern to match with the EnhancedKeyUsageList property of


certificates the cmdlet gets. Wildcard characters ( * ) are permitted. The
EnhancedKeyUsageList
property contains the friendly name and the OID fields of
the EKU.

This parameter was reintroduced in PowerShell 7.1

For more information, see


about_Certificate_Provider.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Exclude

Specifies, as a string array, an item or items that this cmdlet excludes in the
operation. The value
of this parameter qualifies the Path parameter. Enter a path
element or pattern, such as
*.txt . Wildcard characters 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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True


-ExpiringInDays

This is a dynamic parameter made available by the Certificate provider.

Specifies that the cmdlet should only return certificates that are expiring in or before
the
specified number of days. A value of zero ( 0 ) gets certificates that have expired.

This parameter was reintroduced in PowerShell 7.1

For more information, see


about_Certificate_Provider.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Filter

Specifies a filter to qualify the Path parameter. The


FileSystem provider is the only
installed PowerShell provider that supports filters. Filters are more efficient than
other
parameters. The provider applies filter when the cmdlet gets the objects rather
than having
PowerShell filter the objects after they're retrieved. The filter string is
passed to the .NET API
to enumerate files. The API only supports * and ? wildcards.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Force

Indicates that this cmdlet gets items that can't 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 can't override security
restrictions.

Type: SwitchParameter
Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Include

Specifies, as a string array, an item or items that this cmdlet includes in the
operation. The value
of this parameter qualifies the Path parameter. Enter a path
element or pattern, such as
*.txt . Wildcard characters 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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-LiteralPath

Specifies a path to one or more locations. The value of LiteralPath is used exactly as
it's
typed. No characters are interpreted as wildcards. If the path includes escape
characters, enclose
it in single quotation marks. Single quotation marks tell
PowerShell not to interpret any characters
as escape sequences.

For more information, see about_Quoting_Rules.

Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False


-Path

Specifies the path to an item. This cmdlet gets the item at the specified location.
Wildcard
characters 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.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-SSLServerAuthentication

This is a dynamic parameter made available by the Certificate provider.

To get certificates that have Server Authentication in their EnhancedKeyUsageList


property
value, use the SSLServerAuthentication parameter.

For more information, see


about_Certificate_Provider.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Stream

This is a dynamic parameter made available by the FileSystem provider.

Gets the specified alternate NTFS file stream from the file. Enter the stream name.
Wildcards are
supported. To get all streams, use an asterisk ( * ). This parameter isn't
valid on folders.

This parameter was introduced in PowerShell 3.0.


For more information, see
about_FileSystem_Provider.

Type: String[]

Position: Named

Default value: No alternate file streams

Accept pipeline input: False

Accept wildcard characters: True

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

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a string that contains a path to this cmdlet.

Outputs
AliasInfo

The cmdlet outputs this type when accessing the Alias: drive.

X509StoreLocation

X509Store

X509Certificate2
The cmdlet outputs these types when accessing the Cert: drive.

DictionaryEntry

The cmdlet outputs this type when accessing the Env: drive.

DirectoryInfo

FileInfo

The cmdlet outputs these types when accessing the Filesystem drives.

FunctionInfo

FilterInfo

The cmdlet outputs these types when accessing the Function: drives.

RegistryKey

The cmdlet outputs this type when accessing the Registry drives.

PSVariable

The cmdlet outputs this type when accessing the Variable: drives.

Microsoft.WSMan.Management.WSManConfigContainerElement

Microsoft.WSMan.Management.WSManConfigLeafElement

The cmdlet outputs these types when accessing the WSMan: drives.

Notes
Windows PowerShell includes the following aliases for Get-Item :

gi

This cmdlet 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 this cmdlet to get registry keys and the Get-
ItemProperty
to get registry values and data. The registry values are considered to be

properties of the
registry key.
This 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.

Related Links
Clear-Item
Copy-Item
Invoke-Item
Move-Item
New-Item
Remove-Item
Rename-Item
Set-Item
Get-ChildItem
Get-ItemProperty
Get-PSProvider
about_Providers
Get-ItemProperty
Reference
Module: Microsoft.PowerShell.Management

Gets the properties of a specified item.

Syntax
PowerShell

Get-ItemProperty

[-Path] <String[]>

[[-Name] <String[]>]

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Credential <PSCredential>]

[-UseTransaction]

[<CommonParameters>]

PowerShell

Get-ItemProperty

-LiteralPath <String[]>

[[-Name] <String[]>]

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Credential <PSCredential>]

[-UseTransaction]

[<CommonParameters>]

Description
The Get-ItemProperty cmdlet gets the properties of the specified items. For example,
you can use
this cmdlet to get the value of the LastAccessTime property of a file object.
You can also use
this cmdlet to view registry entries and their values.

Examples

Example 1: Get information about a specific directory


This command gets information about the C:\Windows directory.

PowerShell

Get-ItemProperty C:\Windows

Example 2: Get the properties of a specific file


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.

PowerShell

Get-ItemProperty C:\Test\Weather.xls | Format-List

Example 3: Get the value name and data of a registry


entry in a registry subkey
This command gets the value name and data of the ProgramFilesDir registry entry in
the
CurrentVersion registry subkey. The Path specifies the subkey and the Name
parameter
specifies the value name of the entry.

PowerShell

Get-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion -Name


"ProgramFilesDir"

7 Note

This command requires that there is a 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 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: Get the value names and data of registry
entries in a registry key
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.

PowerShell

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=31bf3856ad364e35, ProcessorArchitecture=msil

PowerShellVersion : 2.0

RuntimeVersion : v2.0.50727

CTPVersion : 5

PSCompatibleVersion : 1.0,2.0

Parameters
-Credential

7 Note

This parameter is not supported by any providers installed with Windows


PowerShell. To impersonate
another user, or elevate your credentials when
running this cmdlet, use
Invoke-Command.

Type: PSCredential

Position: Named

Default value: Current user

Accept pipeline input: True

Accept wildcard characters: False

-Exclude

Specifies, as a string array, an item or items that this cmdlet excludes in the
operation. The value
of this parameter qualifies the Path parameter. Enter a path
element or pattern, such as
*.txt . Wildcard characters 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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Filter

Specifies a filter to qualify the Path parameter. The


FileSystem provider is the only
installed PowerShell provider that supports the use of filters. You can find the syntax
for the
FileSystem filter language in
about_Wildcards. Filters are more efficient
than
other parameters, because the provider applies them when the cmdlet gets the
objects rather
than having PowerShell filter the objects after they are retrieved.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Include

Specifies, as a string array, an item or items that this cmdlet includes in the
operation. The value
of this parameter qualifies the Path parameter. Enter a path
element or pattern, such as
*.txt . Wildcard characters 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.

Type: String[]

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: True

-LiteralPath

Specifies the path to the current location of the 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 PowerShell not
to interpret any characters as escape sequences.

For more information, see


about_Quoting_Rules.

Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies the name of the property or properties to retrieve.

Type: String[]

Aliases: PSProperty

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Path

Specifies the path to the item or items.

Type: String[]

Position: 0
Default value: None

Accept pipeline input: True

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.

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a string that contains a path to this cmdlet.

Outputs
Boolean

String

DateTime

FileInfo

DirectoryInfo

This cmdlet returns an object for each item property that it gets. The object type
depends on
the object that is retrieved. For example, in a file system drive, it might
return a file or folder.
Notes
Windows PowerShell includes the following aliases for Get-ItemProperty :

gp

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.

Related Links
Clear-ItemProperty
Copy-ItemProperty
Move-ItemProperty
New-ItemProperty
Remove-ItemProperty
Rename-ItemProperty
Set-ItemProperty
about_Providers
Get-ItemPropertyValue
Reference
Module: Microsoft.PowerShell.Management

Gets the value for one or more properties of a specified item.

Syntax
PowerShell

Get-ItemPropertyValue

[[-Path] <String[]>]

[-Name] <String[]>

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Credential <PSCredential>]

[-UseTransaction]

[<CommonParameters>]

PowerShell

Get-ItemPropertyValue

-LiteralPath <String[]>

[-Name] <String[]>

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Credential <PSCredential>]

[-UseTransaction]

[<CommonParameters>]

Description
The Get-ItemPropertyValue gets the current value for a property that you specify when
you use the
Name parameter, located in a path that you specify with either the Path or
LiteralPath
parameters.

Examples

Example 1: Get the value of the ProductID property


This command gets the value of the ProductID property of the
\SOFTWARE\Microsoft\WindowsNT\CurrentVersion
object in the Windows Registry
provider.

PowerShell

Get-ItemPropertyValue 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -


Name ProductID

94253-50000-11141-AA785

Example 2: Get the last write time of a file or folder


This command gets the value of the LastWriteTime property, or the last time a file or
folder was
changed, from the C:\Program Files\WindowsPowerShell folder, working in
the FileSystem
provider.

PowerShell

Get-ItemPropertyValue -Path 'C:\Program Files\WindowsPowerShell' -Name


LastWriteTime

Wednesday, September 3, 2014 2:53:22 PM

Example 3: Get multiple property values of a file or folder


This command gets the values of the LastWriteTime, CreationTime, and Root properties
of
a folder. The property values are returned in the order in which you specified the
property names.

PowerShell

Get-ItemPropertyValue -Path 'C:\Program Files\WindowsPowerShell' -Name


LastWriteTime,CreationTime,Root

Tuesday, March 23, 2021 6:53:13 AM

Monday, August 14, 2017 1:42:40 PM

Name : C:\

FullName : C:\

Parent :

Exists : True

Root : C:\

Extension :

CreationTime : 10/30/2015 1:28:30 AM

CreationTimeUtc : 10/30/2015 6:28:30 AM

LastAccessTime : 5/26/2021 9:24:31 AM

LastAccessTimeUtc : 5/26/2021 2:24:31 PM

LastWriteTime : 5/25/2021 7:25:08 AM

LastWriteTimeUtc : 5/25/2021 12:25:08 PM

Attributes : Hidden, System, Directory

Mode : d--hs-

BaseName : C:\

Target : {}

LinkType :

Parameters
-Credential

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 are prompted for a
password.

2 Warning

This parameter is not supported by any providers installed with Windows


PowerShell.

Type: PSCredential

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Exclude

Specifies, as a string array, an item or items that this cmdlet excludes from the
operation. The
value of this parameter qualifies the Path parameter. Enter a path
element or pattern, such as
"*.txt". Wildcard characters are permitted.

Type: String[]

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Filter

Specifies a filter in the format or language of the provider. The value of this
parameter qualifies
the Path parameter.

The syntax of the filter, including the use of wildcard characters, depends on the
provider. Filters
are more efficient than other parameters, because the provider
applies them when the cmdlet gets the
objects rather than having PowerShell filter
the objects after they are retrieved.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Include

Specifies, as a string array, an item or items that this cmdlet includes in the
operation. The value
of this parameter qualifies the Path parameter. Enter a path
element or pattern, such as
"*.txt". Wildcard characters are permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-LiteralPath

Specifies the path to the current location of the property. Unlike the Path parameter,
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 PowerShell not to interpret any characters as escape
sequences.

Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies the name of the property or properties to retrieve.

Type: String[]

Aliases: PSProperty

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Path

Specifies the path to the item or items.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

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.

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a string that contains a path to this cmdlet.

Outputs
PSObject

This cmdlet returns an object for each item property value that it gets.
The object type
depends on the property value that is retrieved.

Notes
Windows PowerShell includes the following aliases for Get-ItemPropertyValue :

gpv

This cmdlet is designed to work with the data exposed by any provider. To list the
providers
available in your session, run the Get-PSProvider cmdlet. For more
information, see
about_Providers.

Related Links
Get-ItemProperty
Clear-ItemProperty
Copy-ItemProperty
Get-PSProvider
Move-ItemProperty
New-ItemProperty
Remove-ItemProperty
Rename-ItemProperty
Set-ItemProperty
about_Providers
Get-Location
Reference
Module: Microsoft.PowerShell.Management

Gets information about the current working location or a location stack.

Syntax
PowerShell

Get-Location

[-PSProvider <String[]>]

[-PSDrive <String[]>]

[-UseTransaction]

[<CommonParameters>]

PowerShell

Get-Location

[-Stack]

[-StackName <String[]>]

[-UseTransaction]

[<CommonParameters>]

Description
The Get-Location cmdlet gets an object that represents the current directory, much like
the print
working directory (pwd) command.

When you move between PowerShell drives, PowerShell retains your location in each
drive. You can use
this cmdlet to find your location in each drive.

You can use this cmdlet 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 PowerShell
prompt.

You can also use this cmdlet to display the locations in a location stack. For more
information, see
the Notes and the descriptions of the Stack and StackName
parameters.

Examples
Example 1: Display your current drive location
This command displays your location in the current PowerShell drive.

PowerShell

PS C:\Windows> Get-Location

Path

----

C:\Windows

For instance, if you are in the Windows directory of the C: drive, it displays the path to
that
directory.

Example 2: Display your current location for different


drives
This example demonstrates the use of Get-Location to display your current location in
different
PowerShell drives. Set-Location is used to change the location to several
different paths on
different PSDrives.

PowerShell

PS C:\> Set-Location C:\Windows

PS C:\Windows> Set-Location HKLM:\Software\Microsoft

PS HKLM:\Software\Microsoft> Set-Location "HKCU:\Control Panel\Input Method"

PS HKCU:\Control Panel\Input Method> Get-Location -PSDrive C

Path

----

C:\Windows

PS HKCU:\Control Panel\Input Method> Get-Location -PSDrive HKLM

Path

----

HKLM:\Software\Microsoft

PS HKCU:\Control Panel\Input Method> Set-Location C:

PS C:\Windows> Get-Location -PSProvider Registry

Path

----

HKCU:\Control Panel\Input Method


Example 3: Get locations using stacks
This example shows how to use the Stack and StackName parameters of Get-Location
to list
the locations in the current location stack and alternate location stacks.

The Push-Location cmdlet is used to change into three different locations. The third
push uses a
different stack name. The Stack parameter of Get-Location displays the
contents of the default
stack. The StackName parameter of Get-Location displays the
contents of the stack named
Stack2 .

PowerShell

PS C:\> Push-Location C:\Windows

PS C:\Windows>Push-Location System32

PS C:\Windows\System32>Push-Location WindowsPowerShell -StackName Stack2

C:\Windows\System32\WindowsPowerShell>Get-Location -Stack

Path

----

C:\Windows

C:\

C:\Windows\System32\WindowsPowerShell>Get-Location -StackName Stack2

Path

----

C:\Windows\System32

Example 4: Customize the PowerShell prompt


This example shows how to customize the PowerShell prompt.

PowerShell

PS C:\>

function prompt { 'PowerShell: ' + (Get-Location) + '> '}

PowerShell: C:\>

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 PowerShell prompt is defined by a special function named
prompt . You can
change the prompt in your console by creating a new function named

prompt .
To see the current prompt function, type the following command: Get-Content
Function:\prompt

Parameters
-PSDrive

Gets the current location in the specified PowerShell drive.

For instance, if you are in the Cert: drive, you can use this parameter to find your
current location in the C: drive.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-PSProvider

Gets the current location in the drive supported by the specified PowerShell provider.
If the specified provider supports more than one drive, this cmdlet 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 PowerShell Registry provider.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Stack

Indicates that this cmdlet displays the locations added to the current location stack.
You can add
locations to stacks by using the Push-Location cmdlet.
To display the locations in a different location stack, use the StackName parameter.
For
information about location stacks, see the Notes.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-StackName

Specifies, as a string array, the named location stacks. Enter one or more location
stack names.

To display the locations in the current location stack, use the Stack parameter. To
make a
location stack the current location stack, use the Set-Location cmdlet.

This cmdlet cannot display the locations in the unnamed default stack unless it is the
current
stack.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: True

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.

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False


Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
PathInfo

By default, this cmdlet returns a PathInfo object.

PathInfoStack

When you use the Stack or StackName parameters, this cmdlet returns a PathInfoStack
object.

Notes
Windows PowerShell includes the following aliases for Get-Location :

gl
pwd

PowerShell supports multiple runspaces per process. Each runspace has its own current
directory.
This is not the same as [System.Environment]::CurrentDirectory . This behavior
can be an issue
when calling .NET APIs or running native applications without providing
explicit directory paths.
The Get-Location cmdlet returns the current directory of the
current PowerShell runspace.

This cmdlet is designed to work with the data exposed by any provider. To list the
providers in your
session, type Get-PSProvider . For more information, see
about_Providers.

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, this cmdlet returns
the PathInfo object for the provider that contains the
current working location.
A stack is a last-in, first-out list in which only the most recently added item is accessible.
You
add items to a stack in the order that you use them, and then retrieve them for use
in the reverse
order. PowerShell lets you store provider locations in location stacks.
PowerShell creates an
unnamed default location stack and you can create multiple
named location stacks. If you do not
specify a stack name, PowerShell uses the current
location stack. By default, the unnamed default
location is the current location stack, but
you can use the Set-Location cmdlet to change the
current location stack.

To manage location stacks, use the PowerShell *-Location cmdlets, as follows.

To add a location to a location stack, use the Push-Location cmdlet.

To get a location from a location stack, use the Pop-Location cmdlet.

To display the locations in the current location stack, use the Stack parameter of
the
Get-Location cmdlet. To display the locations in a named location stack, use
the StackName
parameter of the Get-Location cmdlet.

To create a new location stack, use the StackName parameter of the Push-
Location cmdlet.
If you specify a stack that does not exist, Push-Location creates

the stack.

To make a location stack the current location stack, use the StackName parameter
of the
Set-Location cmdlet.

The unnamed default location stack is fully accessible only when it is the current location
stack.
If you make a named location stack the current location stack, you can no longer
use the
Push-Location or Pop-Location cmdlets to add or get items from the default
stack or use this
cmdlet to display the locations in the unnamed stack. To make the
unnamed stack the current stack,
use the StackName parameter of the Set-Location
cmdlet with a value of $null or an empty
string ( "" ).

Related Links
Pop-Location
Push-Location
Set-Location
Get-Process
Reference
Module: Microsoft.PowerShell.Management

Gets the processes that are running on the local computer or a remote computer.

Syntax
PowerShell

Get-Process

[[-Name] <String[]>]

[-ComputerName <String[]>]

[-Module]

[-FileVersionInfo]

[<CommonParameters>]

PowerShell

Get-Process

[[-Name] <String[]>]

[-IncludeUserName]

[<CommonParameters>]

PowerShell

Get-Process

-Id <Int32[]>

[-IncludeUserName]

[<CommonParameters>]

PowerShell

Get-Process

-Id <Int32[]>

[-ComputerName <String[]>]

[-Module]

[-FileVersionInfo]

[<CommonParameters>]

PowerShell

Get-Process

-InputObject <Process[]>

[-IncludeUserName]

[<CommonParameters>]

PowerShell

Get-Process

-InputObject <Process[]>

[-ComputerName <String[]>]

[-Module]

[-FileVersionInfo]

[<CommonParameters>]

Description
The Get-Process cmdlet gets the processes on a local or remote computer.

Without parameters, this cmdlet 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 this cmdlet.

By default, this cmdlet 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 the
Get-Process cmdlet to get file version information for the
program that runs in the process and to
get the modules that the process loaded.

Examples

Example 1: Get a list of all active processes on the local


computer
PowerShell

Get-Process

This command gets a list of all active processes running on the local computer. For a
definition of
each column, see the Notes section.

Example 2: Get all available data about one or more


processes
PowerShell

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 instance, Get-Process -Id
664, 2060 .

Example 3: Get all processes with a working set greater


than a specified size
PowerShell

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: List processes on the computer in groups


based on priority
PowerShell

$A = Get-Process

$A | Get-Process | 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 pipes the Process object stored in the $A variable to the Get-
Process
cmdlet, then 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
PowerShell
home directory ( $pshome ).

Example 5: Add a property to the standard Get-Process


output display
PowerShell

Get-Process powershell | Format-Table `

@{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) {$_.CPU.ToString("N")}}},

Id, ProcessName, StartTime -AutoSize

NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName StartTime

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

143 239540 259384 2366162 22.73 12720 powershell 12/5/2022 3:21:51 PM

114 61776 104588 2366127 11.45 18336 powershell 12/5/2022 7:30:53 AM

156 77924 82060 2366185 10.47 18812 powershell 12/5/2022 7:30:52 AM

85 48216 115192 2366074 1.14 24428 powershell 12/8/2022 9:14:15 AM

This example retrieves processes from the local computer. The retrieved processes are
piped to the
Format-Table command that adds the StartTime property to the standard
Get-Process output
display.

Example 6: Get version information for a process


PowerShell

Get-Process powershell -FileVersionInfo

ProductVersion FileVersion FileName

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

6.1.6713.1 6.1.6713.1 (f...


C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe

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 PowerShell with the Run as administrator option.

Example 7: Get modules loaded with the specified


process
PowerShell

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 PowerShell with the Run as administrator option.

Example 8: Find the owner of a process


PowerShell

Get-Process pwsh -IncludeUserName

Handles WS(K) CPU(s) Id UserName ProcessName

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

782 132080 2.08 2188 DOMAIN01\user01 powershell

$p = Get-WmiObject Win32_Process -Filter "name='powershell.exe'"

$p.GetOwner()

__GENUS : 2

__CLASS : __PARAMETERS

__SUPERCLASS :

__DYNASTY : __PARAMETERS

__RELPATH :

__PROPERTY_COUNT : 3

__DERIVATION : {}

__SERVER :

__NAMESPACE :

__PATH :

Domain : DOMAIN01

ReturnValue : 0

User : user01

The first command shows how to find the owner of a process. The IncludeUserName
parameter
requires elevated user rights (Run as Administrator). The output reveals that
the owner is
Domain01\user01 .

The second and third command are another way to find the owner of a process.

The second command uses Get-WmiObject to get the PowerShell process.


It saves it in
the $p variable.

The third command uses the GetOwner method to get the owner of the process in $p .
The output
reveals that the owner is Domain01\user01 .

Example 9: Use an automatic variable to identify the


process hosting the current session
PowerShell

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

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

These commands show how to use the $PID automatic variable to identify the process
that is hosting
the current 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.

Example 10: Get all processes that have a main window


title and display them in a table
PowerShell

Get-Process | Where-Object {$_.mainWindowTitle} | Format-Table Id, Name,


mainWindowtitle -AutoSize
This command gets all the processes that have a main window title, and it displays them
in a table
with the process ID and the process name.

The mainWindowTitle property is just one of many useful properties of the Process
object
that Get-Process returns. To view all of the properties, pipe the results of a Get-
Process
command to the Get-Member cmdlet Get-Process | Get-Member .

Parameters
-ComputerName

Specifies the computers for which this cmdlet gets active processes. The default is
the local
computer.

Type the NetBIOS name, an IP address, or a fully qualified domain name (FQDN) 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 this cmdlet even if your computer is not configured to
run remote commands.

Type: String[]

Aliases: Cn

Position: Named

Default value: Local computer

Accept pipeline input: True

Accept wildcard characters: False

-FileVersionInfo

Indicates that this cmdlet gets the file version information for the program that runs
in the
process.

On Windows Vista and later versions of Windows, you must open PowerShell with
the Run as
administrator option to use this parameter on processes that you do not
own.
You cannot use the FileVersionInfo and ComputerName parameters of the Get-
Process
cmdlet in the same command.

To get file version information for a process on a remote computer, use the Invoke-
Command cmdlet.

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 .

Type: SwitchParameter

Aliases: FV, FVI

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Id

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 .

Type: Int32[]

Aliases: PID

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-IncludeUserName

Indicates that the UserName value of the Process object is returned with results of
the command.

Type: SwitchParameter
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies one or more process objects. Enter a variable that contains the objects, or
type a command
or expression that gets the objects.

Type: Process[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Module

Indicates that this cmdlet gets the modules that have been loaded by the processes.

On Windows Vista and later versions of Windows, you must open PowerShell with
the Run as
administrator option to use this parameter on processes that you do not
own.

To get the modules that have been loaded by a process on a remote computer, use
the Invoke-Command
cmdlet.

This parameter is equivalent to getting the Modules property of each process object.
When you
use this parameter, this cmdlet 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, this cmdlet
returns a FileVersionInfo object with information about the
file version of all modules.

Type: SwitchParameter
Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Name

Specifies one or more processes by process name. You can type multiple process
names (separated by
commas) and use wildcard characters. The parameter name
( Name ) is optional.

Type: String[]

Aliases: ProcessName

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

Inputs
Process

You can pipe a process object to this cmdlet.

Outputs
Process

By default, this cmdlet returns a System.Diagnostics.Process object.

FileVersionInfo

If you use the FileVersionInfo parameter, this cmdlet returns a FileVersionInfo object.

ProcessModule

If you use the Module parameter, without the FileVersionInfo parameter, this cmdlet
returns
a ProcessModule object.
Notes
Windows PowerShell includes the following aliases for Get-Process :

gps

ps

On computers that are running a 64-bit version of Windows, the 64-bit version of
PowerShell gets
only 64-bit process modules and the 32-bit version of PowerShell
gets only 32-bit process modules.

You can use the properties and methods of the Windows Management
Instrumentation (WMI)
Win32_Process object in PowerShell. For information, see
Get-WmiObject and the WMI SDK.

The default display of a process is a table that includes the following columns. For
a description
of all of the properties of process objects, see
Process Properties.
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.

Related Links
Debug-Process
Get-Process
Start-Process
Stop-Process
Wait-Process
Get-PSDrive
Reference
Module: Microsoft.PowerShell.Management

Gets drives in the current session.

Syntax
PowerShell

Get-PSDrive

[[-Name] <String[]>]

[-Scope <String>]

[-PSProvider <String[]>]

[<CommonParameters>]

PowerShell

Get-PSDrive

[-LiteralName] <String[]>

[-Scope <String>]

[-PSProvider <String[]>]

[<CommonParameters>]

Description
The Get-PSDrive cmdlet gets the drives in the current session. You can get a particular
drive or
all drives in the session.

This cmdlet gets the following types of drives:

Windows logical drives on the computer, including drives mapped to network


shares.
Drives exposed by 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.
Session-specified temporary drives and persistent mapped network drives that you
create by using
the New-PSDrive cmdlet.

Beginning in Windows PowerShell 3.0, the Persist parameter of the New-PSDrive cmdlet
can
create mapped network drives that are saved on the local computer and are
available in other
sessions. For more information, see New-PSDrive.

Also, beginning in Windows PowerShell 3.0, when an external drive is connected to the
computer,
Windows PowerShell automatically adds a PSDrive to the file system that
represents the new drive.
You do not need to restart Windows PowerShell. Similarly,
when an external drive is disconnected
from the computer, Windows PowerShell
automatically deletes the PSDrive that represents the removed
drive.

Examples

Example 1: Get drives in the current session


PowerShell

PS C:\> Get-PSDrive

Name Used (GB) Free (GB) Provider Root

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

Alias Alias

C 202.06 23718.91 FileSystem C:\

Cert Certificate \

D 1211.06 123642.32 FileSystem D:\

Env Environment

Function Function

HKCU Registry HKEY_CURRENT_USER

HKLM Registry HKEY_LOCAL_MACHINE

Variable Variable

This command gets the drives in the current session.

The output shows the hard drive (C:), CD-ROM drive (D:), and the drives exposed by the
Windows
PowerShell providers (Alias:, Cert:, Env:, Function:, HKCU:, HKLM:, and
Variable:).

Example 2: Get a drive on the computer


PowerShell

PS C:\foo> Get-PSDrive D

Name Used (GB) Free (GB) Provider Root

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

D 1211.06 123642.32 FileSystem D:\


This command gets the D: drive on the computer. Note that the drive letter in the
command is not
followed by a colon.

Example 3: Get all the drives that are supported by the


Windows PowerShell file system provider
PowerShell

PS C:\> Get-PSDrive -PSProvider FileSystem

Name Used (GB) Free (GB) Provider Root

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

A A:\

C 202.06 23718.91 FileSystem C:\

D 1211.06 123642.32 FileSystem D:\

G 202.06 710.91 FileSystem \\Music\GratefulDead

This command gets all of the drives that are supported by the Windows PowerShell
FileSystem
provider. This includes fixed drives, logical partitions, mapped network drives,
and temporary
drives that you create by using the New-PSDrive cmdlet.

Example 4: Check to see if a drive is in use as a Windows


PowerShell drive name
PowerShell

if (Get-PSDrive X -ErrorAction SilentlyContinue) {

Write-Host 'The X: drive is already in use.'

} else {

New-PSDrive -Name X -PSProvider Registry -Root HKLM:\SOFTWARE

This command checks to see whether the X drive is already in use as a Windows
PowerShell drive name.
If it is not, the command uses the New-PSDrive cmdlet to create
a temporary drive that is mapped
to the HKLM:\SOFTWARE registry key.

Example 5: Compare the types of files system drives


PowerShell

PS C:\> Get-PSDrive -PSProvider FileSystem

Name Used (GB) Free (GB) Provider Root

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

A A:\

C 202.06 23718.91 FileSystem C:\

D 1211.06 123642.32 FileSystem D:\

G 202.06 710.91 FileSystem \\Music\GratefulDead

X Registry HKLM:\Network

PS C:\> net use

New connections will be remembered.

Status Local Remote Network

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

OK G: \\Server01\Public Microsoft Windows Network

PS C:\> [System.IO.DriveInfo]::GetDrives() | Format-Table

Name DriveType DriveFormat IsReady AvailableFreeSpace TotalFreeSpace


TotalSize RootDirectory VolumeLabel

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


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

A:\ Network False


A:\

C:\ Fixed NTFS True 771920580608 771920580608


988877418496 C:\ Windows

D:\ Fixed NTFS True 689684144128 689684144128


1990045179904 D:\ Big Drive

E:\ CDRom False


E:\

G:\ Network NTFS True 69120000 69120000


104853504 G:\ GratefulDead

PS N:\> Get-CimInstance -Class Win32_LogicalDisk

DeviceID DriveType ProviderName VolumeName Size FreeSpace

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

A: 4

C: 3 Windows 988877418496
771926069248

D: 3 Big! 1990045179904
689684144128

E: 5

G: 4 \\Music\GratefulDead 988877418496
771926069248

PS C:\> Get-CimInstance -Class Win32_NetworkConnection

LocalName RemoteName ConnectionState Status

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

G: \\Music\GratefulDead Connected OK

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 session-specific drives
created by using the New-PSDrive
cmdlet are accessible only in Windows PowerShell.
The first command uses Get-PSDrive to get all of the file system drives in the session.
This
includes the fixed drives (C: and D:), a mapped network drive (G:) that was created
by using the
Persist parameter of New-PSDrive , and a PowerShell drive (T:) that was
created by using
New-PSDrive without the Persist parameter.

The net use command displays Windows mapped network drives, in this case it displays
only the G
drive. It does not display the X: drive that was created by New-PSDrive . It
shows that the G:
drive is also mapped to \\Music\GratefulDead.

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 G:,
but it does not get the drives created by New-PSDrive .

The fourth command uses the Get-CimInstance cmdlet to get the instances of the
Win32_LogicalDisk class. It returns the A:, C:, D:, E:, and G: drives, but not the drives
created by New-PSDrive .

The last command uses the Get-CimInstance cmdlet to display the instances of the
Win32_NetworkConnection class. Like net use, it returns only the persistent G: drive
created
by New-PSDrive .

Parameters
-LiteralName

Specifies the name of the 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.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name
Specifies, as a string array, the name or name of drives that this cmdlet gets in the
operation.
Type the drive name or letter without a colon ( : ).

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-PSProvider

Specifies, as a string array, the Windows PowerShell provider. This cmdlet gets only
the drives
supported by this provider. Type the name of a provider, such as
FileSystem, Registry, or
Certificate.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Scope

Specifies the scope in which this cmdlet gets the drives.

The acceptable values for this parameter are:

Global
Local
Script
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.

Type: String

Position: Named

Default value: None


Accept pipeline input: True

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.

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
PSDriveInfo

This cmdlet returns objects representing the drives in the session.

Notes
Windows PowerShell includes the following aliases for Get-PSDrive :

gdr

This cmdlet is designed to work with the data exposed by any provider. To list the
providers
available in your session, use the Get-PSProvider cmdlet. For more
information, see
about_Providers.
Mapped network drives that are created by using the Persist parameter of the
New-PSDrive
cmdlet are specific to a user account. Mapped network drives that
you create in sessions that are
started with the Run as administrator option or with
the credentials of another user are not
visible in sessions that are started without
explicit credentials or with the credentials of the
current user.

Related Links
New-PSDrive
Remove-PSDrive
Get-PSProvider
Get-PSProvider
Reference
Module: Microsoft.PowerShell.Management

Gets information about the specified PowerShell provider.

Syntax
PowerShell

Get-PSProvider

[[-PSProvider] <String[]>]

[<CommonParameters>]

Description
The Get-PSProvider cmdlet gets the PowerShell providers in the current session. You can
get a
particular drive or all drives in the session.

PowerShell providers let you access a variety of data stores as though they were file
system drives.
For information about PowerShell providers, see
about_Providers.

Examples

Example 1: Display a list of all available providers


PowerShell

Get-PSProvider

This command displays a list of all available PowerShell providers.

Example 2: Display a list of all PowerShell providers that


begin with specified letters
PowerShell

Get-PSProvider f*, r* | Format-List


This command displays a list of all PowerShell providers with names that begin with the
letter f
or r .

Example 3: Find snap-ins or module that added providers


to your session
PowerShell

Get-PSProvider | Format-Table Name, Module, PSSnapIn -AutoSize

Name Module PSSnapIn

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

Registry Microsoft.PowerShell.Core

Alias Microsoft.PowerShell.Core

Environment Microsoft.PowerShell.Core

FileSystem Microsoft.PowerShell.Core

Function Microsoft.PowerShell.Core

Variable Microsoft.PowerShell.Core

Certificate Microsoft.PowerShell.Security

WSMan Microsoft.WSMan.Management

Get-PSProvider | Where {$_.ModuleName -eq "Microsoft.PowerShell.Security"}

Name Capabilities Drives

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

Certificate ShouldProcess {cert}

These commands find the PowerShell snap-ins or modules that added providers to your
session.
All 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.

Example 4: Resolve the path of the Home property of the


file system provider
PowerShell
C:\> Resolve-Path ~

Path

----

C:\Users\User01

PS C:\> (get-psprovider FileSystem).home

C:\Users\User01

This example shows that the tilde symbol ( ~ ) represents the value of the Home property
of the
FileSystem provider. The Home property value is optional, but for the FileSystem
provider,
it is defined as $env:HOMEDRIVE\$env:HOMEPATH or $HOME .

Parameters
-PSProvider

Specifies the name or names of the PowerShell providers about which this cmdlet
gets information.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

Inputs
String

You can pipe one or more provider name strings to this cmdlet.

Outputs
ProviderInfo

This cmdlet returns objects that represent the PowerShell providers in the session.
Get-Service
Reference
Module: Microsoft.PowerShell.Management

Gets the services on a local or remote computer.

Syntax
PowerShell

Get-Service

[[-Name] <String[]>]

[-ComputerName <String[]>]

[-DependentServices]

[-RequiredServices]

[-Include <String[]>]

[-Exclude <String[]>]

[<CommonParameters>]

PowerShell

Get-Service

[-ComputerName <String[]>]

[-DependentServices]

[-RequiredServices]

-DisplayName <String[]>

[-Include <String[]>]

[-Exclude <String[]>]

[<CommonParameters>]

PowerShell

Get-Service

[-ComputerName <String[]>]

[-DependentServices]

[-RequiredServices]

[-Include <String[]>]

[-Exclude <String[]>]

[-InputObject <ServiceController[]>]

[<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. By default, when Get-
Service is run without
parameters, all the local computer's services are returned.

You can direct this cmdlet to get only particular services by specifying the service name
or the
display name of the services, or you can pipe service objects to this cmdlet.

Examples

Example 1: Get all services on the computer


This example gets all of the services on the computer. It behaves as though you typed
Get-Service * . The default display shows the status, service name, and display name of

each
service.

PowerShell

Get-Service

Example 2: Get services that begin with a search string


This example retrieves services with service names that begin with WMI (Windows
Management
Instrumentation).

PowerShell

Get-Service "wmi*"

Example 3: Display services that include a search string


This example displays services with a display name that includes the word network .
Searching the
display name finds network-related services even when the service name
doesn't include Net , such as
xmlprov, the Network Provisioning Service.

PowerShell

Get-Service -Displayname "*network*"


Example 4: Get services that begin with a search string
and an exclusion
This example only gets the services with service names that begin with win , except for
the WinRM
service.

PowerShell

Get-Service -Name "win*" -Exclude "WinRM"

Example 5: Display services that are currently active


This example displays only the services with a status of Running .

PowerShell

Get-Service | Where-Object {$_.Status -eq "Running"}

Get-Service gets all the services on the computer and sends the objects down the

pipeline. The
Where-Object cmdlet, 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: Get the services on a remote computer


PowerShell

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: List the services on the local computer that


have dependent services
This example gets services that have dependent services.

PowerShell

Get-Service |

Where-Object {$_.DependentServices} |

Format-List -Property Name, DependentServices, @{

Label="NoOfDependentServices"; Expression={$_.dependentservices.count}

Name : AudioEndpointBuilder

DependentServices : {AudioSrv}

NoOfDependentServices : 1

Name : Dhcp

DependentServices : {WinHttpAutoProxySvc}

NoOfDependentServices : 1

...

The Get-Service cmdlet gets all the services on the computer and sends the objects
down the
pipeline. The Where-Object cmdlet selects the services whose
DependentServices property isn't
null.

The results are sent down the pipeline to the Format-List cmdlet. The Property
parameter
displays the name of the service, the name of the dependent services, and a
calculated property that
displays the number of dependent services for each service.

Example 8: Sort services by property value


This example 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 . For more information, see
ServiceControllerStatus.

To list running services first, use the Descending parameter of the Sort-Object cmdlet.

PowerShell

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

Example 9: Get services on multiple computers


PowerShell

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)

This command uses the Get-Service cmdlet to run a Get-Service Winrm command on
two remote
computers and the local computer ( localhost ).

The 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: Get the dependent services of a service


This example gets the services that the WinRM service requires. The value of the
service's
ServicesDependedOn property is returned.

PowerShell

Get-Service "WinRM" -RequiredServices

Example 11: Get a service through the pipeline operator


This example gets the WinRM service on the local computer. The service name string,
enclosed in
quotation marks, is sent down the pipeline to Get-Service .

PowerShell

"WinRM" | Get-Service

Parameters
-ComputerName

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 (FQDN) 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.

Type: String[]

Aliases: Cn

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-DependentServices

Indicates that this cmdlet gets only the services that depend upon the specified
service.

Type: SwitchParameter

Aliases: DS

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-DisplayName

Specifies, as a string array, the display names of services to be retrieved. Wildcards


are
permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Exclude

Specifies, as a string array, a service or services that this cmdlet excludes from the
operation.
The value of this parameter qualifies the Name parameter. Enter a name
element or pattern, such
as s* . Wildcards are permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Include

Specifies, as a string array, a service or services that this cmdlet includes in the
operation. The
value of this parameter qualifies the Name parameter. Enter a name
element or pattern, such as
s* . Wildcards are permitted.

Type: String[]

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: True

-InputObject

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 pipe a
service object to this cmdlet.

Type: ServiceController[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies the service names of services to be retrieved. Wildcards are permitted.

Type: String[]

Aliases: ServiceName

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-RequiredServices

Indicates that this cmdlet gets only the services that this service requires. This
parameter gets
the value of the ServicesDependedOn property of the service.

Type: SwitchParameter

Aliases: SDO, ServicesDependedOn

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: True

Inputs
ServiceController

You can pipe a service object to this cmdlet.

String

You can pipe a service name to this cmdlet.

Outputs
ServiceController

This cmdlet returns objects that represent the services on the computer.

Notes
Windows PowerShell includes the following aliases for Get-Service :

gsv

This cmdlet can display services only when the current user has permission to see them.
If this
cmdlet 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 .

Related Links
New-Service
Restart-Service
Resume-Service
Set-Service
Start-Service
Stop-Service
Suspend-Service
Get-TimeZone
Reference
Module: Microsoft.PowerShell.Management

Gets the current time zone or a list of available time zones.

Syntax
PowerShell

Get-TimeZone

[[-Name] <String[]>]

[<CommonParameters>]

PowerShell

Get-TimeZone

-Id <String[]>

[<CommonParameters>]

PowerShell

Get-TimeZone

[-ListAvailable]

[<CommonParameters>]

Description
The Get-TimeZone cmdlet gets the current time zone or a list of available time zones.

Examples

Example 1: Get the current time zone


PowerShell

Get-TimeZone

This command gets the current time zone.


Example 2: Get time zones that match a specified string
PowerShell

Get-TimeZone -Name "*pac*"

Pacific Standard Time (Mexico)

(UTC-08:00) Pacific Time (US & Canada)

Pacific Standard Time

SA Pacific Standard Time

Pacific SA Standard Time

West Pacific Standard Time

Central Pacific Standard Time

This command gets all time zones that match the specified wildcard.

Example 3: Get all available time zones


PowerShell

Get-TimeZone -ListAvailable

This command gets all available time zones.

Parameters
-Id

Specifies, as a string array, the ID or IDs of the time zones that this cmdlet gets.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False


-ListAvailable

Indicates that this cmdlet gets all available time zones.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Name

Specifies, as a string array, the name or names of the time zones that this cmdlet
gets.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

Inputs
String[]

Outputs
TimeZoneInfo[]

Notes
Windows PowerShell includes the following aliases for Get-TimeZone :

gtz

Related Links
Set-TimeZone
Get-Transaction
Reference
Module: Microsoft.PowerShell.Management

Gets the current (active) transaction.

Syntax
PowerShell

Get-Transaction []

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, this cmdlet
shows the
transaction that was most recently active in the session.

This cmdlet is one of a set of cmdlets that support the transactions feature in Windows
PowerShell.
For more information, see about_Transactions.

Examples

Example 1: Get the current transaction


PowerShell

Start-Transaction

Get-Transaction

RollbackPreference SubscriberCount Status

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

Error 1 Active
This command uses the Get-Transaction cmdlet to get the current transaction.

Example 2: Show the properties and methods of the


transaction object
PowerShell

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;}

This command uses the Get-Member cmdlet to show the properties and methods of the
transaction
object.

Example 3: Show the property values of a rolled back


transaction
PowerShell

Set-Location hklm:\software

Start-Transaction

New-Item MyCompany -UseTransaction

Undo-Transaction

Get-Transaction

RollbackPreference SubscriberCount Status

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

Error 0 RolledBack

This command shows the property values of a transaction object for a transaction that
has been
rolled back.
Example 4: Show the property values of a committed
transaction
PowerShell

Set-Location hklm:\software

Start-Transaction

New-Item MyCompany -UseTransaction

Complete-Transaction

Get-Transaction

RollbackPreference SubscriberCount Status

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

Error 1 Committed

This command shows the property values of a transaction object for a transaction that
has been
committed.

Example 5: Start a transaction while another is in progress


PowerShell

Set-Location hklm:\software

Start-Transaction

New-Item MyCompany -UseTransaction

Start-Transaction

New-Item MyCompany2 -UseTransaction

Get-Transaction

RollbackPreference SubscriberCount Status

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

Error 2 Active

Complete-Transaction

Get-Transaction

RollbackPreference SubscriberCount Status

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

Error 1 Active

Complete-Transaction

Get-Transaction

RollbackPreference SubscriberCount Status

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

Error 1 Committed
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: Start an independent transaction while


another is in progress
PowerShell

Set-Location hklm:\software

Start-Transaction

Get-Transaction

RollbackPreference SubscriberCount IsRolledBack IsCommitted

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

Error 1 False False

Start-Transaction -Independent

Get-Transaction

RollbackPreference SubscriberCount IsRolledBack IsCommitted

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

Error 1 False False

Complete-Transaction

Get-Transaction

Complete-Transaction

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

Inputs
None

You cannot pipe objects to this cmdlet.

Outputs
PSTransaction

This cmdlet returns an object that represents the current transaction.

Related Links
Complete-Transaction
Start-Transaction
Undo-Transaction
Use-Transaction
New-Item
Get-WmiObject
Reference
Module: Microsoft.PowerShell.Management

Gets instances of Windows Management Instrumentation (WMI) classes or information


about the
available classes.

Syntax
PowerShell

Get-WmiObject

[-Class] <String>

[[-Property] <String[]>]

[-Filter <String>]

[-Amended]

[-DirectRead]

[-AsJob]

[-Impersonation <ImpersonationLevel>]

[-Authentication <AuthenticationLevel>]

[-Locale <String>]

[-EnableAllPrivileges]

[-Authority <String>]

[-Credential <PSCredential>]

[-ThrottleLimit <Int32>]

[-ComputerName <String[]>]

[-Namespace <String>]

[<CommonParameters>]

PowerShell

Get-WmiObject

[[-Class] <String>]

[-Recurse]

[-Amended]

[-List]

[-AsJob]

[-Impersonation <ImpersonationLevel>]

[-Authentication <AuthenticationLevel>]

[-Locale <String>]

[-EnableAllPrivileges]

[-Authority <String>]

[-Credential <PSCredential>]

[-ThrottleLimit <Int32>]

[-ComputerName <String[]>]

[-Namespace <String>]

[<CommonParameters>]
PowerShell

Get-WmiObject

[-Amended]

[-DirectRead]

-Query <String>

[-AsJob]

[-Impersonation <ImpersonationLevel>]

[-Authentication <AuthenticationLevel>]

[-Locale <String>]

[-EnableAllPrivileges]

[-Authority <String>]

[-Credential <PSCredential>]

[-ThrottleLimit <Int32>]

[-ComputerName <String[]>]

[-Namespace <String>]

[<CommonParameters>]

PowerShell

Get-WmiObject

[-Amended]

[-AsJob]

[-Impersonation <ImpersonationLevel>]

[-Authentication <AuthenticationLevel>]

[-Locale <String>]

[-EnableAllPrivileges]

[-Authority <String>]

[-Credential <PSCredential>]

[-ThrottleLimit <Int32>]

[-ComputerName <String[]>]

[-Namespace <String>]

[<CommonParameters>]

PowerShell

Get-WmiObject

[-Amended]

[-AsJob]

[-Impersonation <ImpersonationLevel>]

[-Authentication <AuthenticationLevel>]

[-Locale <String>]

[-EnableAllPrivileges]

[-Authority <String>]

[-Credential <PSCredential>]

[-ThrottleLimit <Int32>]

[-ComputerName <String[]>]

[-Namespace <String>]

[<CommonParameters>]
Description
Starting in PowerShell 3.0, this cmdlet has been superseded by Get-CimInstance .

The Get-WmiObject cmdlet gets instances of WMI classes or information about the
available WMI
classes. To specify a remote computer, use the ComputerName
parameter. 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 Windows PowerShell remoting 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 or is not configured for remoting in
Windows PowerShell.

Beginning in Windows PowerShell 3.0, the __Server property of the object that Get-
WmiObject
returns has a PSComputerName alias. This makes it easier to include the

source computer name in


output and reports.

Examples

Example 1: Get processes on the local computer


This example get the processes on the local computer.

PowerShell

Get-WmiObject -Class Win32_Process

Example 2: Gets services on a remote computer


This example gets the services on a remote computer. The ComputerName parameter
specifies the IP
address of a remote computer. By default, the current user account must
be a member of the
Administrators group on the remote computer.

PowerShell

Get-WmiObject -Class Win32_Service -ComputerName 10.1.4.62


Example 3: Get WMI classes in the root or default
namespace of the local computer
This example gets the WMI classes in the root or default namespace of the local
computer.

PowerShell

Get-WmiObject -Namespace "root/default" -List

Example 4: Get a named service on multiple computers


This example gets the WinRM service on the computers specified by the value of the
ComputerName
parameter.

PowerShell

Get-WmiObject -Query "select * from win32_service where name='WinRM'" -


ComputerName Server01, Server02 |
Format-List -Property PSComputerName, Name, ExitCode, Name, ProcessID,
StartMode, State, Status

PSComputerName : SERVER01

Name : WinRM

ExitCode : 0

Name : WinRM

ProcessID : 844

StartMode : Auto

State : Running

Status : OK

PSComputerName : SERVER02

Name : WinRM

ExitCode : 0

Name : WinRM

ProcessID : 932

StartMode : Auto

State : Running

Status : OK

A pipeline operator ( | ) sends the output to the Format-List cmdlet, which adds the
PSComputerName property to the default output. PSComputerName is an alias of the
__Server property of the objects that Get-WmiObject returns. This alias was introduced in
PowerShell 3.0.

Example 5: Stop a service on a remote computer


This example stops the WinRM service on a remote computer. Get-WmiObject gets the
instance of the
WinRM service object on Server01. Then, it invokes the StopService
method of the
Win32_Service WMI class on that object.

PowerShell

(Get-WmiObject -Class Win32_Service -Filter "name='WinRM'" -ComputerName


Server01).StopService()

This is equivalent to using the Stop-Service cmdlet.

Example 6: Get the BIOS on the local computer


This example gets the BIOS information from the local computer. The Property
parameter of the
Format-List cmdlet is used to display all properties of the returned
object in a list. By default,
only the subset of properties defined in the Types.ps1xml
configuration file are displayed.

PowerShell

Get-WmiObject -Class Win32_Bios | Format-List -Property *

Status : OK

Name : Phoenix ROM BIOS PLUS Version 1.10 A05

Caption : Phoenix ROM BIOS PLUS Version 1.10 A05

SMBIOSPresent : True

__GENUS : 2

__CLASS : Win32_BIOS

__SUPERCLASS : CIM_BIOSElement

__DYNASTY : CIM_ManagedSystemElement

__RELPATH : Win32_BIOS.Name="Phoenix ROM BIOS PLUS Version 1.10

__PROPERTY_COUNT : 27

__DERIVATION : {CIM_BIOSElement, CIM_SoftwareElement,


CIM_LogicalElement,

__SERVER : Server01

__NAMESPACE : root\cimv2

__PATH : \\SERVER01\root\cimv2:Win32_BIOS.Name="Phoenix ROM


BIOS

BiosCharacteristics : {7, 9, 10, 11...}

BIOSVersion : {DELL - 15, Phoenix ROM BIOS PLUS Version 1.10


A05}

BuildNumber :

CodeSet :

CurrentLanguage : en|US|iso8859-1

Description : Phoenix ROM BIOS PLUS Version 1.10 A05

IdentificationCode :

InstallableLanguages : 1

InstallDate :

LanguageEdition :

ListOfLanguages : {en|US|iso8859-1}

Manufacturer : Dell Inc.


OtherTargetOS :

PrimaryBIOS : True

ReleaseDate : 20101103000000.000000+000

SerialNumber : 8VDM9P1

SMBIOSBIOSVersion : A05

SMBIOSMajorVersion : 2

SMBIOSMinorVersion : 6

SoftwareElementID : Phoenix ROM BIOS PLUS Version 1.10 A05

SoftwareElementState : 3

TargetOperatingSystem : 0

Version : DELL - 15

Scope : System.Management.ManagementScope

Path : \\SERVER01\root\cimv2:Win32_BIOS.Name="Phoenix ROM


BIOS

Options : System.Management.ObjectGetOptions

ClassPath : \\JUNE-PC\root\cimv2:Win32_BIOS

Properties : {BiosCharacteristics, BIOSVersion, BuildNumber,


Caption...}

SystemProperties : {__GENUS, __CLASS, __SUPERCLASS, __DYNASTY...}

Qualifiers : {dynamic, Locale, provider, UUID}

Site :

Container :

Example 7: Get the services on a remote computer


This example uses the Credential parameter of the Get-WmiObject cmdlet to get the
services on
a remote computer. The value of the Credential parameter is a user account
name. The user is
prompted for a password.

PowerShell

Get-WmiObject Win32_Service -Credential FABRIKAM\administrator -ComputerName


Fabrikam

7 Note

Credentials cannot be used when targeting the local computer.

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.

Type: SwitchParameter

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 with the
ComputerName parameter, 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. 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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Authentication

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

Type: AuthenticationLevel

Accepted values: Default, None, Connect, Call, Packet, PacketIntegrity,


PacketPrivacy, Unchanged

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Authority

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.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-Class

Specifies the name of a WMI class. When this parameter is used, the cmdlet retrieves
instances of
the WMI class.

Type: String

Aliases: ClassName

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ComputerName

Specifies the target computer for the management operation. Enter a fully qualified
domain name
(FQDN), a NetBIOS name, or an IP address. When the remote
computer is in a different domain than the
local computer, the fully qualified domain
name is required.

The default is the local computer. To specify the local computer, such as in a list of
computer
names, use localhost , the local computer name, or a dot ( . ).

When specifying a remote computer, your current account or the one you specify
with the
Credential parameter must have appropriate permissions to access the
information.

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.

Type: String[]

Aliases: Cn

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-Credential

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 are prompted for a
password. Credentials cannot be used when targeting the
local computer.

Type: PSCredential

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.

Type: SwitchParameter

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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-Filter

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 have a DeviceID of
c: and services that have the
name 'WinRM' without using the Where keyword.

Get-WmiObject Win32_LogicalDisk -filter "DeviceID = 'c:' "

Get-WmiObject win32_service -filter "name='WinRM'"

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Impersonation

Specifies the impersonation level to use.

The acceptable values for this parameter are:

0 : Default. Reads the local registry for the default impersonation level. The
default is
usually set to 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.

Type: ImpersonationLevel

Accepted values: Default, Anonymous, Identify, Impersonate, Delegate

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-List

Gets the names of the WMI classes in the WMI repository namespace that is
specified by the
Namespace parameter.

If you specify the List parameter, but not the Namespace parameter, Get-WmiObject
uses
the Root\Cimv2 namespace by default. This cmdlet does not use the Default
Namespace registry
entry in the
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WBEM\Scripting registry key to determine

the
default namespace.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Locale

Specifies the preferred locale for WMI objects. Enter a value in MS_<LCID> format.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Namespace

When used with the Class parameter, the Namespace parameter specifies the WMI
repository
namespace where the specified WMI class is located. When used with the
List parameter, it
specifies the namespace from which to gather WMI class
information.
Type: String

Aliases: NS

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Property

Specifies the WMI class properties that this cmdlet gets information from. Enter the
property names.

Type: String[]

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Query

Runs the specified WMI Query Language (WQL) statement. This parameter does not
support event
queries.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Recurse

Searches the current namespace and all other namespaces for the class name that is
specified by the
Class parameter.

Type: SwitchParameter
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ThrottleLimit

Specifies the maximum number of WMI operations that can be executed


simultaneously. This parameter
is valid only when the AsJob parameter is used in the
command.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

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
Windows PowerShell includes the following aliases for Get-WmiObject :

gwmi
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. Or,
the default access control on
the WMI namespace of the remote repository can be
changed to give access rights to other accounts.

Only some of the properties of each WMI class are displayed by default. The set of
properties that
is displayed for each WMI class is specified in the Types.ps1xml
configuration file. To get all
properties of a WMI object, use the Get-Member or Format-
List cmdlets.

Related Links
Invoke-WmiMethod
Remove-WmiObject
Set-WmiInstance
Get-WSManInstance
Invoke-WSManAction
New-WSManInstance
Remove-WSManInstance
Invoke-Item
Reference
Module: Microsoft.PowerShell.Management

Performs the default action on the specified item.

Syntax
PowerShell

Invoke-Item

[-Path] <String[]>

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Credential <PSCredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

PowerShell

Invoke-Item

-LiteralPath <String[]>

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Credential <PSCredential>]

[-WhatIf]

[-Confirm]

[-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 PowerShell provider that
provides access to the data.

Examples
Example 1: Open a file
This command opens the file aliasApr04.doc in Microsoft Office Word. In this case,
opening in Word
is the default action for .doc files.

PowerShell

Invoke-Item "C:\Test\aliasApr04.doc"

Example 2: Open all files of a specific type


This command opens all of the Microsoft Office Excel spreadsheets in the
C:\Users\User1\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.

PowerShell

Invoke-Item "C:\Users\User1\Documents\*.xls"

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Credential

7 Note
This parameter is not supported by any providers installed with PowerShell.
To
impersonate another user, or elevate your credentials when running this cmdlet,
use Invoke-Command.

Type: PSCredential

Position: Named

Default value: Current user

Accept pipeline input: True

Accept wildcard characters: False

-Exclude

Specifies, as a string array, an item or items that this cmdlet excludes in the
operation. The value
of this parameter qualifies the Path parameter. Enter a path
element or pattern, such as
*.txt . Wildcard characters 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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Filter

Specifies a filter to qualify the Path parameter. The


FileSystem provider is the only
installed PowerShell provider that supports the use of filters. You can find the syntax
for the
FileSystem filter language in
about_Wildcards. Filters are more efficient
than
other parameters, because the provider applies them when the cmdlet gets the
objects rather
than having PowerShell filter the objects after they are retrieved.

Type: String

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: True

-Include

Specifies, as a string array, an item or items that this cmdlet includes in the
operation. The value
of this parameter qualifies the Path parameter. Enter a path
element or pattern, such as
"*.txt" . Wildcard characters 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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-LiteralPath

Specifies a path to one or more locations. 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
PowerShell not to interpret any characters
as escape sequences.

For more information, see about_Quoting_Rules.

Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Path
Specifies the path to the selected item.
Wildcard characters are permitted.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

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

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs.


The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String
You can pipe a string that contains a path to this cmdlet.

Outputs
None

This cmdlet returns no output of its own, but the items it invokes may return their own
output.

Notes
Windows PowerShell includes the following aliases for Invoke-Item :

ii

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

Related Links
Clear-Item
Copy-Item
Get-Item
Move-Item
New-Item
Remove-Item
Rename-Item
Set-Item
about_Providers
Invoke-WmiMethod
Reference
Module: Microsoft.PowerShell.Management

Calls WMI methods.

Syntax
PowerShell

Invoke-WmiMethod

[-Class] <String>

[-Name] <String>

[-ArgumentList <Object[]>]

[-AsJob]

[-Impersonation <ImpersonationLevel>]

[-Authentication <AuthenticationLevel>]

[-Locale <String>]

[-EnableAllPrivileges]

[-Authority <String>]

[-Credential <PSCredential>]

[-ThrottleLimit <Int32>]

[-ComputerName <String[]>]

[-Namespace <String>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Invoke-WmiMethod

-InputObject <ManagementObject>

[-Name] <String>

[-ArgumentList <Object[]>]

[-AsJob]

[-ThrottleLimit <Int32>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Invoke-WmiMethod

-Path <String>

[-Name] <String>

[-ArgumentList <Object[]>]

[-AsJob]

[-Impersonation <ImpersonationLevel>]

[-Authentication <AuthenticationLevel>]

[-Locale <String>]

[-EnableAllPrivileges]

[-Authority <String>]

[-Credential <PSCredential>]

[-ThrottleLimit <Int32>]

[-ComputerName <String[]>]

[-Namespace <String>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Invoke-WmiMethod

[-Name] <String>

[-AsJob]

[-Impersonation <ImpersonationLevel>]

[-Authentication <AuthenticationLevel>]

[-Locale <String>]

[-EnableAllPrivileges]

[-Authority <String>]

[-Credential <PSCredential>]

[-ThrottleLimit <Int32>]

[-ComputerName <String[]>]

[-Namespace <String>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Invoke-WmiMethod

[-Name] <String>

[-AsJob]

[-Impersonation <ImpersonationLevel>]

[-Authentication <AuthenticationLevel>]

[-Locale <String>]

[-EnableAllPrivileges]

[-Authority <String>]

[-Credential <PSCredential>]

[-ThrottleLimit <Int32>]

[-ComputerName <String[]>]

[-Namespace <String>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell
Invoke-WmiMethod

[-Name] <String>

[-AsJob]

[-Impersonation <ImpersonationLevel>]

[-Authentication <AuthenticationLevel>]

[-Locale <String>]

[-EnableAllPrivileges]

[-Authority <String>]

[-Credential <PSCredential>]

[-ThrottleLimit <Int32>]

[-ComputerName <String[]>]

[-Namespace <String>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Invoke-WmiMethod cmdlet calls the methods of Windows Management
Instrumentation (WMI)
objects.

New Common Information Model (CIM) cmdlets, introduced in Windows PowerShell 3.0,
perform the same
tasks as the WMI cmdlets. The CIM cmdlets comply with WS-
Management (WSMan) standards and with the
CIM standard, which enables the cmdlets
to use the same techniques to manage Windows computers and
those running other
operating systems. Instead of using Invoke-WmiMethod , consider using
Invoke-
CimMethod.

Examples

Example 1: List the required order of WMI objects


PowerShell

([wmiclass]'Win32_Volume').GetMethodParameters('Format')

__GENUS : 2

__CLASS : __PARAMETERS

__SUPERCLASS :

__DYNASTY : __PARAMETERS

__RELPATH :

__PROPERTY_COUNT : 6

__DERIVATION : {}

__SERVER :

__NAMESPACE :

__PATH :

ClusterSize : 0

EnableCompression : False

FileSystem : NTFS

Label :

QuickFormat : False

Version : 0

PSComputerName :

This command lists the required order of the objects. To invoke WMI in PowerShell 3.0
differs from
alternate methods, and requires that object values are entered in a specific
order.

Example 2: Start an instance of an application


PowerShell

([Wmiclass]'Win32_Process').GetMethodParameters('Create')

__GENUS : 2

__CLASS : __PARAMETERS

__SUPERCLASS :

__DYNASTY : __PARAMETERS

__RELPATH :

__PROPERTY_COUNT : 3

__DERIVATION : {}

__SERVER :

__NAMESPACE :

__PATH :

CommandLine :

CurrentDirectory :

ProcessStartupInformation :

PSComputerName :

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 : 11312

ReturnValue : 0

PSComputerName :
This command starts an instance of Notepad by calling the Create method of the
Win32_Process
class.

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 3: Rename a file


PowerShell

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

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.

The ReturnValue property is populated with a 0 if the command is completed.

Example 4: Passing an array of values using `-


ArgumentList`
An example using an array of objects $binSD followed by a $null value.

PowerShell

$acl = get-acl test.txt


$binSD = $acl.GetSecurityDescriptorBinaryForm()

Invoke-WmiMethod -class Win32_SecurityDescriptorHelper -Name BinarySDToSDDL


-ArgumentList $binSD, $null

Parameters
-ArgumentList

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. The Invoke-CimCommand
cmdlet does not have these limitations.

To determine the order in which to list those objects, run the GetMethodParameters()
method on the
WMI class, as illustrated in Example 1, near the end of this topic.

) Important

If the first value is an array that contains more than one element, a second value
of $null is
required. Otherwise, the command generates an error, such as
Unable to cast object of type 'System.Byte' to type 'System.Array'. . See
example 4 above.

Type: Object[]

Aliases: Args

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-AsJob

Indicates that this cmdlet 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.

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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Authentication

Specifies the authentication level to be used with the WMI connection. The
acceptable values for
this parameter 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.)

Type: AuthenticationLevel

Accepted values: Default, None, Connect, Call, Packet, PacketIntegrity,


PacketPrivacy, Unchanged

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-Authority

Specifies the authority to use to authenticate the WMI connection. You can specify
standard Windows
NT LAN Manager (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.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Class

Specifies the WMI class that contains a static method to call.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ComputerName

Specifies, as a string array, the computers that this cmdlet runs the command on. 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 even if your computer is not configured to run remote
commands.

Type: String[]

Aliases: Cn

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Credential

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.

Type: PSCredential

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-EnableAllPrivileges

Indicates that this cmdlet enables all the privileges of the current user before the
command makes
the WMI call.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Impersonation

Specifies the impersonation level to use. The acceptable values for this parameter
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.)

Type: ImpersonationLevel

Accepted values: Default, Anonymous, Identify, Impersonate, Delegate

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies a ManagementObject object to use as input. When this parameter is used,


all other
parameters except the Flag and Argument parameters are ignored.

Type: ManagementObject
Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Locale

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.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Name

Specifies the name of the method to be invoked. This parameter is mandatory and
cannot be null or
empty.

Type: String

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Namespace

When used with the Class parameter, this parameter specifies the WMI repository
namespace where
the referenced WMI class or object is located.

Type: String

Aliases: NS

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Path

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.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ThrottleLimit

Specifies a throttle 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.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named
Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

This cmdlet does not accept any input.

Outputs
None

This cmdlet does not generate any output.

Related Links
Get-WSManInstance
Invoke-WSManAction
New-WSManInstance
Remove-WSManInstance
Get-WmiObject
Remove-WmiObject
Set-WmiInstance
Join-Path
Reference
Module: Microsoft.PowerShell.Management

Combines a path and a child path into a single path.

Syntax
PowerShell

Join-Path

[-Path] <String[]>

[-ChildPath] <String>

[-Resolve]

[-Credential <PSCredential>]

[-UseTransaction]

[<CommonParameters>]

Description
The Join-Path cmdlet combines a path and child-path into a single path.
The provider
supplies the path delimiters.

Examples

Example 1: Combine a path with a child path


PowerShell

PS C:\> Join-Path -Path "path" -ChildPath "childpath"

path\childpath

This command uses Join-Path to combine a path with a childpath.

Since the command is executed from the FileSystem provider, it provides the \
delimiter to join the paths.
Example 2: Combine paths that already contain directory
separators
PowerShell

PS C:\> Join-Path -Path "path\" -ChildPath "\childpath"

path\childpath

Existing directory separators \ and handled so there is only one separator between
Path and ChildPath

Example 3: Display files and folders by joining a path with


a child path
PowerShell

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 4: Use Join-Path with the PowerShell registry


provider
PowerShell

PS HKLM:\> Join-Path -Path System -ChildPath *ControlSet* -Resolve

HKLM:\System\ControlSet001

HKLM:\System\CurrentControlSet

This command displays the registry keys in the HKLM\System registry subkey that include
ControlSet .

The Resolve parameter, attempts to resolve the joined path, including wildcards from
the current provider path HKLM:\
Example 5: Combine multiple path roots with a child path
PowerShell

Join-Path -Path C:, D:, E:, F: -ChildPath New

C:\New

D:\New

E:\New

F:\New

This command uses Join-Path to combine multiple path roots with a child path.

7 Note

The Drives specified by Path must exist or the join of that entry will fail.

Example 6: Combine the roots of a file system drive with


a child path
PowerShell

Get-PSDrive -PSProvider filesystem | ForEach-Object {$_.root} | Join-Path -


ChildPath "Subdir"

C:\Subdir

D:\Subdir

This command combines the roots of each PowerShell file system drive in the console
with the Subdir child path.

The command uses the Get-PSDrive cmdlet to get the PowerShell drives supported by
the FileSystem provider.
The ForEach-Object statement selects only the Root property of
the PSDriveInfo objects and combines it with the specified child path.

The output shows that the PowerShell drives on the computer included a drive mapped
to the C:\Program Files directory.

Parameters
-ChildPath
Specifies the elements to append to the value of the Path parameter.
Wildcards are
permitted.
The ChildPath parameter is required, although the parameter name
("ChildPath") is optional.

Type: String

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-Credential

7 Note

This parameter is not supported by any providers installed with PowerShell.


To
impersonate another user, or elevate your credentials when running this cmdlet,
use Invoke-Command.

Type: PSCredential

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Path

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.

Type: String[]

Aliases: PSPath

Position: 0
Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-Resolve

Indicates that this cmdlet should attempt to resolve the joined path from the current
provider.

If wildcards are used, the cmdlet returns all paths that match the joined path.
If no wildcards are used, the cmdlet will error if the path does not exist.

Type: SwitchParameter

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.

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a string that contains a path to this cmdlet.


Outputs
String

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

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

Related Links
Convert-Path
Resolve-Path
Split-Path
Test-Path
Get-PSProvider
Get-ChildItem
Get-PSDrive
Limit-EventLog
Reference
Module: Microsoft.PowerShell.Management

Sets the event log properties that limit the size of the event log and the age of its
entries.

Syntax
PowerShell

Limit-EventLog

[-LogName] <String[]>

[-ComputerName <String[]>]

[-RetentionDays <Int32>]

[-OverflowAction <OverflowAction>]

[-MaximumSize <Int64>]

[-WhatIf]

[-Confirm]

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

Examples

Example 1: Increase the size of an event log


PowerShell

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 bytes (20 KB).

Example 2: Retain an event log for a specified duration


PowerShell

Limit-EventLog -LogName Security -ComputerName "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: Change the overflow action of all event logs


PowerShell

$Logs = Get-EventLog -List | ForEach {$_.log}

Limit-EventLog -OverflowAction OverwriteOlder -LogName $Logs

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

This example changes 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.

Parameters
-ComputerName
Specifies remote computers. The default is the local computer.

Type the NetBIOS name, an Internet Protocol (IP) address, or a fully qualified domain
name (FQDN) 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.

Type: String[]

Aliases: CN

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-LogName

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.

Type: String[]

Aliases: LN
Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-MaximumSize

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.

Type: Int64

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-OverflowAction

Specifies what happens when the event log reaches its maximum size.

The acceptable values for this parameter 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.

Type: OverflowAction

Aliases: OFA

Accepted values: OverwriteOlder, OverwriteAsNeeded, DoNotOverwrite


Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RetentionDays

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.

Type: Int32

Aliases: MRD

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You cannot pipe input to this cmdlet.


Outputs
None

This cmdlet does not generate any output.

Notes
To use this cmdlet on Windows Vista and later versions of Windows, open
Windows PowerShell with
the Run as administrator option.

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

Related Links
Clear-EventLog
Get-EventLog
Limit-EventLog
New-EventLog
Remove-EventLog
Show-EventLog
Write-EventLog
Move-Item
Reference
Module: Microsoft.PowerShell.Management

Moves an item from one location to another.

Syntax
PowerShell

Move-Item

[-Path] <String[]>

[[-Destination] <String>]

[-Force]

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-PassThru]

[-Credential <PSCredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

PowerShell

Move-Item

-LiteralPath <String[]>

[[-Destination] <String>]

[-Force]

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-PassThru]

[-Credential <PSCredential>]

[-WhatIf]

[-Confirm]

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

Examples

Example 1: Move a file to another directory and rename it


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 .

PowerShell

Move-Item -Path C:\test.txt -Destination E:\Temp\tst.txt

Example 2: Move a directory and its contents to another


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

PowerShell

Move-Item -Path C:\Temp -Destination C:\Logs

Example 3: Move all files of a specified extension from


the current directory to another directory
This command moves all of the text files ( *.txt ) in the current directory (represented by
a dot
( . )) to the C:\Logs directory.

PowerShell

Move-Item -Path .\*.txt -Destination C:\Logs


Example 4: Recursively move all files of a specified
extension from the current directory to another directory
This command moves all of the text files from the current directory and all
subdirectories,
recursively, to the C:\TextFiles directory.

PowerShell

Get-ChildItem -Path ".\*.txt" -Recurse | Move-Item -Destination


"C:\TextFiles"

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 that are to be 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 .

7 Note

In Windows PowerShell 2.0, when using the Recurse parameter of the Get-
ChildItem cmdlet, the
value of the Path parameter must be a container. Use the

Include parameter to specify the


*.txt file name extension filter
( Get-ChildItem -
Path .\* -Include *.txt -Recurse | Move-Item -Destination C:\TextFiles ).

Example 5: Move registry keys and values to another key


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.

PowerShell

Move-Item "HKLM:\software\mycompany\*" "HKLM:\software\mynewcompany"

Example 6: Move a directory and its contents to a


subdirectory of the specified directory
This command moves the Logs[Sept`06] directory (and its contents) into the
Logs[2006]
directory.

PowerShell

Move-Item -LiteralPath 'Logs[Sept`06]' -Destination 'Logs[2006]'

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 must also be enclosed in single quotation marks because it
includes
brackets that can be misinterpreted.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


-Credential

7 Note

This parameter is not supported by any providers installed with PowerShell.


To
impersonate another user, or elevate your credentials when running this cmdlet,
use Invoke-Command.

Type: PSCredential

Position: Named

Default value: Current user

Accept pipeline input: True

Accept wildcard characters: False

-Destination

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.

Type: String

Position: 1

Default value: Current directory

Accept pipeline input: True

Accept wildcard characters: True

-Exclude

Specifies, as a string array, an item or items that this cmdlet excludes in the
operation. The value
of this parameter qualifies the Path parameter. Enter a path
element or pattern, such as
*.txt . Wildcard characters 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.
Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Filter

Specifies a filter to qualify the Path parameter. The


FileSystem provider is the only
installed PowerShell provider that supports the use of filters. You can find the syntax
for the
FileSystem filter language in
about_Wildcards. Filters are more efficient
than
other parameters, because the provider applies them when the cmdlet gets the
objects rather
than having PowerShell filter the objects after they are retrieved.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Force

Forces the command to run without asking for user confirmation. Implementation
varies from provider
to provider. For more information, see
about_Providers.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Include

Specifies, as a string array, an item or items that this cmdlet includes in the
operation. The value
of this parameter qualifies the Path parameter. Enter a path
element or pattern, such as
*.txt . Wildcard characters 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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-LiteralPath

Specifies the path to the current location of the items. 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 PowerShell not
to interpret any characters as escape sequences.

For more information, see


about_Quoting_Rules.

Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-PassThru

Returns an object representing the moved item. By default, this cmdlet does not
generate any output.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False


Accept wildcard characters: False

-Path

Specifies the path to the current location of the items. The default is the current
directory.
Wildcard characters are permitted.

Type: String[]

Position: 0

Default value: Current directory

Accept pipeline input: True

Accept wildcard characters: True

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

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False


Accept wildcard characters: False

Inputs
String

You can pipe a string that contains a path to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

PSObject

When you use the PassThru parameter, this cmdlet returns an object representing the
moved item.

Notes
Windows PowerShell includes the following aliases for Move-Item :

mi

move

mv

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

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

Related Links
Clear-Item
Copy-Item
Get-Item
Invoke-Item
New-Item
Remove-Item
Rename-Item
Set-Item
about_Providers
Move-ItemProperty
Reference
Module: Microsoft.PowerShell.Management

Moves a property from one location to another.

Syntax
PowerShell

Move-ItemProperty

[-Path] <String[]>

[-Name] <String[]>

[-Destination] <String>

[-PassThru]

[-Force]

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Credential <PSCredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

PowerShell

Move-ItemProperty

-LiteralPath <String[]>

[-Name] <String[]>

[-Destination] <String>

[-PassThru]

[-Force]

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Credential <PSCredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

Description
The Move-ItemProperty cmdlet moves a property of an item from one item to another
item.
For instance, 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.

Examples

Example 1: Move a registry value and its data to another


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

PowerShell

Move-ItemProperty "HKLM:\Software\MyCompany\MyApp" -Name "Version" -


Destination "HKLM:\Software\MyCompany\NewApp"

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Credential

7 Note

This parameter is not supported by any providers installed with PowerShell.


To
impersonate another user, or elevate your credentials when running this cmdlet,
use Invoke-Command.

Type: PSCredential

Position: Named

Default value: Current user

Accept pipeline input: True

Accept wildcard characters: False

-Destination

Specifies the path to the destination location.

Type: String

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Exclude

Specifies, as a string array, a property or property that this cmdlet excludes from the
operation.
The value of this parameter qualifies the Path parameter.
Enter a path
element or pattern, such as "*.txt".
Wildcard characters are permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Filter

Specifies a filter in the format or language of the provider.


The value of this
parameter qualifies the Path parameter.
The syntax of the filter, including the use of wildcard characters, depends on the
provider.
Filters are more efficient than other parameters, because the provider
applies them when the cmdlet gets the objects rather than having PowerShell filter
the objects after they are retrieved.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Force

Forces the command to run without asking for user confirmation.


Implementation
varies from provider to provider.
For more information, see about_Providers.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Include

Specifies, as a string array, a property or property that this cmdlet includes in the
operation.
The value of this parameter qualifies the Path parameter.
Enter a path
element or pattern, such as "*.txt".
Wildcard characters are permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-LiteralPath
Specifies the path to the current location of the property.
Unlike the Path parameter,
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 PowerShell not to interpret any characters as escape
sequences.

Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies the name of the property to be moved.

Type: String[]

Aliases: PSProperty

Position: 2

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-PassThru

Returns an object representing the item with which you are working.
By default, this
cmdlet does not generate any output.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-Path

Specifies the path to the current location of the property.


Wildcard characters are
permitted.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

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

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs.


The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


Inputs
String

You can pipe a string that contains a path to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

PSCustomObject

When you use the PassThru parameter, this cmdlet returns a PSCustomObject
representing the
moved item property.

Notes
Windows PowerShell includes the following aliases for Move-ItemProperty :

mp

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

Related Links
Clear-ItemProperty
Copy-ItemProperty
Get-ItemProperty
New-ItemProperty
Remove-ItemProperty
Rename-ItemProperty
Set-ItemProperty
about_Providers
New-EventLog
Reference
Module: Microsoft.PowerShell.Management

Creates a new event log and a new event source on a local or remote computer.

Syntax
PowerShell

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 .

Examples

Example 1 - create a new event log


This command creates the TestLog event log on the local computer and registers a new
source for
it.

PowerShell

New-EventLog -source TestApp -LogName TestLog -MessageResourceFile


C:\Test\TestApp.dll
Example 2 - add a new event source to an existing log
This command adds a new event source, NewTestApp , to the Application log on the
Server01 remote
computer.

PowerShell

$file = "C:\Program Files\TestApps\NewTestApp.dll"

New-EventLog -ComputerName Server01 -Source NewTestApp -LogName Application


-MessageResourceFile $file -CategoryResourceFile $file

The command requires that the NewTestApp.dll file is located on the Server01
computer.

Parameters
-CategoryResourceFile

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.

Type: String

Aliases: CRF

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ComputerName

Creates the new event logs on the specified computers. The default is the local
computer.

The NetBIOS name, IP address, or 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 PowerShell remoting. You can use the
ComputerName parameter of
Get-EventLog even if your computer is not configured
to run remote commands.

Type: String[]

Aliases: CN

Position: 3

Default value: Local computer

Accept pipeline input: False

Accept wildcard characters: False

-LogName

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.

Type: String

Aliases: LN

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-MessageResourceFile

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.

Type: String

Aliases: MRF
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ParameterResourceFile

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.

Type: String

Aliases: PRF

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Source

Specifies the names of the event log sources, such as application programs that write
to the event
log. This parameter is required.

Type: String[]

Aliases: SRC

Position: 2

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None
You cannot pipe input to this cmdlet.

Outputs
EventLogEntry

Notes
To use New-EventLog on Windows Vista and later versions of Windows, open 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
$env: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.

Related Links
Clear-EventLog
Get-EventLog
Get-WinEvent
Limit-EventLog
New-EventLog
Remove-EventLog
Show-EventLog
Write-EventLog
New-Item
Reference
Module: Microsoft.PowerShell.Management

Creates a new item.

Syntax
PowerShell

New-Item

[-Path] <string[]>

[-ItemType <string>]

[-Value <Object>]

[-Force]

[-Credential <pscredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

PowerShell

New-Item

[[-Path] <string[]>]

-Name <string>

[-ItemType <string>]

[-Value <Object>]

[-Force]

[-Credential <pscredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

PowerShell

New-Item

[-Path] <string[]>

-ConnectionURI <uri>

[-ItemType <string>]

[-Value <Object>]

[-Force]

[-Credential <pscredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[-OptionSet <hashtable>]

[-Authentication <AuthenticationMechanism>]

[-CertificateThumbprint <string>]

[-SessionOption <SessionOption>]

[-Port <int>]

[<CommonParameters>]

PowerShell

New-Item

[[-Path] <string[]>]

-Name <string>

[-ItemType <string>]

[-Value <Object>]

[-Force]

[-Credential <pscredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[-OptionSet <hashtable>]

[-Authentication <AuthenticationMechanism>]

[-CertificateThumbprint <string>]

[-SessionOption <SessionOption>]

[-ApplicationName <string>]

[-Port <int>]

[-UseSSL]

[<CommonParameters>]

PowerShell

New-Item

[-Path] <string[]>

[-ItemType <string>]

[-Value <Object>]

[-Force]

[-Credential <pscredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[-Options <ScopedItemOptions>]
[<CommonParameters>]

PowerShell

New-Item

[[-Path] <string[]>]

-Name <string>

[-ItemType <string>]

[-Value <Object>]

[-Force]

[-Credential <pscredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[-Options <ScopedItemOptions>]
[<CommonParameters>]

Description
The New-Item cmdlet creates a new item and sets its value. The types of items that can
be created
depend on the location of the item. For example, in the file system, New-Item
creates 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 it creates

a new
file, New-Item can add initial content to the file.

Examples

Example 1: Create a file in the current directory


This command creates a text file that is 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.

PowerShell

New-Item -Path . -Name "testfile1.txt" -ItemType "file" -Value "This is a


text string."

Example 2: Create a directory


This command creates a directory named "Logfiles" in the C: drive. The ItemType
parameter
specifies that the new item is a directory, not a file or other file system object.

PowerShell

New-Item -Path "c:\" -Name "logfiles" -ItemType "directory"

Example 3: Create a profile


This command creates a PowerShell profile in the path that is specified by the $profile
variable.

You can use profiles to customize 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 PowerShell stores a path and file name
for it.

In this command, the $profile variable represents the path of the file. ItemType
parameter
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.

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

PowerShell

New-Item -Path $profile -ItemType "file" -Force

7 Note

When you create a file using this method, the resulting file is encoded as UTF-8
without a
byte-order-mark (BOM).

Example 4: Create a directory in a different directory


This example 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 Path
parameter,
instead of being specified in the value of Name. As indicated by the syntax,
either command form
is valid.

PowerShell

New-Item -ItemType "directory" -Path "c:\ps-test\scripts"

Example 5: Create multiple files


This example creates files in two different directories. Because Path takes multiple
strings,
you can use it to create multiple items.

PowerShell

New-Item -ItemType "file" -Path "c:\ps-test\test.txt", "c:\ps-


test\Logs\test.log"

Example 6: Use wildcards to create files in multiple


directories
The New-Item cmdlet supports wildcards in the Path parameter. The following command
creates a
temp.txt file in all of the directories specified by the wildcards in the Path
parameter.

PowerShell

Get-ChildItem -Path C:\Temp\

Directory: C:\Temp

Mode LastWriteTime Length Name

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

d----- 5/15/2019 6:45 AM 1 One

d----- 5/15/2019 6:45 AM 1 Two

d----- 5/15/2019 6:45 AM 1 Three

New-Item -Path C:\Temp\* -Name temp.txt -ItemType File | Select-Object


FullName

FullName

--------

C:\Temp\One\temp.txt

C:\Temp\Three\temp.txt

C:\Temp\Two\temp.txt

The Get-ChildItem cmdlet shows three directories under the C:\Temp directory. Using
wildcards
the New-Item cmdlet creates a temp.txt file in all of the directories under the
current
directory. The New-Item cmdlet outputs the items you created, which is piped to
Select-Object
to verify the paths of the newly created files.

Example 7: Create a symbolic link to a file or folder


This example creates a symbolic link to the Notice.txt file in the current folder.
PowerShell

$link = New-Item -ItemType SymbolicLink -Path .\link -Target .\Notice.txt

$link | Select-Object LinkType, Target

LinkType Target

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

SymbolicLink {.\Notice.txt}

In this example, Target is an alias for the Value parameter. The target of the symbolic
link
must be a fully-qualified path.

Example 8: Use the -Force parameter to attempt to


recreate folders
This example creates a folder with a file inside. Then, attempts to create the same folder
using
-Force . It will not overwrite the folder but simply return the existing folder object
with the
file created intact.

PowerShell

PS> New-Item -Path .\TestFolder -ItemType Directory

PS> New-Item -Path .\TestFolder\TestFile.txt -ItemType File

PS> New-Item -Path .\TestFolder -ItemType Directory -Force

Directory: C:\

Mode LastWriteTime Length Name

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

d----- 5/1/2020 8:03 AM TestFolder

PS> Get-ChildItem .\TestFolder\

Directory: C:\TestFolder

Mode LastWriteTime Length Name

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

-a---- 5/1/2020 8:03 AM 0 TestFile.txt

Example 9: Use the -Force parameter to overwrite


existing files
This example creates a file with a value and then recreates the file using -Force . This
overwrites
The existing file and it will lose it's content as you can see by the length
property
PowerShell

PS> New-Item ./TestFile.txt -ItemType File -Value 'This is just a test file'

Directory: C:\Source\Test

Mode LastWriteTime Length Name

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

-a---- 5/1/2020 8:32 AM 24 TestFile.txt

New-Item ./TestFile.txt -ItemType File -Force

Directory: C:\Source\Test

Mode LastWriteTime Length Name

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

-a---- 5/1/2020 8:32 AM 0 TestFile.txt

7 Note

When using New-Item with the -Force switch to create registry keys, the command
will behave
the same as when overwriting a file. If the registry key already exists,
the key and all
properties and values will be overwritten with an empty registry key.

Parameters
-ApplicationName

This is a dynamic parameter made available by the WSMan provider. The WSMan
provider and
this parameter are only available on Windows.

Specifies the application name in the connection. The default value of the
ApplicationName
parameter is WSMAN.

For more information, see New-WSManInstance.

Type: String

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Authentication
This is a dynamic parameter made available by the WSMan provider. The WSMan
provider and
this parameter are only available on Windows.

Specifies the authentication mechanism to be used at the server.

For more information, see New-WSManInstance.

Type: Microsoft.WSMan.Management.AuthenticationMechanism

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-CertificateThumbprint

This is a dynamic parameter made available by the WSMan provider. The WSMan
provider and
this parameter are only available on Windows.

Specifies the digital public key certificate (X509) of a user account that has
permission to perform
this WSMan action. Enter the certificate thumbprint of the
certificate.

For more information, see New-WSManInstance.

Type: String

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False


Accept pipeline input: False

Accept wildcard characters: False

-ConnectionURI

This is a dynamic parameter made available by the WSMan provider. The WSMan
provider and
this parameter are only available on Windows.

Specifies the connection endpoint for WSMan.

For more information, see New-WSManInstance.

Type: Uri

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Credential

7 Note

This parameter isn't supported by any providers installed with PowerShell. To


impersonate another
user or elevate your credentials when running this cmdlet,
use Invoke-Command .

Type: PSCredential

Position: Named

Default value: Current user

Accept pipeline input: True

Accept wildcard characters: False

-Force

Forces this cmdlet to create an item that writes over an existing read-only item.
Implementation
varies from provider to provider. Even using the Force parameter,
the cmdlet can't override
security restrictions.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ItemType

Specifies the provider-specified type of the new item. The available values of this
parameter depend
on the current provider you are using.

If your location is in a FileSystem drive, the following values are allowed:

File
Directory
SymbolicLink
Junction
HardLink

When you create a file using this method, the resulting file is encoded as UTF-8
without a
byte-order-mark (BOM).

In a Certificate drive, these are the values you can specify:

Certificate Provider
Certificate
Store
StoreLocation

For more information see about_Providers.

Type: String

Aliases: Type

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False


-Name

Specifies the name of the new item. You can specify the name of the new item in the
Name or
Path parameter value, and you can specify the path of the new item in
Name or Path
value. Items names passed using the Name parameter are created
relative to the value of the
Path parameter.

Type: String

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Options

This is a dynamic parameter made available by the Alias provider. For more
information, see
New-Alias.

Specifies the value of the Options property of an alias.

Valid values are:

None : The alias has no constraints (default value)

ReadOnly : The alias can be deleted but can't be changed without using the

Force parameter
Constant : The alias can't be deleted or changed

Private : The alias is available only in the current scope


AllScope : The alias is copied to any new scopes that are created

Unspecified : The option isn't specified

Type: ScopedItemOptions

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-OptionSet
This is a dynamic parameter made available by the WSMan provider. The WSMan
provider and
this parameter are only available on Windows.

Passes a set of switches to a service to modify or refine the nature of the request.

For more information, see New-WSManInstance.

Type: Hashtable

Aliases: OS

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Path

Specifies the path of the location of the new item. The default is the current location
when
Path is omitted. You can specify the name of the new item in Name, or include
it in
Path. Items names passed using the Name parameter are created relative to the
value of the
Path parameter.

For this cmdlet, the Path parameter works like the LiteralPath parameter of other
cmdlets.
Wildcard characters are not interpreted. All characters are passed to the
location's provider. The
provider may not support all characters. For example, you
can't create a filename that contains an
asterisk ( * ) character.

Type: String[]

Position: 0

Default value: Current location

Accept pipeline input: True

Accept wildcard characters: False

-Port

This is a dynamic parameter made available by the WSMan provider. The WSMan
provider and
this parameter are only available on Windows.

Specifies the port to use when the client connects to the WinRM service.
For more information, see New-WSManInstance.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-SessionOption

This is a dynamic parameter made available by the WSMan provider. The WSMan
provider and
this parameter are only available on Windows.

Defines a set of extended options for the WS-Management session.

For more information, see New-WSManInstance.

Type: Microsoft.WSMan.Management.SessionOption

Aliases: SO

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-UseSSL

This is a dynamic parameter made available by the WSMan provider. The WSMan
provider and
this parameter are only available on Windows.

Specifies that the Secure Sockets Layer (SSL) protocol should be used to establish a
connection to
the remote computer. By default, SSL isn't used.

For more information, see New-WSManInstance.

Type: SwitchParameter

Position: Named

Default value: None


Accept pipeline input: True

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.

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Value

Specifies the value of the new item. You can also pipe a value to New-Item .

Type: Object

Aliases: Target

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet isn't run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False


Accept pipeline input: False

Accept wildcard characters: False

Inputs
Object

You can pipe a value for the new item to this cmdlet.

Outputs
Object

This cmdlet returns the item that it creates.

Notes
Windows PowerShell includes the following aliases for New-Item :

ni

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

Related Links
Clear-Item
Copy-Item
Get-Item
Invoke-Item
Move-Item
Remove-Item
Rename-Item
Set-Item
about_Providers
New-ItemProperty
Reference
Module: Microsoft.PowerShell.Management

Creates a new property for an item and sets its value.

Syntax
PowerShell

New-ItemProperty

[-Path] <String[]>

[-Name] <String>

[-PropertyType <String>]

[-Value <Object>]

[-Force]

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Credential <PSCredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

PowerShell

New-ItemProperty

-LiteralPath <String[]>

[-Name] <String>

[-PropertyType <String>]

[-Value <Object>]

[-Force]

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Credential <PSCredential>]

[-WhatIf]

[-Confirm]

[-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, modify the Types.ps1xml file.

Examples

Example 1: Add a registry entry


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

PowerShell

New-ItemProperty -Path "HKLM:\Software\MyCompany" -Name "NoOfEmployees" -


Value 822

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

Example 2: Add a registry entry to a key


This command adds a new registry entry to a registry key. To specify the key, it uses a
pipeline
operator ( | ) to send an object that represents the key to New-ItemProperty .
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 New-ItemProperty ,
which adds the new
registry entry ( NoOfLocations ), and its value ( 3 ), to the MyCompany
key.

PowerShell

Get-Item -Path "HKLM:\Software\MyCompany" | New-ItemProperty -Name


NoOfLocations -Value 3

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.

Example 3: Create a MultiString value in the registry using


a Here-String
This example creates a MultiString value using a Here-String.

PowerShell

$newValue = New-ItemProperty -Path "HKLM:\SOFTWARE\ContosoCompany\" -Name


'HereString' -PropertyType MultiString -Value @"

This is text which contains newlines

It can also contain "quoted" strings

"@

$newValue.multistring

This is text which contains newlines

It can also contain "quoted" strings

Example 4: Create a MultiString value in the registry


using an array
The example shows how to use an array of values to create the MultiString value.

PowerShell

$newValue = New-ItemProperty -Path "HKLM:\SOFTWARE\ContosoCompany\" -Name


'MultiString' -PropertyType MultiString -Value ('a','b','c')

$newValue.multistring[0]

a
Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Credential

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 are prompted for a
password.

7 Note

This parameter is not supported by any providers installed with PowerShell.


To
impersonate another user, or elevate your credentials when running this cmdlet,
use Invoke-Command.

Type: PSCredential

Position: Named

Default value: Current user

Accept pipeline input: True

Accept wildcard characters: False

-Exclude
Specifies, as a string array, a property or property that this cmdlet excludes from the
operation.
The value of this parameter qualifies the Path parameter.
Enter a path
element or pattern, such as *.txt .
Wildcard characters are permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Filter

Specifies a filter in the format or language of the provider.


The value of this
parameter qualifies the Path parameter.

The syntax of the filter, including the use of wildcard characters, depends on the
provider. Filters
are more efficient than other parameters, because the provider
applies them when the cmdlet gets the
objects rather than having PowerShell filter
the objects after they are retrieved.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Force

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

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False


Accept wildcard characters: False

-Include

Specifies, as a string array, an item or items that this cmdlet includes in the
operation. The value
of this parameter qualifies the Path parameter. Enter a path
element or pattern, such as
*.txt . Wildcard characters 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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-LiteralPath

Specifies a path to one or more locations. 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
PowerShell not to interpret any
characters as escape sequences.

For more information, see


about_Quoting_Rules.

Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies a name for the new property.


If the property is a registry entry, this
parameter specifies the name of the entry.
Type: String

Aliases: PSProperty

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Path

Specifies the path of the item.


This parameter identifies the item to which this cmdlet
adds the new property.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-PropertyType

Specifies the type of property that this cmdlet adds.


The acceptable values for this
parameter are:

String : Specifies a null-terminated string. Used for REG_SZ values.


ExpandString : Specifies a null-terminated string that contains unexpanded

references to
environment variables that are expanded when the value is
retrieved. Used for REG_EXPAND_SZ
values.
Binary : Specifies binary data in any form. Used for REG_BINARY values.

DWord : Specifies a 32-bit binary number. Used for REG_DWORD values.


MultiString : Specifies an array of null-terminated strings terminated by two

null characters.
Used for REG_MULTI_SZ values.
Qword : Specifies a 64-bit binary number. Used for REG_QWORD values.
Unknown : Indicates an unsupported registry data type, such as

REG_RESOURCE_LIST values.

Type: String
Aliases: Type

Position: Named

Default value: None

Accept pipeline input: True

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.

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Value

Specifies the property value.


If the property is a registry entry, this parameter
specifies the value of the entry.

Type: Object

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs.


The cmdlet is not run.

Type: SwitchParameter

Aliases: wi
Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
PSCustomObject

This cmdlet returns a custom object representing the new property.

Notes
New-ItemProperty 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.

Related Links
Clear-ItemProperty
Copy-ItemProperty
Get-ItemProperty
Move-ItemProperty
Remove-ItemProperty
Rename-ItemProperty
Set-ItemProperty
about_Providers
New-PSDrive
Reference
Module: Microsoft.PowerShell.Management

Creates temporary and persistent drives that are associated with a location in an item
data store.

Syntax
PowerShell

New-PSDrive

[-Name] <String>

[-PSProvider] <String>

[-Root] <String>

[-Description <String>]

[-Scope <String>]

[-Persist]

[-Credential <PSCredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

Description
The New-PSDrive cmdlet creates temporary and persistent drives that are 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, and persistent Windows mapped network drives that
are associated with a file system
location on a remote computer.

Temporary drives exist only in the current PowerShell session and in sessions that you
create in the
current session. They can have any name that is valid in PowerShell and can
be mapped to any local
or remote resource. You can use temporary PowerShell drives to
access data in the associated data
store, just as you would do with any mapped network
drive. You can change locations into the drive,
by using Set-Location , and access the
contents of the drive by using Get-Item or
Get-ChildItem .

Because temporary drives are known only to PowerShell, you can't access them by using
File Explorer,
Windows Management Instrumentation (WMI), Component Object Model
(COM), Microsoft .NET Framework, or
with tools such as net use .
The following features were added to New-PSDrive in PowerShell 3.0:

Mapped network drives. You can use the Persist parameter of New-PSDrive to
create Windows
mapped network drives. Unlike temporary PowerShell drives,
Windows mapped network drives aren't
session-specific. They're saved in Windows
and they can be managed by using standard Windows
tools, such as File Explorer
and net use. Mapped network drives must have a drive-letter name
and be
connected to a remote file system location. When your command is scoped locally,
no
dot-sourcing, the Persist parameter doesn't persist the creation of a PSDrive
beyond the
scope in which the command is running. If you're running New-PSDrive
inside a script, and you
want the drive to persist indefinitely, you must dot-source
the script. For best results, to force
a new drive to persist indefinitely, add the
Scope parameter to your command, and set its
value to Global. For more
information about dot-sourcing, see
about_Scripts.
External drives. When an external drive is connected to the computer, PowerShell
automatically
adds a PSDrive to the file system that represents the new drive. You
don't have to restart
PowerShell. Similarly, when an external drive is disconnected
from the computer, PowerShell
automatically deletes the PSDrive that represents
the removed drive.
Credentials for Universal Naming Convention (UNC) paths.

When the value of the Root parameter is a UNC path, such as \\Server\Share , the
credential
specified in the value of the Credential parameter is used to create the
PSDrive. Otherwise,
Credential isn't effective when you're creating new file system
drives.

Some code samples use splatting to reduce the line length and improve readability. For
more
information, see about_Splatting.

7 Note

Unless you use the Scope parameter, PSDrives are created in the scope in which
the
New-PSDrive command is run.

Examples

Example 1: Create a temporary drive mapped to a


network share
This example creates a temporary PowerShell drive that's mapped to a network share.
PowerShell

New-PSDrive -Name "Public" -PSProvider "FileSystem" -Root


"\\Server01\Public"

Name Provider Root

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

Public FileSystem \\Server01\Public

New-PSDrive uses the Name parameter to specify PowerShell drive named Public and

the
PSProvider parameter to specify the PowerShell FileSystem provider. The Root
parameter
specifies the network share's UNC path.

To view the contents from a PowerShell session: Get-ChildItem -Path Public:

Example 2: Create a temporary drive mapped to a local


directory
This example creates a temporary PowerShell drive that provides access to a directory
on the local
computer.

PowerShell

$parameters = @{

Name = "MyDocs"

PSProvider = "FileSystem"

Root = "C:\Users\User01\Documents"

Description = "Maps to my My Documents folder."

New-PSDrive @parameters

Name Provider Root

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

MyDocs FileSystem C:\Users\User01\Documents

Splatting creates the parameter keys and values. The Name parameter specifies the
drive name,
MyDocs. The PSProvider parameter specifies the PowerShell FileSystem
provider. Root
specifies the local computer's directory. The Description parameter
describes the drive's
purpose. New-PSDrive uses the splatted parameters to create the
MyDocs drive.

To view the contents from a PowerShell session: Get-ChildItem -Path MyDocs:

Example 3: Create a temporary drive for a registry key


This example creates a temporary PowerShell drive that provides access to a registry
key. It creates
a drive named MyCompany that is mapped to the
HKLM:\Software\MyCompany registry key.

PowerShell

New-PSDrive -Name "MyCompany" -PSProvider "Registry" -Root


"HKLM:\Software\MyCompany"

Name Provider Root


---- -------- ----
MyCompany Registry HKLM:\Software\MyCompany

New-PSDrive uses the Name parameter to specify PowerShell drive named MyCompany
and the
PSProvider parameter to specify the PowerShell Registry provider. The Root
parameter
specifies the registry location.

To view the contents from a PowerShell session: Get-ChildItem -Path MyCompany:

Example 4: Create a persistent mapped network drive


using credentials
This example maps a network drive that's authenticated with a domain service account's
credentials.
For more information about the PSCredential object that stores credentials
and how passwords are
stored as a SecureString, see the Credential parameter's
description.

PowerShell

$cred = Get-Credential -Credential Contoso\ServiceAccount

New-PSDrive -Name "S" -Root "\\Server01\Scripts" -Persist -PSProvider


"FileSystem" -Credential $cred

Net Use

Status Local Remote Network

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

OK S: \\Server01\Scripts Microsoft Windows Network

7 Note

Remember, if you use the above snippet in a script, set the Scope parameter value
to
"Global" to ensure the drive persists outside the current scope.
The $cred variable stores a PSCredential object that contains the service account's
credentials. Get-Credential prompts you to enter the password that's stored in a
SecureString.

New-PSDrive creates the mapped network drive by using several parameters. Name
specifies the
S drive letter that Windows accepts. and Root defines \\Server01\Scripts
as the location on
a remote computer. Persist creates a Windows mapped network drive
that's saved on the local
computer. PSProvider specifies the FileSystem provider.
Credential uses the $cred
variable to get the service account credentials for
authentication.

The mapped drive can be viewed on the local computer in PowerShell sessions, File
Explorer, and with
tools such as net use. To view the contents from a PowerShell session:
Get-ChildItem -Path S:

Example 5: Create persistent and temporary drives


This example shows the difference between a persistent mapped network drive and a
temporary
PowerShell drive that is mapped to the same network share.

If you close the PowerShell session and then open a new session, the temporary
PSDrive: isn't
available, but the persistent X: drive is available. When deciding which
method to use to map
network drives, consider how you'll use the drive. For example,
whether it has to be persistent, and
whether the drive has to be visible to other
Windows features.

PowerShell

# Create a temporary PowerShell drive called PSDrive:

# that's mapped to the \\Server01\Public network share.

New-PSDrive -Name "PSDrive" -PSProvider "FileSystem" -Root


"\\Server01\Public"

# Use the Persist parameter of New-PSDrive to create the X: mapped network


drive,

# which is also mapped to the \\Server01\Public network share.

New-PSDrive -Persist -Name "X" -PSProvider "FileSystem" -Root


"\\Server01\Public"

# Now, you can use the Get-PSDrive drive cmdlet to examine the two drives.

# The drives appear to be the same, although the network share name appears
only

# in the root of the PSDrive: drive.

Get-PSDrive -Name "PSDrive", "X"

Name Provider Root

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

PsDrive FileSystem \\Server01\public

X FileSystem X:\

# Get-Member cmdlet shows that the drives have the same object type,

# System.Management.Automation.PSDriveInfo.

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()

...

# Net Use and Get-CimInstance for the Win32_LogicalDisk class,

# and Win32_NetworkConnection class find only the persistent X: drive.

# PowerShell temporary drives are known only to PowerShell.

Net Use

Get-CimInstance Win32_LogicalDisk | Format-Table -Property DeviceID

Get-CimInstance Win32_NetworkConnection

Status Local Remote Network

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

OK X: \\contoso-pc\data Microsoft Windows Network

deviceid

--------

C:

D:

X:

LocalName RemoteName ConnectionState Status

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

X: \\products\public Disconnected Unavailable

Example 6: Create persistent drive in a script


PSDrives are created in the scope in which the New-PSDrive command is run. When the
command is run
within a script, the drive mapping is local to the script. When the script
exits, the drive is no
longer available.

PowerShell

New-PSDrive -Persist -Name "X" -PSProvider "FileSystem" -Root


"\\Server01\Public" -Scope Global
To ensure that the drive is available outside of the script you must use the Scope
parameter to
create the drive in the Global scope.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Credential

Specifies a user account that has permission to do this action. The default is the
current user.

Since PowerShell 3.0, when the value of the Root parameter is a UNC path, you can
use
credentials to create file system drives.

Type a user name, such as User01 or Domain01\User01, or enter a PSCredential


object
generated by the Get-Credential cmdlet. If you type a user name, you're
prompted to enter the
password.

Credentials are stored in a PSCredential


object and the password is stored as a
SecureString.

7 Note

For more information about SecureString data protection, see


How secure is
SecureString?.

Type: PSCredential

Position: Named
Default value: Current user

Accept pipeline input: True

Accept wildcard characters: False

-Description

Specifies a brief text description of the drive. Type any string.

To see the descriptions of all the session's drives, Get-PSDrive | Format-Table Name,
Description .

To see the description of a particular drive, type (Get-PSDrive


<DriveName>).Description .

Type: String

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies a name for the new drive. For persistent mapped network drives, use a
drive letter. For
temporary PowerShell drives, you aren't limited to drive letters, use
any valid string.

Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Persist

Indicates that this cmdlet creates a Windows mapped network drive. The Persist
parameter is only
available on Windows.
Mapped network drives are saved in Windows on the local computer. They're
persistent, not
session-specific, and can be viewed and managed in File Explorer and
other tools.

When you scope the command locally, without dot-sourcing, the Persist parameter
doesn't persist
the creation of a PSDrive beyond the scope in which you run the
command. If you run
New-PSDrive inside a script, and you want the new drive to
persist indefinitely, you must
dot-source the script. For best results, to force a new
drive to persist, specify Global as the
value of the Scope parameter and include
Persist in your command.

The name of the drive must be a letter, such as D or E . The value of Root parameter
must be
a UNC path of a different computer. The PSProvider parameter's value must
be FileSystem .

To disconnect a Windows mapped network drive, use the Remove-PSDrive cmdlet.


When you disconnect a
Windows mapped network drive, the mapping is
permanently deleted from the computer, not just deleted
from the current session.

Mapped network drives are specific to a user account. Mapped drives created in
elevated sessions or
sessions using the credential of another user aren't visible in
sessions started using different
credentials.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: True

Accept wildcard characters: False

-PSProvider

Specifies the PowerShell provider that supports drives of this kind.

For example, if the drive is associated with a network share or file system directory,
the
PowerShell provider is FileSystem . If the drive is associated with a registry key,
the provider is
Registry .

Temporary PowerShell drives can be associated with any PowerShell provider.


Mapped network drives
can be associated only with the FileSystem provider.
To see a list of the providers in your PowerShell session, use the Get-PSProvider
cmdlet.

Type: String

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Root

Specifies the data store location to which a PowerShell drive is mapped.

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 .

Temporary PowerShell drives can be associated with a local or remote location on


any supported
provider drive. Mapped network drives can be associated only with a
file system location on a remote
computer.

Type: String

Position: 2

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Scope

Specifies a scope for the drive. The acceptable values for this parameter are: Global,
Local, and Script, or a number relative to the current scope. Scopes number 0
through the
number of scopes. The current scope number is 0 and its parent is 1. For
more information, see
about_Scopes.

Type: String

Position: Named

Default value: Local

Accept pipeline input: True


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.

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet isn't run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet

Outputs
PSDriveInfo

This cmdlet returns a PSDriveInfo object representing the created drive.


Notes
Windows PowerShell includes the following aliases for New-PSDrive :

mount

ndr

New-PSDrive is designed to work with the data exposed by any provider. To list the

providers
available in your session, use Get-PSProvider . For more information about
providers, see
about_Providers.

Mapped network drives are specific to a user account. Mapped drives created in
elevated sessions or
sessions using the credential of another user aren't visible in
sessions started using different
credentials.

Related Links
about_Providers
Get-Credential
Get-PSDrive
Remove-PSDrive
New-Service
Reference
Module: Microsoft.PowerShell.Management

Creates a new Windows service.

Syntax
PowerShell

New-Service

[-Name] <String>

[-BinaryPathName] <String>

[-DisplayName <String>]

[-Description <String>]

[-StartupType <ServiceStartMode>]

[-Credential <PSCredential>]

[-DependsOn <String[]>]

[-WhatIf]

[-Confirm]

[<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 runs during the
service.

The parameters of this cmdlet let you set the display name, description, startup type,
and
dependencies of the service.

Examples

Example 1: Create a service


PowerShell

New-Service -Name "TestService" -BinaryPathName


'"C:\WINDOWS\System32\svchost.exe -k netsvcs"'

This command creates a service named TestService.


Example 2: Create a service that includes description,
startup type, and display name
PowerShell

$params = @{

Name = "TestService"

BinaryPathName = '"C:\WINDOWS\System32\svchost.exe -k netsvcs"'

DependsOn = "NetLogon"

DisplayName = "Test Service"

StartupType = "Manual"

Description = "This is a test service."

New-Service @params

This command creates a service named TestService. It uses the parameters of New-
Service to specify
a description, startup type, and display name for the new service.

Example 3: View the new service


PowerShell

Get-CimInstance -ClassName Win32_Service -Filter "Name='testservice'"

ExitCode : 0

Name : testservice

ProcessId : 0

StartMode : Auto

State : Stopped

Status : OK

This command uses Get-CimInstance to get the Win32_Service object for the new
service. This
object includes the start mode and the service description.

Example 4: Delete a service


PowerShell

sc.exe delete TestService

# - or -

(Get-CimInstance -Class Win32_Service -Filter "name='TestService'").delete()

This example shows two ways to delete the TestService service. The first command uses
the delete
option of Sc.exe . The second command uses the Delete method of the
Win32_Service objects
that Get-CimInstance returns.

Parameters
-BinaryPathName

Specifies the path of the executable file for the service. This parameter is required.

The fully qualified path to the service binary file. If the path contains a space, it must
be quoted
so that it is correctly interpreted. For example, d:\my share\myservice.exe
should be specified as
'"d:\my share\myservice.exe"' .

The path can also include arguments for an auto-start service. For example,
'"d:\myshare\myservice.exe arg1 arg2"' . These arguments are passed to the service
entry point.

For more information, see the lpBinaryPathName parameter of


CreateServiceW API.

Type: String

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Credential
Specifies the account used by the service as the
Service Logon Account.

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, this cmdlet prompts
you for a password.

Credentials are stored in a PSCredential


object and the password is stored as a
SecureString.

7 Note

For more information about SecureString data protection, see


How secure is
SecureString?.

Type: PSCredential

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-DependsOn

Specifies the names of other services upon which the new service depends. To enter
multiple service
names, use a comma to separate the names.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Description

Specifies a description of the service.

Type: String

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-DisplayName

Specifies a display name for the service.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Name

Specifies the name of the service. This parameter is required.

Type: String

Aliases: ServiceName

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-StartupType

Sets the startup type of the service. The acceptable values for this parameter are:

Automatic - The service is 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.
Manual - The service is started only manually, by a user, using the Service
Control Manager,
or by an application.
Boot - Indicates that the service is a device driver started by the system loader.
This
value is valid only for device drivers.
System - Indicates that the service is a device driver started by the
'IOInitSystem()'
function. This value is valid only for device drivers.

The default value is Automatic.

Type: ServiceStartMode

Accepted values: Boot, System, Automatic, Manual, Disabled

Position: Named

Default value: Automatic

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
ServiceController
This cmdlet returns an object representing the new service.

Notes
To run this cmdlet, start PowerShell by using the Run as administrator option.

To delete a service, use Sc.exe, or use the Get-CimInstance cmdlet to get the
Win32_Service
object that represents the service and then use the Delete method to
delete the service. The
object that Get-Service returns does not have a delete method.

Related Links
Get-Service
Restart-Service
Resume-Service
Set-Service
Start-Service
Stop-Service
Suspend-Service
New-WebServiceProxy
Reference
Module: Microsoft.PowerShell.Management

Creates a Web service proxy object that lets you use and manage the Web service in
PowerShell.

Syntax
PowerShell

New-WebServiceProxy

[-Uri] <Uri>

[[-Class] <String>]

[[-Namespace] <String>]

[<CommonParameters>]

PowerShell

New-WebServiceProxy

[-Uri] <Uri>

[[-Class] <String>]

[[-Namespace] <String>]

[-Credential <PSCredential>]

[<CommonParameters>]

PowerShell

New-WebServiceProxy

[-Uri] <Uri>

[[-Class] <String>]

[[-Namespace] <String>]

[-UseDefaultCredential]

[<CommonParameters>]

Description
The New-WebServiceProxy cmdlet lets you use a Web service in PowerShell. The cmdlet
connects to a
Web service and creates a Web service proxy object in 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, especially
over the
Internet. The Microsoft .NET Framework provides Web service proxy objects
that represent the Web
service as a .NET Framework object.

Examples

Example 1: Create a proxy for a Web service


This example creates a .NET Framework proxy of the calculator Web service in Windows
PowerShell.

PowerShell

$calc = New-WebServiceProxy -Uri "http://www.dneonline.com/calculator.asmx?


wsdl"

Example 2: Create a proxy for a Web service and specify


namespace and class
This example uses the New-WebServiceProxy cmdlet to create a .NET Framework proxy of
the
calculator Web service.

PowerShell

$URI = "http://www.dneonline.com/calculator.asmx?wsdl"

$calc = New-WebServiceProxy -Uri $URI -Namespace "WSProxy" -Class


"Calculator"

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: Display methods of a Web service proxy


PowerShell

$calc | Get-Member -MemberType method

TypeName: WSProxy.Calculator

Name MemberType Definition

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

Abort Method void Abort()

Add Method int Add(int intA, int intB)

AddAsync Method void AddAsync(int intA, int intB), void


AddAsync(int intA,

BeginAdd Method System.IAsyncResult BeginAdd(int intA,


int intB, System.Asy

BeginDivide Method System.IAsyncResult BeginDivide(int


intA, int intB, System.

BeginMultiply Method System.IAsyncResult BeginMultiply(int


intA, int intB, Syste

BeginSubtract Method System.IAsyncResult BeginSubtract(int


intA, int intB, Syste

CancelAsync Method void CancelAsync(System.Object


userState)

CreateObjRef Method System.Runtime.Remoting.ObjRef


CreateObjRef(type requestedT

Discover Method void Discover()

Dispose Method void Dispose(), void


IDisposable.Dispose()

Divide Method int Divide(int intA, int intB)

DivideAsync Method void DivideAsync(int intA, int intB),


void DivideAsync(int

EndAdd Method int EndAdd(System.IAsyncResult


asyncResult)

EndDivide Method int EndDivide(System.IAsyncResult


asyncResult)

EndMultiply Method int EndMultiply(System.IAsyncResult


asyncResult)

EndSubtract Method int EndSubtract(System.IAsyncResult


asyncResult)

Equals Method bool Equals(System.Object obj)

GetHashCode Method int GetHashCode()

GetLifetimeService Method System.Object GetLifetimeService()

GetType Method type GetType()

InitializeLifetimeService Method System.Object


InitializeLifetimeService()

Multiply Method int Multiply(int intA, int intB)

MultiplyAsync Method void MultiplyAsync(int intA, int intB),


void MultiplyAsync(

Subtract Method int Subtract(int intA, int intB)

SubtractAsync Method void SubtractAsync(int intA, int intB),


void SubtractAsync(

ToString Method string ToString()

This example uses the Get-Member cmdlet to display the methods of the Web service
proxy object in
the $calc variable. We uses 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: Use a Web service proxy


PowerShell
PS> $calc.Multiply(6,7)

42

This example uses the Web service proxy stored in the $calc variable. The command
uses the
Multiply method of the proxy.

Parameters
-Class

Specifies a name for the proxy class that the cmdlet creates for the Web service. The
value of this
parameter is used together with the Namespace parameter to provide a
fully qualified name for
the class. The default value is generated from the Uniform
Resource Identifier (URI).

Type: String

Aliases: FileName, FN

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Credential

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, this cmdlet prompts you for a
password.

Type: PSCredential

Aliases: Cred

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-Namespace

Specifies a namespace for the new class.

The value of this parameter is used together 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 that
have the same name.

Type: String

Aliases: NS

Position: 2

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Uri

Specifies the URI of the Web service. Enter a URI or the path and filename of a file
that contains
a service description.

The URI must return an .asmx page or to a page that returns a service description. To
return a
service description of a Web service that was created using ASP.NET, append
"?WSDL" to the URL of
the Web service (for example,
http://www.contoso.com/MyWebService.asmx?WSDL ).

Type: Uri

Aliases: WL, WSDL, Path

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-UseDefaultCredential

Indicates that this cmdlet uses the default credential. This cmdlet sets the
UseDefaultCredential property in the resulting proxy object to True. This is an
alternative to
using the Credential parameter.

Type: SwitchParameter

Aliases: UDC

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You cannot pipe input to this cmdlet.

Outputs
A Web service proxy object

This cmdlet returns 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 URI.

Notes
New-WebServiceProxy uses the System.Net.WebClient class to load the specified Web
service.

Related Links
New-Service
Pop-Location
Reference
Module: Microsoft.PowerShell.Management

Changes the current location to the location most recently pushed onto the stack.

Syntax
PowerShell

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.

Examples

Example 1: Change to most recent location


PowerShell

PS C:\> Pop-Location

This command changes your location to the location most recently added to the current
stack.

Example 2: Change to most recent location in a named


stack
PowerShell
PS C:\> Pop-Location -StackName "Stack2"

This command changes your location to the location most recently added to the Stack2
location stack.

For more information about location stacks, see the Notes.

Example 3: Move between locations for different


providers
PowerShell

PS C:\> pushd HKLM:\Software\Microsoft\PowerShell

PS HKLM:\Software\Microsoft\PowerShell> pushd
Cert:\LocalMachine\TrustedPublisher

PS cert:\LocalMachine\TrustedPublisher> popd

PS HKLM:\Software\Microsoft\PowerShell> popd

PS C:\>

These commands use the Push-Location and Pop-Location cmdlets to move between
locations
supported by different 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 PowerShell Registry provider.

The second command pushes the registry location onto the stack and moves to a
location supported by
the 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.

Parameters
-PassThru

Passes an object that represents the location to the pipeline. By default, this cmdlet
does not
generate any output.

Type: SwitchParameter

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-StackName

Specifies the location stack from which the location is popped. Enter a location stack
name.

Without this parameter, Pop-Location pops a location from the current location
stack. By
default, the current location stack is the unnamed default location stack
that PowerShell
creates. To make a location stack the current location stack, use the
StackName parameter
of the Set-Location cmdlet. For more information about
location stacks, see the Notes.

Pop-Location cannot pop a location from the unnamed default stack unless it is the

current
location stack.

Type: String

Position: Named

Default value: None

Accept pipeline input: True

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.

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

PathInfo

When you use the PassThru parameter, this cmdlet returns a PathInfo object
representing the
current path after the cmdlet's operation.

Notes
Windows PowerShell includes the following aliases for Pop-Location :

popd

PowerShell supports multiple runspaces per process. Each runspace has its own current
directory.
This is not the same as [System.Environment]::CurrentDirectory . This behavior
can be an issue
when calling .NET APIs or running native applications without providing
explicit directory paths.

Even if the location cmdlets did set the process-wide current directory, you can't depend
on it
because another runspace might change it at any time. You should use the location
cmdlets to perform
path-based operations using the current working directory specific
to the current runspace.

A stack is a last-in, first-out list in which only the most recently added item can be
accessed. You
add items to a stack in the order that you use them, and then retrieve
them for use in the reverse
order. PowerShell lets you store provider locations in
location stacks.

PowerShell creates an unnamed default location stack and you can create multiple
named location
stacks. If you do not specify a stack name, PowerShell uses the current
location stack. By
default, the unnamed default location is the current location stack, but
you can use the
Set-Location cmdlet to change the current location stack.
To manage location stacks, use the PowerShell *-Location cmdlets, as follows:

To add a location to a location stack, use the Push-Location cmdlet.

To get a location from a location stack, use the Pop-Location cmdlet.

To display the locations in the current location stack, use the Stack parameter of
the
Get-Location cmdlet.

To display the locations in a named location stack, use the StackName parameter
of the
Get-Location cmdlet.

To create a new location stack, use the StackName parameter of the Push-
Location cmdlet. If
you specify a stack that does not exist, Push-Location creates
the stack.

To make a location stack the current location stack, use the StackName parameter
of the
Set-Location cmdlet.

The unnamed default location stack is fully accessible only when it is the current location
stack.
If you make a named location stack the current location stack, you can no longer
use the
Push-Location or Pop-Location cmdlets to add or get items from the default
stack or use the
Get-Location cmdlet to display the locations in the unnamed stack. To
make the unnamed stack
the current stack, use the StackName parameter of the Set-
Location cmdlet with a value of
$Null or an empty string ( "" ).

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

Related Links
Get-Location
Push-Location
Set-Location
about_Aliases
about_Providers
Push-Location
Reference
Module: Microsoft.PowerShell.Management

Adds the current location to the top of a location stack.

Syntax
PowerShell

Push-Location

[[-Path] <String>]

[-PassThru]

[-StackName <String>]

[-UseTransaction]

[<CommonParameters>]

PowerShell

Push-Location

[-LiteralPath <String>]

[-PassThru]

[-StackName <String>]

[-UseTransaction]

[<CommonParameters>]

Description
The Push-Location cmdlet adds ("pushes") the current location onto a location stack. If
you
specify a path, Push-Location pushes the current location onto a location stack and
then changes
the current location to the location specified by the path. You can use the
Pop-Location cmdlet
to get locations from the location stack.

By default, the Push-Location cmdlet pushes the current location onto the current
location stack,
but you can use the StackName parameter to specify an alternate
location stack. If the stack
does not exist, Push-Location creates it.

For more information about location stacks, see the Notes.

Examples
Example 1
This example pushes the current location onto the default location stack and then
changes the
location to C:\Windows .

PowerShell

PS C:\> Push-Location C:\Windows

Example 2
This example pushes the current location onto the RegFunction stack and changes the
current location
to the HKLM:\Software\Policies location.

PowerShell

PS C:\> Push-Location HKLM:\Software\Policies -StackName RegFunction

You can use the Location cmdlets in any PowerShell drive (PSDrive).

Example 3
This command pushes the current location onto the default stack. It does not change
the location.

PowerShell

PS C:\> Push-Location

Example 4 - Create and use a named stack


These commands show how to create and use a named location stack.

PowerShell

PS C:\> Push-Location ~ -StackName Stack2

PS C:\Users\User01> Pop-Location -StackName Stack2

PS C:\>

The first command pushes the current location onto a new stack named Stack2, and
then changes the
current location to the home directory, represented in the command
by the tilde symbol ( ~ ),
which when used on a FileSystem provider drives is equivalent
to $HOME .

If Stack2 does not already exist in the session, Push-Location creates it. The second
command uses
the Pop-Location cmdlet to pop the original location ( C:\ ) from the
Stack2 stack. Without the
StackName parameter, Pop-Location would pop the location
from the unnamed default stack.

For more information about location stacks, see the Notes.

Parameters
-LiteralPath

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 PowerShell not to interpret any characters as escape
sequences.

Type: String

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-PassThru

Passes an object representing the location to the pipeline. By default, this cmdlet
does not
generate any output.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


-Path

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

Type: String

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-StackName

Specifies the location stack to which the current location is added. Enter a location
stack name.
If the stack does not exist, Push-Location creates it.

Without this parameter, Push-Location adds the location to the current location
stack. By
default, the current location stack is the unnamed default location stack
that PowerShell creates.
To make a location stack the current location stack, use the
StackName parameter of the
Set-Location cmdlet. For more information about
location stacks, see the Notes.

7 Note

Push-Location cannot add a location to the unnamed default stack unless it is

the current
location stack.

Type: String

Position: Named

Default value: Default stack

Accept pipeline input: True

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.

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a string that contains a path (but not a literal path) to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

PathInfo

When you use the PassThru parameter, this cmdlet returns a PathInfo object
representing the
current path after the cmdlet's operation.

Notes
Windows PowerShell includes the following aliases for Push-Location :

pushd

PowerShell supports multiple runspaces per process. Each runspace has its own current
directory.
This is not the same as [System.Environment]::CurrentDirectory . This behavior
can be an issue
when calling .NET APIs or running native applications without providing
explicit directory paths.
Even if the location cmdlets did set the process-wide current directory, you can't depend
on it
because another runspace might change it at any time. You should use the location
cmdlets to perform
path-based operations using the current working directory specific
to the current runspace.

A stack is a last-in, first-out list in which only the most recently added item is accessible.
You add items to a stack in the order that you use them, and then retrieve them for use
in the
reverse order. PowerShell lets you store provider locations in location stacks.

PowerShell creates an unnamed default location stack and you can create multiple
named location
stacks. If you do not specify a stack name, PowerShell uses the current
location stack. By
default, the unnamed default location is the current location stack, but
you can use the
Set-Location cmdlet to change the current location stack.

To manage location stacks, use the PowerShell Location cmdlets, as follows.

To add a location to a location stack, use the Push-Location cmdlet.

To get a location from a location stack, use the Pop-Location cmdlet.

To display the locations in the current location stack, use the Stack parameter of
the
Get-Location cmdlet.

To display the locations in a named location stack, use the StackName parameter
of the
Get-Location cmdlet.

To create a new location stack, use the StackName parameter of the Push-Location
cmdlet. If you
specify a stack that does not exist, Push-Location creates the stack.

To make a location stack the current location stack, use the StackName parameter
of the
Set-Location cmdlet.

The unnamed default location stack is fully accessible only when it is the current location
stack.
If you make a named location stack the current location stack, you can no longer
use the
Push-Location or Pop-Location cmdlets to add or get items from the default
stack or use the
Get-Location cmdlet to display the locations in the unnamed stack. To
make the unnamed stack
the current stack, use the StackName parameter of the Set-
Location cmdlet with a value of
$null or an empty string ( "" ).

You can also refer to Push-Location by its built-in alias, pushd . For more information,
see
about_Aliases.

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.

Related Links
Get-Location
Pop-Location
Set-Location
about_Aliases
about_Providers
Register-WmiEvent
Reference
Module: Microsoft.PowerShell.Management

Subscribes to a Windows Management Instrumentation (WMI) event.

Syntax
PowerShell

Register-WmiEvent

[-Namespace <String>]

[-Credential <PSCredential>]

[-ComputerName <String>]

[-Class] <String>

[-Timeout <Int64>]

[[-SourceIdentifier] <String>]

[[-Action] <ScriptBlock>]
[-MessageData <PSObject>]
[-SupportEvent]

[-Forward]

[-MaxTriggerCount <Int32>]

[<CommonParameters>]

PowerShell

Register-WmiEvent

[-Namespace <String>]

[-Credential <PSCredential>]

[-ComputerName <String>]

[-Query] <String>

[-Timeout <Int64>]

[[-SourceIdentifier] <String>]

[[-Action] <ScriptBlock>]
[-MessageData <PSObject>]
[-SupportEvent]

[-Forward]

[-MaxTriggerCount <Int32>]

[<CommonParameters>]

Description
The Register-WmiEvent cmdlet subscribes to Windows Management Instrumentation
(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 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.

New Common Information Model (CIM) cmdlets, introduced Windows PowerShell 3.0,
perform the same
tasks as the WMI cmdlets. The CIM cmdlets comply with WS-
Management (WSMan) standards and with the
CIM standard, which enables the cmdlets
to use the same techniques to manage computers that run the
Windows operating
system and those that run other operating systems. Instead of using
Register-WmiEvent ,
consider using the
Register-CimIndicationEvent cmdlet.

Examples

Example 1: Subscribe to events generated by a class


This command subscribes to the events generated by the Win32_ProcessStartTrace
class. This class
raises an event whenever a process starts.

PowerShell

Register-WmiEvent -Class 'Win32_ProcessStartTrace' -SourceIdentifier


"ProcessStarted"

Example 2: Subscribe to creation events for a process


This command uses a query to subscribe to Win32_process instance creation events.

PowerShell

$wmiParameters = @{

Query = "select * from __instancecreationevent within 5 where


targetinstance isa 'win32_process'"

SourceIdentifier = "WMIProcess"
MessageData = "Test 01"

TimeOut = 500

Register-WmiEvent @wmiParameters

Example 3: Use an action to respond to an event


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.

PowerShell

$action = { Get-History | where { $_.commandline -like "*start-process*" } |


export-cliXml "commandHistory.clixml" }

Register-WmiEvent -Class 'Win32_ProcessStartTrace' -SourceIdentifier


"ProcessStarted" -Action $action

Id Name State HasMoreData Location Command

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

1 ProcessStarted NotStarted False get-history | where


{...

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: Register for events on a remote computer


This example registers for events on the Server01 remote computer.

PowerShell

Register-WmiEvent -Class 'Win32_ProcessStartTrace' -SourceIdentifier "Start"


-Computername Server01

Get-Event -SourceIdentifier "Start"

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.

Parameters
-Action

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 Action can include the $Event , $EventSubscriber , $Sender , $EventArgs ,
and
$Args 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.

Type: ScriptBlock

Position: 101

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Class

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.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ComputerName

Specifies the name of the computer on which the command runs. The default is the
local computer.

Type the NetBIOS name, an IP address, or a fully qualified domain name of the
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.

Type: String

Aliases: Cn

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Credential

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, this cmdlet prompts you for a
password.

Type: PSCredential

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Forward

Indicates that this cmdlet 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.

Type: SwitchParameter

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-MaxTriggerCount

Specifies the maximum trigger count.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-MessageData

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.

Type: PSObject

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Namespace

Specifies the namespace of the WMI class.

Type: String

Aliases: NS

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-Query

Specifies a query in WMI Query Language (WQL) that identifies the WMI event class,
such as:
select * from __InstanceDeletionEvent .

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SourceIdentifier

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.

Type: String

Position: 100

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SupportEvent

Indicates that this cmdlet 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 by using the SupportEvent


parameter, specify
the Force parameter of the Get-EventSubscriber and Unregister-
Event cmdlets.
Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Timeout

Specifies how long Windows PowerShell waits for this command to finish.

The default value, 0 (zero), means that there is no time-out, and it causes Windows
PowerShell to
wait indefinitely.

Type: Int64

Aliases: TimeoutMSec

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You cannot pipe objects to this cmdlet.

Outputs
None

This cmdlet does not generate any output.

Notes
To use this cmdlet in Windows Vista or a later version of the Windows operating system,
start
Windows PowerShell by using 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.
Remove-Computer
Reference
Module: Microsoft.PowerShell.Management

Removes the local computer from its domain.

Syntax
PowerShell

Remove-Computer

[[-UnjoinDomainCredential] <PSCredential>]

[-Restart]

[-Force]

[-PassThru]

[-WorkgroupName <String>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-Computer

-UnjoinDomainCredential <PSCredential>

[-LocalCredential <PSCredential>]

[-Restart]

[-ComputerName <String[]>]

[-Force]

[-PassThru]

[-WorkgroupName <String>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Remove-Computer cmdlet removes the local computer and remote computers from
their current
domains.

When you remove a computer from a domain, Remove-Computer also disables the
domain account of the
computer. You must provide explicit credentials to unjoin the
computer from its domain, even when
they are the credentials of the current user. You
must restart the computer to make the change
effective. Also, when you remove a
computer from a domain, you must move it to a workgroup. Use the
WorkgroupName
parameter to specify the workgroup.

To move a computer from a workgroup to a domain, from one workgroup to another, or


from one domain
to another, use the Add-Computer cmdlet.

To get the results of the command, use the Verbose and PassThru parameters. To
suppress the
user prompt, use the Force parameter.

Remove-Computer removes the local computer and remote computers from domains. It
includes
credential parameters that specify alternate credentials for connecting to
remote computers, and
unjoining from a domain, a Restart parameter for restarting the
affected computers, and a
WorkgroupName parameter for specifying the name of the
workgroup to which computers are added.

Examples

Example 1: Remove the local computer from its domain


This example removes the local computer from the domain to which it is joined.

PowerShell

Remove-Computer -UnjoinDomaincredential Domain01\Admin01 -PassThru -Verbose


-Restart

The UnjoinDomainCredential parameter provides the credentials of a domain


administrator. The
PassThru and the Verbose common parameters display information
about the success or failure
of the command. The Restart parameter restarts the
computer to complete the remove operation.

When no workgroup name is specified, the computer is moved to the workgroup


named after it is
removed from its domain.

Example 2: Move several computers to a legacy


workgroup
This example removes all the computers listed in the OldServers.txt file from their
domains and
moves them into the Legacy workgroup.

PowerShell
Remove-Computer -ComputerName (Get-Content OldServers.txt) -LocalCredential
Domain01\Admin01 -UnJoinDomainCredential Domain01\Admin01 -WorkgroupName
"Legacy" -Force -Restart

The LocalCredential parameter provides the credentials of a user who has permission to
connect
to remote computers. The UnjoinDomainCredential parameter provides the
credentials of a user who
has permission to remove the computers from their domains.
The Force parameter suppresses the
confirmation prompts for each computer. The
Restart parameter restarts each of the computers
after it is removed from its domain.

Example 3: Remove computers from a workgroup without


confirmation
This example removes the remote computer, Server01, and the local computer from
their domains and
adds them to the Local workgroup.

PowerShell

Remove-Computer -ComputerName "Server01", "localhost" -


UnjoinDomainCredential Domain01\Admin01 -WorkgroupName "Local" -Restart -
Force

The Force parameter suppresses the confirmation prompt for each computer. The
Restart
parameter restarts the computers to make the change effective.

Parameters
-ComputerName

Specifies the computers to be removed from their domains. The default is the local
computer.

Type the NetBIOS name, an IP address, or a fully qualified domain name (FQDN) of
the remote
computers. To specify the local computer, type the computer name, a dot
( . ), or localhost .

This parameter does not rely on PowerShell remoting. You can use the
ComputerName
parameter of Remove-Computer even if your computer is not
configured to run remote commands.

This parameter was introduced in PowerShell 3.0.


Type: String[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Force

Suppresses the user prompt. By default, Remove-Computer prompts you for


confirmation before
removing each computer.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-LocalCredential

Specifies a user account that has permission to connect to the computers that the
ComputerName
parameter specifies. 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, the cmdlet prompts you for a
password. To specify a user account that has
permission to remove the computer from its current
domain, use the
UnjoinDomainCredential parameter.

This parameter was introduced in PowerShell 3.0.

Type: PSCredential

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-PassThru

Returns the results of the command. Otherwise, this cmdlet does not generate any
output.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Restart

Indicates that this cmdlet restarts the computers that are being removed. A restart is
often
required to make the change effective.

This parameter was introduced in PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-UnjoinDomainCredential

Specifies a user account that has permission to remove the computers from their
current domains.
Explicit credentials, as provided by this parameter, are required to
remove remote computers from a
domain, even when the value is the credentials of
the current user.

Type a user name, such as User01 or Domain01\User01 , or enter a PSCredential


object, such as
one generated by Get-Credential . If you type a user name, this
cmdlet prompts you for a password.

To specify a user account that has permission to connect to the remote computers,
use the
LocalCredential parameter.

This parameter was introduced in PowerShell 3.0.

Type: PSCredential

Aliases: Credential

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-WorkgroupName

Specifies the name of a workgroup to which the computers are added when they are
removed from their
domains. The default value is WORKGROUP. When you remove
a computer from a domain, you must add
it to a workgroup.

This parameter was introduced in PowerShell 3.0.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe computer names to this cmdlet.

Outputs
ComputerChangeInfo

When you use the PassThru parameter, Remove-Computer returns a


ComputerChangeInfo object.
Otherwise, this cmdlet does not generate any output.

Notes
This cmdlet does not remove computers from workgroups.

Related Links
Add-Computer
Checkpoint-Computer
Remove-Computer
Rename-Computer
Restart-Computer
Restore-Computer
Stop-Computer
Test-Connection
Remove-EventLog
Reference
Module: Microsoft.PowerShell.Management

Deletes an event log or unregisters an event source.

Syntax
PowerShell

Remove-EventLog

[[-ComputerName] <String[]>]

[-LogName] <String[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-EventLog

[[-ComputerName] <String[]>]

[-Source <String[]>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Remove-EventLog cmdlet deletes an event log file from a local or remote computer
and
unregisters all 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 the Windows operating system, use Get-WinEvent.

2 Warning

This cmdlet can delete operating system event logs, which might cause application
failures and
unexpected system behavior.
Examples

Example 1: Remove an event log from the local computer


PowerShell

Remove-EventLog -LogName "MyLog"

This command deletes the MyLog event log from the local computer and unregisters its
event sources.

Example 2: Remove an event log from several computers


PowerShell

Remove-EventLog -LogName "MyLog", "TestLog" -ComputerName "Server01",


"Server02", "localhost"

This command deletes the MyLog and TestLog event logs from the local computer and
the Server01 and Server02 remote computers.
The command also unregisters the event
sources for these logs.

Example 3: Delete an event source


PowerShell

Remove-EventLog -Source "MyApp"

This command deletes the MyApp event source from the logs on the local computer.
When the command
finishes, the MyApp program cannot write to any event logs.

Example 4: Remove an event log and confirm the action


These commands show how to list the event logs on a computer and verify that a
Remove-EventLog command was successful.

PowerShell

Get-EventLog -List

Max(K) Retain OverflowAction Entries Log

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

15,168 0 OverwriteAsNeeded 22,923 Application

15,168 0 OverwriteAsNeeded 53 DFS Replication

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

Remove-EventLog -LogName "ZapLog"

Get-EventLog -List

Max(K) Retain OverflowAction Entries Log

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

15,168 0 OverwriteAsNeeded 22,923 Application

15,168 0 OverwriteAsNeeded 53 DFS Replication

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

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: Remove an event source and confirm the


action
PowerShell

Get-WmiObject win32_nteventlogfile -Filter "logfilename='TestLog'" | foreach


{$_.sources}

MyApp

TestApp

Remove-Eventlog -Source "MyApp"

Get-WmiObject win32_nteventlogfile -Filter "logfilename='TestLog'"} |


foreach {$_.sources}

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

Parameters
-ComputerName

Specifies a remote computer. 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 Remove-EventLog even if your computer is not
configured to run remote commands.

Type: String[]

Aliases: CN

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter
Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-LogName

Specifies the event logs. Enter the log name of one or more event logs, separated by
commas. The log
name is the value of the Log property, not the LogDisplayName,
Wildcard characters are not
permitted. This parameter is required.

Type: String[]

Aliases: LN

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Source

Specifies the event sources that this cmdlet unregisters. Enter the source names, not
the executable
name, separated by commas.

Type: String[]

Aliases: SRC

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

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 the Windows
operating system, start
Windows PowerShell by using 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.

Related Links
Clear-EventLog
Get-EventLog
Limit-EventLog
New-EventLog
Remove-EventLog
Show-EventLog
Write-EventLog
Remove-Item
Reference
Module: Microsoft.PowerShell.Management

Deletes the specified items.

Syntax
PowerShell

Remove-Item

[-Path] <String[]>

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Recurse]

[-Force]

[-Credential <PSCredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[-Stream <String[]>]

[<CommonParameters>]

PowerShell

Remove-Item

-LiteralPath <String[]>

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Recurse]

[-Force]

[-Credential <PSCredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[-Stream <String[]>]

[<CommonParameters>]

PowerShell

Remove-Item

[-Path] <String[]>

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Recurse]

[-Force]

[-Credential <PSCredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[-DeleteKey] <CommonParameters>]

PowerShell

Remove-Item

-LiteralPath <String[]>

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Recurse]

[-Force]

[-Credential <PSCredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[-DeleteKey]

[<CommonParameters>]

PowerShell

Remove-Item

[-Path] <string[]>

[-Filter <string>]

[-Include <string[]>]

[-Exclude <string[]>]

[-Recurse]

[-Force]

[-Credential <pscredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

PowerShell

Remove-Item

-LiteralPath <string[]>

[-Filter <string>]

[-Include <string[]>]

[-Exclude <string[]>]

[-Recurse]

[-Force]

[-Credential <pscredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

Description
The Remove-Item cmdlet deletes one or more items. Because it's supported by many
providers, it
can delete many different types of items, including files, folders, registry
keys, variables,
aliases, and functions.

Examples

Example 1: Delete files that have any file extension


This example deletes all files with names that include a dot ( . ) from the C:\Test folder.
Because the command specifies a dot, the command doesn't delete folders or files that
have no
file extension.

PowerShell

Remove-Item C:\Test\*.*

Example 2: Delete document files in a folder


This example deletes from the current folder all files that have a .doc file extension and
a
name that doesn't include *1* .

PowerShell

Remove-Item * -Include *.doc -Exclude *1*

It uses the wildcard character ( * ) to specify the contents of the current folder. It uses the
Include and Exclude parameters to specify the files to delete.

Example 3: Delete hidden, read-only files


This command deletes a file that's both hidden and read-only.

PowerShell
Remove-Item -Path C:\Test\hidden-RO-file.txt -Force

It uses the Path parameter to specify the file. It uses the Force
parameter to delete it.
Without Force, you can't delete read-only or
hidden files.

Example 4: Delete files in subfolders recursively


This command deletes all the CSV files in the current folder and all subfolders
recursively.

Because the Recurse parameter in Remove-Item has a known issue, the command in this
example
uses Get-ChildItem to get the desired files, and then uses the pipeline operator
to pass them to
Remove-Item .

PowerShell

Get-ChildItem * -Include *.csv -Recurse | Remove-Item

In the Get-ChildItem command, Path has a value of ( * ), which represents the contents
of the
current folder. It uses Include to specify the CSV file type, and it uses Recurse 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.

7 Note

This behavior was fixed in Windows versions 1909 and up.

Example 5: Delete subkeys recursively


This command deletes the "OldApp" registry key and all its subkeys and values. It uses
Remove-Item
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.

PowerShell
Remove-Item HKLM:\Software\MyCompany\OldApp -Recurse

Example 6: Deleting files with special characters


The following example shows how to delete files that contain special characters like
brackets or
parentheses.

PowerShell

Get-ChildItem

Directory: C:\temp\Downloads

Mode LastWriteTime Length Name

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

-a--- 6/1/2018 12:19 PM 1362 myFile.txt

-a--- 6/1/2018 12:30 PM 1132 myFile[1].txt

-a--- 6/1/2018 12:19 PM 1283 myFile[2].txt

-a--- 6/1/2018 12:19 PM 1432 myFile[3].txt

Get-ChildItem | Where-Object Name -Like '*`[*'

Directory: C:\temp\Downloads

Mode LastWriteTime Length Name

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

-a--- 6/1/2018 12:30 PM 1132 myFile[1].txt

-a--- 6/1/2018 12:19 PM 1283 myFile[2].txt

-a--- 6/1/2018 12:19 PM 1432 myFile[3].txt

Get-ChildItem | Where-Object Name -Like '*`[*' | ForEach-Object { Remove-


Item -LiteralPath $_.Name }

Get-ChildItem

Directory: C:\temp\Downloads

Mode LastWriteTime Length Name

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

-a--- 6/1/2018 12:19 PM 1362 myFile.txt

Example 7: Remove an alternate data stream


This example shows how to use the Stream dynamic parameter of the Remove-Item
cmdlet to delete
an alternate data stream. The stream parameter is introduced in
Windows PowerShell 3.0.

PowerShell
Get-Item C:\Test\Copy-Script.ps1 -Stream Zone.Identifier

FileName: \\C:\Test\Copy-Script.ps1

Stream Length

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

Zone.Identifier 26

Remove-Item C:\Test\Copy-Script.ps1 -Stream Zone.Identifier

Get-Item C:\Test\Copy-Script.ps1 -Stream Zone.Identifier

Get-Item : Could not open alternate data stream 'Zone.Identifier' of file


'C:\Test\Copy-Script.ps1'.

At line:1 char:1

+ Get-Item 'C:\Test\Copy-Script.ps1' -Stream Zone.Identifier

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : ObjectNotFound: (C:\Test\Copy-


Script.ps1:String) [Get-Item], FileNotFoundException

+ FullyQualifiedErrorId :
AlternateDataStreamNotFound,Microsoft.PowerShell.Commands.GetItemCommand

The Stream parameter Get-Item gets the Zone.Identifier stream of the Copy-
Script.ps1
file. Remove-Item uses the Stream parameter to remove the Zone.Identifier
stream of the
file. Finally, the Get-Item cmdlet shows that the Zone.Identifier stream
was deleted.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet. For more information, see
the following
articles:

about_Preference_Variables
about_Functions_CmdletBindingAttribute

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


-Credential

7 Note

This parameter isn't supported by any providers installed with PowerShell.


To
impersonate another user, or elevate your credentials when running this cmdlet,
use Invoke-Command.

Type: PSCredential

Position: Named

Default value: Current user

Accept pipeline input: True

Accept wildcard characters: False

-DeleteKey

This is a dynamic parameter made available by the Certificate provider. The


Certificate
provider and this parameter are only available on Windows platforms.

When provided, the cmdlet deletes the private key when the certificate is deleted.

For more information, see


about_Certificate_Provider.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Exclude

Specifies, as a string array, an item or items that this cmdlet excludes in the
operation. The value
of this parameter qualifies the Path parameter. Enter a path
element or pattern, such as
*.txt . Wildcard characters 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.
When using Recurse with Exclude, Exclude only filters results of the current
directory.
If there are files that match the Exclude pattern in subfolders, those files
are removed along
with its parent directory.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Filter

Specifies a filter to qualify the Path parameter. The


FileSystem provider is the only
installed PowerShell provider that supports the use of filters. You can find the syntax
for the
FileSystem filter language in
about_Wildcards. Filters are more efficient
than
other parameters, because the provider applies them when the cmdlet gets the
objects rather
than having PowerShell filter the objects after they're retrieved.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Force

Forces the cmdlet to remove items that can't otherwise be changed, such as hidden
or read-only
files or read-only aliases or variables. The cmdlet can't remove constant
aliases or variables.
Implementation varies from provider to provider. For more
information, see
about_Providers. Even using the Force
parameter, the cmdlet can't
override security restrictions.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False


Accept wildcard characters: False

-Include

Specifies, as a string array, an item or items that this cmdlet includes in the
operation. The value
of this parameter qualifies the Path parameter. Enter a path
element or pattern, such as
"*.txt" . Wildcard characters 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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-LiteralPath

Specifies a path to one or more locations. The value of LiteralPath is used exactly as
it's
typed. No characters are interpreted as wildcards. If the path includes escape
characters, enclose
it in single quotation marks. Single quotation marks tell
PowerShell not to interpret any characters
as escape sequences.

For more information, see


about_Quoting_Rules.

Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Path

Specifies a path of the items being removed.


Wildcard characters are permitted.
Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-Recurse

Indicates that this cmdlet deletes the items in the specified locations and in all child
items of
the locations.

The Recurse parameter might not delete all subfolders or all child items. This is a
known issue.

7 Note

This behavior was fixed in Windows versions 1909 and newer.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Stream

This is a dyanamic parameter made available by the FileSystem provider. This


parameter is only
available on Windows. This parameter can't be used in
combination with the Recurse parameter.

You can use Remove-Item to delete an alternative data stream, such as


Zone.Identifier .
However, it isn't the recommended way to eliminate security

checks that block files that are


downloaded from the Internet. If you verify that a
downloaded file is safe, use the Unblock-File
cmdlet.

This parameter was introduced in Windows PowerShell 3.0.

For more information, see


about_FileSystem_Provider.
Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-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

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet isn't run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a string that contains a path, but not a literal path, to this cmdlet.
Outputs
None

This cmdlet returns no output.

Notes
Windows PowerShell includes the following aliases for Remove-Item :

del
erase

rd

ri
rm

rmdir

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.

When you try to delete a folder that contains items without using the Recurse
parameter, the
cmdlet prompts for confirmation. Using -Confirm:$false doesn't
suppress the prompt. This is by
design.

Related Links
Clear-Item
Copy-Item
Get-Item
Invoke-Item
Move-Item
New-Item
Remove-ItemProperty
Rename-Item
Set-Item
about_Providers
about_Preference_Variables
about_Functions_CmdletBindingAttribute
Remove-ItemProperty
Reference
Module: Microsoft.PowerShell.Management

Deletes the property and its value from an item.

Syntax
PowerShell

Remove-ItemProperty

[-Path] <String[]>

[-Name] <String[]>

[-Force]

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Credential <PSCredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

PowerShell

Remove-ItemProperty

-LiteralPath <String[]>

[-Name] <String[]>

[-Force]

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Credential <PSCredential>]

[-WhatIf]

[-Confirm]

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

Example 1: Delete a registry value


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 ( PS C:\> ), it includes the fully
qualified path of 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.

PowerShell

Remove-ItemProperty -Path "HKLM:\Software\SmpApplication" -Name


"SmpProperty"

Example 2: Delete a registry value from the HKCU


location
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 Remove-ItemProperty to remove the "Options" registry value,
and its data, from the "MyApp" subkey.
Because Path is required, the command uses a
dot ('.') to indicate the current location.
It uses Name to specify which registry value to
delete.
It uses the Confirm parameter to request a user prompt before deleting the
value.

PowerShell

PS C:\> Set-Location HKCU:\Software\MyCompany\MyApp

PS HKCU:\Software\MyCompany\MyApp> Remove-ItemProperty -Path . -Name


"Options" -Confirm

Example 3: Remove a registry value by using the pipeline


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 Remove-ItemProperty .
Then, it uses
the Name parameter of Remove-ItemProperty to specify the name of the registry value.

PowerShell

Get-Item -Path HKLM:\Software\MyCompany | Remove-ItemProperty -Name


NoOfEmployees

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Credential

7 Note

This parameter is not supported by any providers installed with PowerShell.


To
impersonate another user, or elevate your credentials when running this cmdlet,
use Invoke-Command.

Type: PSCredential

Position: Named

Default value: Current user


Accept pipeline input: True

Accept wildcard characters: False

-Exclude

Specifies items that this cmdlet omits.


The value of this parameter qualifies the Path
parameter.
Enter a path element or pattern, such as "*.txt".
Wildcard characters are
permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Filter

Specifies a filter in the format or language of the provider.


The value of this
parameter qualifies the Path parameter.

The syntax of the filter, including the use of wildcard characters, depends on the
provider.
Filters are more efficient than other parameters, because the provider
applies them when the cmdlet gets the objects rather than having PowerShell filter
the objects after they are retrieved.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Force

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

Type: SwitchParameter
Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Include

Specifies, as a string array, an item or items that this cmdlet includes in the
operation.
The value of this parameter qualifies the Path parameter.
Enter a path
element or pattern, such as "*.txt".
Wildcard characters are permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-LiteralPath

Specifies the path to the current location of the property.


Unlike the Path parameter,
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 PowerShell not to interpret any characters as escape
sequences.

Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies the names of the properties to remove.


Wildcard characters are permitted.
Type: String[]

Aliases: PSProperty

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-Path

Specifies the path of the item whose properties are being removed.
Wildcard
characters are permitted.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

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

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs.


The cmdlet is not run.
Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a string that contains a path, but not a literal path, to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
Windows PowerShell includes the following aliases for Remove-ItemProperty :

rp

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

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

Related Links
Get-Item
Clear-ItemProperty
Copy-ItemProperty
Get-ItemProperty
Move-ItemProperty
New-ItemProperty
Remove-Item
Rename-ItemProperty
Set-ItemProperty
about_Providers
Remove-PSDrive
Reference
Module: Microsoft.PowerShell.Management

Deletes temporary PowerShell drives and disconnects mapped network drives.

Syntax
PowerShell

Remove-PSDrive

[-Name] <String[]>

[-PSProvider <String[]>]

[-Scope <String>]

[-Force]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

PowerShell

Remove-PSDrive

[-LiteralName] <String[]>

[-PSProvider <String[]>]

[-Scope <String>]

[-Force]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

Description
The Remove-PSDrive cmdlet deletes temporary PowerShell drives that were created by
using the
New-PSDrive cmdlet.

Beginning in Windows PowerShell 3.0, Remove-PSDrive also disconnects mapped


network drives,
including, but not limited to, drives created by using the Persist
parameter of New-PSDrive .

Remove-PSDrive cannot delete Windows physical or logical drives.


Beginning in Windows PowerShell 3.0, when an external drive is connected to the
computer, PowerShell
automatically adds a PSDrive to the file system that represents the
new drive. You do not need to
restart PowerShell. Similarly, when an external drive is
disconnected from the computer, PowerShell
automatically deletes the PSDrive that
represents the removed drive.

Examples

Example 1: Remove a file system drive


This command removes a temporary file system drive named smp .

PowerShell

Remove-PSDrive -Name smp

Example 2: Remove mapped network drives


This command uses Remove-PSDrive to disconnect the X: and S: mapped network
drives.

PowerShell

Get-PSDrive X, S | Remove-PSDrive

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


-Force

Removes the current PowerShell drive.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-LiteralName

Specifies the name of the 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 PowerShell not to interpret any characters
as escape sequences.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies the names of the drives to remove. Do not type a colon ( : ) after the drive
name.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True


-PSProvider

Specifies an array of PSProvider objects. This cmdlet removes and disconnects all of
the drives
associated with the specified PowerShell provider.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Scope

Specifies a scope for the drive. The acceptable values for this parameter are: Global ,
Local ,
and Script , or a number relative to the current scope. Scopes number 0

through the number of


scopes. The current scope number is 0 and its parent is 1 .
For more information, see
about_Scopes.

Type: String

Position: Named

Default value: Local

Accept pipeline input: True

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.

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSDriveInfo

You can pipe a drive object, such as from the Get-PSDrive cmdlet, to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
Windows PowerShell includes the following aliases for Remove-PSDrive :

rdr

The Remove-PSDrive cmdlet is designed to work with the data exposed by any
PowerShell provider.
To list the providers in your session, use the Get-PSProvider
cmdlet. For more information, see
about_Providers.

Related Links
Get-PSDrive
New-PSDrive
about_Providers
Remove-WmiObject
Reference
Module: Microsoft.PowerShell.Management

Deletes an instance of an existing Windows Management Instrumentation (WMI) class.

Syntax
PowerShell

Remove-WmiObject

[-Class] <String>

[-AsJob]

[-Impersonation <ImpersonationLevel>]

[-Authentication <AuthenticationLevel>]

[-Locale <String>]

[-EnableAllPrivileges]

[-Authority <String>]

[-Credential <PSCredential>]

[-ThrottleLimit <Int32>]

[-ComputerName <String[]>]

[-Namespace <String>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-WmiObject

-InputObject <ManagementObject>

[-AsJob]

[-ThrottleLimit <Int32>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-WmiObject

-Path <String>

[-AsJob]

[-Impersonation <ImpersonationLevel>]

[-Authentication <AuthenticationLevel>]

[-Locale <String>]

[-EnableAllPrivileges]

[-Authority <String>]

[-Credential <PSCredential>]

[-ThrottleLimit <Int32>]

[-ComputerName <String[]>]

[-Namespace <String>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-WmiObject

[-AsJob]

[-Impersonation <ImpersonationLevel>]

[-Authentication <AuthenticationLevel>]

[-Locale <String>]

[-EnableAllPrivileges]

[-Authority <String>]

[-Credential <PSCredential>]

[-ThrottleLimit <Int32>]

[-ComputerName <String[]>]

[-Namespace <String>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-WmiObject

[-AsJob]

[-Impersonation <ImpersonationLevel>]

[-Authentication <AuthenticationLevel>]

[-Locale <String>]

[-EnableAllPrivileges]

[-Authority <String>]

[-Credential <PSCredential>]

[-ThrottleLimit <Int32>]

[-ComputerName <String[]>]

[-Namespace <String>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-WmiObject

[-AsJob]

[-Impersonation <ImpersonationLevel>]

[-Authentication <AuthenticationLevel>]

[-Locale <String>]

[-EnableAllPrivileges]

[-Authority <String>]

[-Credential <PSCredential>]

[-ThrottleLimit <Int32>]

[-ComputerName <String[]>]

[-Namespace <String>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Remove-WmiObject cmdlet deletes an instance of an existing Windows Management
Instrumentation (WMI)class.

Examples

Example 1: Close all instances of a Win32 process


PowerShell

notepad

$np = Get-WmiObject -Query "select * from win32_process where


name='notepad.exe'"

$np | Remove-WmiObject

This example 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 then stores them in the $np
variable.

The third command passes the object in the $np variable to Remove-WmiObject , which
deletes all the
instances of Notepad.exe.

Example 2: Delete a folder


This command deletes the C:\Test folder.

PowerShell

$a = Get-WMIObject -Query "Select * From Win32_Directory Where Name


='C:\\Test'"

$a | Remove-WMIObject

The first command uses Get-WMIObject to query for the C:\Test folder, and then stores
the object
in the $a variable.

The second command pipes the $a variable to Remove-WMIObject , which deletes the
folder.

Parameters
-AsJob

Indicates that this cmdlet run as a background job. Use this parameter to run
commands that take a
long time to finish.

New CIM cmdlets, introduced Windows PowerShell 3.0, perform the same tasks as
the WMI cmdlets. The
CIM cmdlets comply with WS-Management (WSMan)
standards and with the Common Information Model (CIM)
standard, which enables
the cmdlets to use the same techniques to manage computers that run the
Windows
operating system and those running other operating systems. Instead of using
Remove-WmiObject , consider using the Remove-CimInstance cmdlet.

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.

To use this parameter for remote computers, the local and remote computers must
be configured for
remoting. Start Windows PowerShell by using the Run as
administrator option. For more information,
see about_Remote_Requirements.

For more information about Windows PowerShell background jobs, see about_Jobs
and about_Remote_Jobs.

Type: SwitchParameter

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-Authentication

Specifies the authentication level to use for the WMI connection. The acceptable
values for this
parameter 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 start 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.

Type: AuthenticationLevel

Accepted values: Default, None, Connect, Call, Packet, PacketIntegrity,


PacketPrivacy, Unchanged

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Authority

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.
Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Class

Specifies the name of a WMI class that this cmdlet deletes.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ComputerName

Specifies the name of the computer on which this cmdlet runs. 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 even if your computer is not configured to run remote
commands.

Type: String[]

Aliases: Cn

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Credential

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, this cmdlet prompts you for a
password.

Type: PSCredential

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-EnableAllPrivileges

Indicates that this cmdlet enables all the permissions of the current user before the
command it
makes the WMI call.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-Impersonation

Specifies the impersonation level to use. The acceptable values for this parameter
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.

Type: ImpersonationLevel

Accepted values: Default, Anonymous, Identify, Impersonate, Delegate

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies a ManagementObject object to use as input. When this parameter is used,


all other
parameters are ignored.

Type: ManagementObject

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Locale

Specifies the preferred locale for WMI objects. The Locale parameter is specified as
an array in
the MS_<LCID> format in the preferred order.

Type: String
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Namespace

Specifies the WMI repository namespace where the referenced WMI class is located
when it is used
with the Class parameter.

Type: String

Aliases: NS

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Path

Specifies the WMI object path of a WMI class, or specifies the WMI object path of an
instance of a
WMI class to delete.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ThrottleLimit

Specifies the maximum number of concurrent connections that can be established to


run this command.
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.

Type: Int32
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
ManagementObject

You can pipe a management object to this cmdlet.

Outputs
None, System.Management.Automation.RemotingJob

This cmdlet returns a job object, if you specify the AsJob parameter. Otherwise, it does
not
generate any output.

Related Links
Get-WmiObject
Invoke-WmiMethod
Set-WmiInstance
Rename-Computer
Reference
Module: Microsoft.PowerShell.Management

Renames a computer.

Syntax
PowerShell

Rename-Computer

[-ComputerName <String>]

[-PassThru]

[-DomainCredential <PSCredential>]

[-LocalCredential <PSCredential>]

[-NewName] <String>

[-Force]

[-Restart]

[-WsmanAuthentication <String>]

[-Protocol <String>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Rename-Computer cmdlet renames the local computer or a remote computer.
It
renames one computer in each command.

This cmdlet was introduced in Windows PowerShell 3.0.

Examples

Example 1: Rename the local computer


This command renames the local computer to Server044 and then restarts it to make
the change
effective.

PowerShell

Rename-Computer -NewName "Server044" -DomainCredential Domain01\Admin01 -


Restart
Example 2: Rename a remote computer
This command renames the Srv01 computer to Server001 . The computer is not
restarted.

The DomainCredential parameter specifies the credentials of a user who has permission
to rename
computers in the domain.

The Force parameter suppresses the confirmation prompt.

PowerShell

Rename-Computer -ComputerName "Srv01" -NewName "Server001" -DomainCredential


Domain01\Admin01 -Force

Parameters
-ComputerName

Renames the specified remote computer.


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


You can use the
ComputerName parameter of Rename-Computer even if your computer is not
configured to run remote commands.

Type: String

Position: Named

Default value: Local Computer

Accept pipeline input: True

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.


Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-DomainCredential

Specifies a user account that has permission to connect to the domain.


Explicit
credentials are required to rename a computer that is joined to a domain.

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, this cmdlet prompts you for a password.

To specify a user account that has permission to connect to the computer that is
specified by the
ComputerName parameter, use the LocalCredential parameter.

Type: PSCredential

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Force

Forces the command to run without asking for user confirmation.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-LocalCredential

Specifies a user account that has permission to connect to the computer specified by
the
ComputerName parameter. 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, this cmdlet prompts you for a password.

To specify a user account that has permission to connect to the domain, use the
DomainCredential
parameter.

Type: PSCredential

Position: Named

Default value: Current User

Accept pipeline input: False

Accept wildcard characters: False

-NewName

Specifies a new name for the computer.


This parameter is required.

Standard names may contain letters ( a-z ), ( A-Z ), numbers ( 0-9 ), and hyphens ( - ),
but no
spaces or periods ( . ). The name may not consist entirely of digits, and may
not be longer than
63 characters

Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-PassThru

Returns the results of the command.


Otherwise, this cmdlet does not generate any
output.

Type: SwitchParameter
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Protocol

Specifies which protocol to use to rename the computer.


The acceptable values for
this parameter are: WSMan and DCOM.
The default value is DCOM.

This parameter was introduced in Windows PowerShell 3.0.

Type: String

Accepted values: DCOM, WSMan

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Restart

Indicates that this cmdlet restarts the computer that was renamed.
A restart is often
required to make the change effective.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs.


The cmdlet is not run.

Type: SwitchParameter

Aliases: wi
Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-WsmanAuthentication

Specifies the mechanism that is used to authenticate the user credentials when this
cmdlet uses the
WSMan protocol. The acceptable values for this parameter are:

Basic
CredSSP
Default
Digest
Kerberos
Negotiate

The default value is Default.

For more information about the values of this parameter, see


AuthenticationMechanism Enumeration.

2 Warning

Credential Security Service Provider (CredSSP) authentication, in which the user


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.

This parameter was introduced in Windows PowerShell 3.0.

Type: String

Accepted values: Default, Basic, Negotiate, CredSSP, Digest, Kerberos

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

Inputs
None

This cmdlet has no parameters that take input by value. However, you can pipe the
values of
the ComputerName and NewName properties of objects to this cmdlet.

Outputs
None

By default, this cmdlet doesn't return any output.

RenameComputerChangeInfo

When you use the PassThru parameter, this cmdlet returns a


RenameComputerChangeInfo object.

Related Links
Add-Computer
Remove-Computer
Reset-ComputerMachinePassword
Restart-Computer
Stop-Computer
Rename-Item
Reference
Module: Microsoft.PowerShell.Management

Renames an item in a PowerShell provider namespace.

Syntax
PowerShell

Rename-Item

[-Path] <String>

[-NewName] <String>

[-Force]

[-PassThru]

[-Credential <PSCredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

PowerShell

Rename-Item

-LiteralPath <String>

[-NewName] <String>

[-Force]

[-PassThru]

[-Credential <PSCredential>]

[-WhatIf]

[-Confirm]

[-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 can't use Rename-Item to move an item, such as by specifying a path together with
the new
name. To move and rename an item, use the Move-Item cmdlet.
Examples

Example 1: Rename a file


This command renames the file daily_file.txt to monday_file.txt .

PowerShell

Rename-Item -Path "c:\logfiles\daily_file.txt" -NewName "monday_file.txt"

Example 2: Rename and move an item


You can't use Rename-Item to both rename and move an item. Specifically, you can't
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.

PowerShell

Rename-Item -Path "project.txt" -NewName "d:\archive\old-project.txt"

Rename-Item : can't 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], PS> Move-Item


-Path "project.txt" -De

stination "d:\archive\old-project.txt"

This example attempts 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.

Use the Move-Item cmdlet, instead.

Example 3: Rename a registry key


This example renames 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.

PowerShell

Rename-Item -Path "HKLM:\Software\MyCompany\Advertising" -NewName


"Marketing"
Example 4: Rename multiple files
This example renames all the *.txt files in the current directory to *.log .

PowerShell

Get-ChildItem *.txt

Directory: C:\temp\files

Mode LastWriteTime Length Name

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

-a---- 10/3/2019 7:47 AM 2918 Friday.TXT

-a---- 10/3/2019 7:46 AM 2918 Monday.Txt

-a---- 10/3/2019 7:47 AM 2918 Wednesday.txt

Get-ChildItem *.txt | Rename-Item -NewName { $_.Name -replace '.txt','.log'


}

Get-ChildItem *.log

Directory: C:\temp\files

Mode LastWriteTime Length Name

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

-a---- 10/3/2019 7:47 AM 2918 Friday.log

-a---- 10/3/2019 7:46 AM 2918 Monday.log

-a---- 10/3/2019 7:47 AM 2918 Wednesday.log

The Get-ChildItem cmdlet gets all the files in the current folder that have a .txt file
extension then pipes them to Rename-Item . The value of NewName is a script block that
runs
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 script block uses the -replace operator to
replace the file
extension of each file with .log . Notice that matching using the -
replace operator is not case
sensitive.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf
Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Credential

7 Note

This parameter is not supported by any providers installed with PowerShell. To


impersonate another
user, or elevate your credentials when running this cmdlet,
use Invoke-Command.

Type: PSCredential

Position: Named

Default value: Current user

Accept pipeline input: True

Accept wildcard characters: False

-Force

Forces the cmdlet to rename items that can't otherwise be changed, such as hidden
or read-only files
or read-only aliases or variables. The cmdlet can't change constant
aliases or variables.
Implementation varies from provider to provider. For more
information, see about_Providers.

Even using the Force parameter, the cmdlet can't override security restrictions.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-LiteralPath
Specifies a path to one or more locations. 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
PowerShell not to interpret any characters
as escape sequences.

For more information, see about_Quoting_Rules.

Type: String

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-NewName

Specifies the new name of the item. Enter only a name, not a path and name. If you
enter a path that
differs from the path that is specified in the Path parameter,
Rename-Item generates an error.
To rename and move an item, use Move-Item .

You can't use wildcard characters in the value of the NewName parameter. To specify
a name for
multiple files, use the Replace operator in a regular expression. For more
information about the
Replace operator, see about_Comparison_Operators.

Type: String

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-PassThru

Returns an object that represents the item to the pipeline. By default, this cmdlet
does not
generate any output.

Type: SwitchParameter

Position: Named
Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Path

Specifies the path of the item to rename.

Type: String

Position: 0

Default value: None

Accept pipeline input: True

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.

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs.


The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False


Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a string that contains a path to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

PSObject

When you use the PassThru parameter, this cmdlet returns an object representing the
renamed
item.

Notes
Windows PowerShell includes the following aliases for Rename-Item :

ren

rni

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

Related Links
Clear-Item
Copy-Item
Get-ChildItem
Get-Item
Invoke-Item
Move-Item
New-Item
Remove-Item
Rename-ItemProperty
Set-Item
about_Providers
Rename-ItemProperty
Reference
Module: Microsoft.PowerShell.Management

Renames a property of an item.

Syntax
PowerShell

Rename-ItemProperty

[-Path] <String>

[-Name] <String>

[-NewName] <String>

[-PassThru]

[-Force]

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Credential <PSCredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

PowerShell

Rename-ItemProperty

-LiteralPath <String>

[-Name] <String>

[-NewName] <String>

[-PassThru]

[-Force]

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Credential <PSCredential>]

[-WhatIf]

[-Confirm]

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

Examples

Example 1: Rename a registry entry


This command renames the config registry entry that is contained in the
"HKEY_LOCAL_MACHINE\Software\SmpApplication" key to "oldconfig".

PowerShell

Rename-ItemProperty -Path HKLM:\Software\SmpApplication -Name config -


NewName oldconfig

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Credential

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 are prompted for a password.
2 Warning

This parameter is not supported by any providers installed with Windows


PowerShell.

Type: PSCredential

Position: Named

Default value: Current user

Accept pipeline input: True

Accept wildcard characters: False

-Exclude

Specifies items that this cmdlet omits.


The value of this parameter qualifies the Path
parameter.
Enter a path element or pattern, such as "*.txt".
Wildcard characters are
permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Filter

Specifies a filter in the format or language of the provider.


The value of this
parameter qualifies the Path parameter.

The syntax of the filter, including the use of wildcard characters, depends on the
provider.
Filters are more efficient than other parameters, because the provider
applies them when the cmdlet gets the objects rather than having PowerShell filter
the objects after they are retrieved.

Type: String

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: True

-Force

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

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Include

Specifies only those items upon which the cmdlet acts, excluding all others.
The
value of this parameter qualifies the Path parameter.
Enter a path element or pattern,
such as "*.txt".
Wildcard characters are permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-LiteralPath

Specifies a path to the item.


Unlike the Path parameter, 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 PowerShell not to interpret any characters as escape sequences.

Type: String

Aliases: PSPath
Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies the current name of the property to rename.

Type: String

Aliases: PSProperty

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-NewName

Specifies the new name for the property.

Type: String

Position: 2

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-PassThru

Returns an object that represents the item property.


By default, this cmdlet does not
generate any output.

Type: SwitchParameter

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-Path

Specifies a path to the item.

Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

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

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs.


The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False


Accept wildcard characters: False

Inputs
String

You can pipe a string that contains a path, but not a literal path, to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

PSCustomObject

When you use the PassThru parameter, this cmdlet returns a PSCustomObject
representing the
renamed item property.

Notes
Windows PowerShell includes the following aliases for Rename-ItemProperty :

rnp

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

Related Links
Clear-ItemProperty
Copy-ItemProperty
Get-ItemProperty
Move-ItemProperty
New-ItemProperty
Remove-ItemProperty
Rename-Item
Set-ItemProperty
about_Providers
Reset-ComputerMachinePassword
Reference
Module: Microsoft.PowerShell.Management

Resets the machine account password for the computer.

Syntax
PowerShell

Reset-ComputerMachinePassword

[-Server <String>]

[-Credential <PSCredential>]
[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Reset-ComputerMachinePassword cmdlet changes the computer 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.

Examples

Example 1: Reset the password for the local computer


PowerShell

Reset-ComputerMachinePassword

This command resets the computer password for the local computer. The command
runs with the
credentials of the current user.

Example 2: Reset the password for the local computer by


using a specified domain controller
PowerShell
Reset-ComputerMachinePassword -Server "DC01" -Credential Domain01\Admin01

This command resets the computer password of the local computer by using the DC01
domain controller.
It uses the Credential parameter to specify a user account that has
permission to reset a computer
password in the domain.

Example 3: Reset the password on a remote computer


PowerShell

$cred = Get-Credential

Invoke-Command -ComputerName "Server01" -ScriptBlock {Reset-


ComputerMachinePassword -Credential $using:cred}

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 .

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Credential

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, this cmdlet prompts you for a
password.

This parameter was introduced in Windows PowerShell 3.0.

Type: PSCredential

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Server

Specifies the name of a domain controller to use when this cmdlet sets the computer
account
password.

This parameter is optional. If you omit this parameter, a domain controller is chosen
to service the
command.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


Inputs
None

You cannot pipe input to this cmdlet.

Outputs
None

This cmdlet does not generate any output.


Resolve-Path
Reference
Module: Microsoft.PowerShell.Management

Resolves the wildcard characters in a path, and displays the path contents.

Syntax
PowerShell

Resolve-Path

[-Path] <String[]>

[-Relative]

[-Credential <PSCredential>]

[-UseTransaction]

[<CommonParameters>]

PowerShell

Resolve-Path

-LiteralPath <String[]>

[-Relative]

[-Credential <PSCredential>]

[-UseTransaction]

[<CommonParameters>]

Description
The Resolve-Path cmdlet displays the items and containers that match the wildcard
pattern at the
location specified. The match can include files, folders, registry keys, or
any other object
accessible from a PSDrive provider.

Examples

Example 1: Resolve the home folder path


The tilde character ( ~ ) is shorthand notation for the current user's home folder. This
example
shows Resolve-Path returning the fully qualified path value.

PowerShell
PS C:\> Resolve-Path ~

Path

----

C:\Users\User01

Example 2: Resolve the path of the Windows folder


PowerShell

PS C:\> Resolve-Path -Path "windows"

Path

----

C:\Windows

When run from the root of the C: drive, this command returns the path of the Windows
folder in
the C: drive.

Example 3: Get all paths in the Windows folder


PowerShell

PS C:\> "C:\windows\*" | Resolve-Path

This command returns all the files and folders in the C:\Windows folder. The command
uses a
pipeline operator ( | ) to send a path string to Resolve-Path .

Example 4: Resolve a UNC path


PowerShell

PS C:\> Resolve-Path -Path "\\Server01\public"

This command resolves a Universal Naming Convention (UNC) path and returns the
shares in the path.

Example 5: Get relative paths


PowerShell
PS C:\> Resolve-Path -Path "c:\prog*" -Relative

.\Program Files

.\Program Files (x86)

.\programs.txt

This command returns relative paths for the directories at the root of the C: drive.

Example 6: Resolve a path containing brackets


This example uses the LiteralPath parameter to resolve the path of the Test[xml]
subfolder.
Using LiteralPath causes the brackets to be treated as normal characters
rather than a regular
expression.

PowerShell

PS C:\> Resolve-Path -LiteralPath 'test[xml]'

Parameters
-Credential

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 pass a PSCredential object.


You can
create a PSCredential object using the Get-Credential cmdlet. If you type a
user name, this
cmdlet prompts you for a password.

This parameter is not supported by any providers installed with PowerShell.

Type: PSCredential

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-LiteralPath
Specifies the path to be resolved. The value of the LiteralPath parameter is used
exactly as
typed. No characters are interpreted as wildcard characters. If the path
includes escape characters,
enclose it in single quotation marks ( ' ). Single quotation
marks tell PowerShell not to interpret
any characters as escape sequences.

Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Path

Specifies the PowerShell path to resolve. This parameter is required. You can also
pipe a path
string to Resolve-Path . Wildcard characters are permitted.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-Relative

Indicates that this cmdlet returns a relative path.

Type: SwitchParameter

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.

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a string that contains a path to this cmdlet.

Outputs
PathInfo

By default, this cmdlet returns a PathInfo object.

String

If you specify the Relative parameter, this cmdlet returns a string value for the resolved
path.

Notes
Windows PowerShell includes the following aliases for Resolve-Path :

rvpa

The *-Path cmdlets work with the FileSystem, Registry, and Certificate providers.

Resolve-Path is designed to work with any provider. To list the providers available in
your
session, type Get-PSProvider . For more information, see
about_providers.

Resolve-Path only resolves existing paths. It cannot be used to resolve a location that
does not
exist yet.
Related Links
Convert-Path
Join-Path
Split-Path
Test-Path
Restart-Computer
Reference
Module: Microsoft.PowerShell.Management

Restarts the operating system on local and remote computers.

Syntax
PowerShell

Restart-Computer

[-DcomAuthentication <AuthenticationLevel>]

[-Impersonation <ImpersonationLevel>]

[-WsmanAuthentication <String>]

[-Protocol <String>]

[[-ComputerName] <String[]>]

[[-Credential] <PSCredential>]

[-Force]

[-Wait]

[-Timeout <Int32>]

[-For <WaitForServiceTypes>]

[-Delay <Int16>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Restart-Computer

[-AsJob]

[-DcomAuthentication <AuthenticationLevel>]

[-Impersonation <ImpersonationLevel>]

[[-ComputerName] <String[]>]

[[-Credential] <PSCredential>]

[-Force]

[-ThrottleLimit <Int32>]

[-WhatIf]

[-Confirm]

[<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 at
the same time, and to force an immediate restart.

Starting in Windows PowerShell 3.0, you can wait for the restart to complete before you
run the next
command. Specify a waiting time-out and query interval, and wait for
particular services to be
available on the restarted computer. This feature makes it
practical to use Restart-Computer in
scripts and functions.

You can use the WS-Management (WSMan) protocol to restart the computer, in case
Distributed
Component Object Model (DCOM) calls are blocked, such as by an
enterprise firewall. For more
information, see WS-Management Protocol.

This cmdlet requires Windows PowerShell remoting only when you use the AsJob
parameter in a
command.

Examples

Example 1: Restart the local computer


Restart-Computer restarts the local computer.

PowerShell

Restart-Computer

Example 2: Restart multiple computers


Restart-Computer can restart remote and local computers. The ComputerName

parameter accepts an
array of computer names.

PowerShell

Restart-Computer -ComputerName Server01, Server02, localhost

Example 3: Restart computers as a background job


These commands run a Restart-Computer command as a background job on two
remote computers, and
then get the results.
Because AsJob creates the job on the local computer and automatically returns the
results to the
local computer, you can run Receive-Job as a local command.

PowerShell

$Job = Restart-Computer -ComputerName "Server01", "Server02" -AsJob

$Job | Receive-Job

Restart-Computer uses the ComputerName parameter to specify Server01 and

Server02. The
AsJob parameter runs the command as a background job. The job object
is stored in the $Job
variable. $Job is sent down the pipeline to the Receive-Job cmdlet
that gets the results.

Example 4: Restart a remote computer


Restart-Computer restarts a remote computer with customized impersonation and

authentication
settings.

PowerShell

Restart-Computer -ComputerName Server01 -Impersonation Anonymous -


DcomAuthentication PacketIntegrity

Restart-Computer uses the ComputerName parameter to specify Server01. The


Impersonation parameter specifies Anonymous to hide the requester's identity. The
DcomAuthentication parameter specifies PacketIntegrity as the connection's
authentication level.

Example 5: Force restart of computers listed in a text file


This example forces an immediate restart of the computers listed in the Domain01.txt
file. The
computer names from the text file are stored in a variable. The Force parameter
forces an
immediate restart and the ThrottleLimit parameter limits the number of
concurrent connections.

PowerShell

$Names = Get-Content -Path C:\Domain01.txt

$Creds = Get-Credential
Restart-Computer -ComputerName $Names -Credential $Creds -Force -
ThrottleLimit 10
Get-Content uses the Path parameter to get a list of computer names from a text file,

Domain01.txt. The computer names are stored in the variable $Names . Get-Credential
prompts
you for a username and password and stores the values in the variable $Creds .
Restart-Computer
uses the ComputerName and Credential parameters with their
variables. The Force
parameter causes an immediate restart of each computer. The
ThrottleLimit parameter limits the
command to 10 concurrent connections.

Example 6: Restart a remote computer and wait for


PowerShell
Restart-Computer restarts the remote computer and then waits up to 5 minutes (300

seconds) for
PowerShell to become available on the restarted computer before it
continues.

PowerShell

Restart-Computer -ComputerName Server01 -Wait -For PowerShell -Timeout 300 -


Delay 2

Restart-Computer uses the ComputerName parameter to specify Server01. The Wait

parameter waits for the restart to finish. The For specifies that PowerShell can run
commands on
the remote computer. The Timeout parameter specifies a five-minute
wait. The Delay parameter
queries the remote computer every two seconds to
determine whether it's restarted.

Example 7: Restart a computer by using the WSMan


Protocol
Restart-Computer restarts the remote computer by using the WSMan protocol instead
of the default,
DCOM. Kerberos authentication determines whether the current user has
permission to restart the
remote computer.

These settings are designed for enterprises in which DCOM-based restarts fail because
DCOM is
blocked. For example, by a firewall.

PowerShell

Restart-Computer -ComputerName Server01 -Protocol WSMan -WsmanAuthentication


Kerberos
Restart-Computer uses the ComputerName parameter to specify the remote computer,

Server01.
The Protocol parameter specifies to use the WSMan protocol. The
WsmanAuthentication
parameter specifies the authentication method as Kerberos.

Parameters
-AsJob

Indicates that Restart-Computer runs as a background job.

To use this parameter, the local and remote computers must be configured for
remoting. On Windows
Vista and later versions of the Windows operating system,
you must open PowerShell by using the
Run as Administrator option. For more
information, see about_Remote_Requirements.

When you specify 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 finishes. 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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ComputerName

Specifies one computer name or a comma-separated array of computer names.


Restart-Computer accepts
ComputerName objects from the pipeline or variables.

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 doesn't rely on PowerShell remoting. You can use the
ComputerName parameter even
if your computer isn't configured to run remote
commands.

If the ComputerName parameter isn't specified, Restart-Computer restarts the local


computer.

Type: String[]

Aliases: CN, __SERVER, Server, IPAddress

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running Restart-Computer .

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Credential

Specifies a user account that has permission to do this action. The default is the
current user.

Type a user name, such as User01 or Domain01\User01, or enter a PSCredential


object
generated by the Get-Credential cmdlet. If you type a user name, you're
prompted to enter the
password.

Credentials are stored in a PSCredential


object and the password is stored as a
SecureString.
7 Note

For more information about SecureString data protection, see


How secure is
SecureString?.

Type: PSCredential

Position: 1

Default value: Current user

Accept pipeline input: False

Accept wildcard characters: False

-DcomAuthentication

Specifies the authentication level that is used for the WMI connection. Restart-
Computer uses WMI.

Valid values are:

Call: Call-level COM authentication


Connect: Connect-level COM authentication
Default: Windows Authentication
None: No COM authentication
Packet: Packet-level COM authentication.
PacketIntegrity: Packet Integrity-level COM authentication
PacketPrivacy: Packet Privacy-level COM authentication.
Unchanged: The authentication level is the same as the previous command.

For more information, see AuthenticationLevel Enumeration.

This parameter is introduced in Windows PowerShell 3.0.

Type: AuthenticationLevel

Aliases: Authentication

Accepted values: Default, None, Connect, Call, Packet, PacketIntegrity,


PacketPrivacy, Unchanged

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-Delay

Specifies the frequency of queries, in seconds. PowerShell queries the service


specified by the
For parameter to determine whether the service is available after the
computer is restarted.

This parameter is valid only together with the Wait and For parameters.

This parameter was introduced in Windows PowerShell 3.0.

If the Delay parameter isn't specified, Restart-Computer uses a five second delay.

Type: Int16

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-For

Specifies the behavior of PowerShell as it waits for the specified service or feature to
become
available after the computer restarts. This parameter is only valid with the
Wait parameter.

The acceptable values for this parameter are:

Default: Waits for PowerShell to restart.


PowerShell: Can run commands in a PowerShell remote session on the
computer.
WMI: Receives a reply to a Win32_ComputerSystem query for the computer.
WinRM: Can establish a remote session to the computer by using WS-
Management.

This parameter was introduced in Windows PowerShell 3.0.

Type: WaitForServiceTypes

Accepted values: Wmi, WinRM, PowerShell


Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Force

Forces an immediate restart of the computer.

Type: SwitchParameter

Aliases: f

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Impersonation

Specifies the impersonation level that this cmdlet uses to call WMI. Restart-Computer
uses WMI.
The acceptable values for this parameter are:

Default: Default impersonation. Despite the name, this isn't the default value.
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.

Type: ImpersonationLevel

Accepted values: Default, Anonymous, Identify, Impersonate, Delegate

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Protocol
Specifies which protocol to use to restart the computers. The valid values are
WSMan and
DCOM.

This parameter is introduced in Windows PowerShell 3.0.

Type: String

Accepted values: DCOM, WSMan

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ThrottleLimit

Specifies the maximum number of concurrent connections that can be established to


run this command.
The throttle limit applies only to the current command, not to the
session or to the computer.

If the ThrottleLimit parameter isn't specified or a value of 0 is used, Restart-


Computer uses
a maximum of 32 concurrent connections.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Timeout

Specifies the duration of the wait, in seconds. When the timeout elapses, Restart-
Computer returns
to the command prompt, even if the computers aren't restarted.

The Timeout parameter is only valid with the Wait parameter. Timeout overrides the
Wait parameter's indefinite waiting period.

This parameter was introduced in Windows PowerShell 3.0.

Type: Int32
Aliases: TimeoutSec

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Wait

Restart-Computer suppresses the PowerShell prompt and blocks the pipeline until

the computers have


restarted. You can use this parameter in a script to restart
computers and then continue to process
when the restart is finished.

The Wait parameter waits indefinitely for the computers to restart. You can use
Timeout to
adjust the timing and the For and Delay parameters to wait for particular
services to become
available on the restarted computers.

The Wait parameter isn't valid when you're restarting the local computer. If the value
of the
ComputerName parameter contains the names of remote computers and the
local computer,
Restart-Computer generates a non-terminating error for Wait on the
local computer, but waits
for the remote computers to restart.

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the Restart-Computer runs. The Restart-Computer


cmdlet isn't run.

Type: SwitchParameter

Aliases: wi

Position: Named
Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-WsmanAuthentication

Specifies the mechanism that is used to authenticate the user credentials. This
parameter was
introduced in Windows PowerShell 3.0.

The acceptable values for this parameter are: Basic, CredSSP, Default, Digest,
Kerberos, and Negotiate.

For more information, see


AuthenticationMechanism.

2 Warning

Credential Security Service Provider (CredSSP) authentication, in which the user


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.

Type: String

Accepted values: Basic, CredSSP, Default, Digest, Kerberos, Negotiate

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a string that contains a computer name to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

System.Management.Automation.RemotingJob

When you use the AsJob parameter, this cmdlet returns a job object.

Notes
Restart-Computer only work on computers running Windows and requires WinRM
and WMI to shutdown a
system, including the local system.
Restart-Computer uses the Win32Shutdown method
of the Windows Management

Instrumentation (WMI) Win32_OperatingSystem


class. This method requires the
SeShutdownPrivilege privilege be enabled for the user account
used to restart the
machine.

In Windows PowerShell 2.0, the AsJob parameter doesn't work reliably when you are
restarting or
stopping remote computers. In Windows PowerShell 3.0, the
implementation is changed to resolve this
problem.

Related Links
About Windows Remote Management
Get-Credential
WS-Management Protocol
Restart-Service
Reference
Module: Microsoft.PowerShell.Management

Stops and then starts one or more services.

Syntax
PowerShell

Restart-Service

[-Force]

[-InputObject] <ServiceController[]>

[-PassThru]

[-Include <String[]>]

[-Exclude <String[]>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Restart-Service

[-Force]

[-Name] <String[]>

[-PassThru]

[-Include <String[]>]

[-Exclude <String[]>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Restart-Service

[-Force]

[-PassThru]

-DisplayName <String[]>

[-Include <String[]>]

[-Exclude <String[]>]

[-WhatIf]

[-Confirm]

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

Examples

Example 1: Restart a service on the local computer


PowerShell

PS C:\> Restart-Service -Name winmgmt

This command restarts the Windows Management Instrumentation service (WinMgmt)


on the local
computer.

Example 2: Exclude a service


PowerShell

PS C:\> Restart-Service -DisplayName "net*" -Exclude "net logon"

This command restarts the services that have a display name that starts with Net, except
for the Net
Logon service.

Example 3: Start all stopped network services


PowerShell

PS C:\> Get-Service -Name "net*" | Where-Object {$_.Status -eq "Stopped"} |


Restart-Service

This command starts all of the stopped network services on the computer.

This command uses the Get-Service cmdlet to get objects that represent the services
whose service
name starts with net. The pipeline operator ( | ) sends the services object
to the Where-Object
cmdlet, which selects only the services that have a status of
stopped. Another pipeline operator
sends the selected services to Restart-Service .

In practice, you would use the WhatIf parameter to determine the effect of the
command before
you run it.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-DisplayName

Specifies the display names of services to restarted. Wildcard characters are


permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Exclude

Specifies services that this cmdlet omits. The value of this parameter qualifies the
Name
parameter. Enter a name element or pattern, such as s*. Wildcard characters
are permitted.

Type: String[]
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Force

Forces the command to run without asking for user confirmation.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Include

Specifies services that this cmdlet restarts. The value of this parameter qualifies the
Name
parameter. Enter a name element or pattern, such as s*. Wildcard characters
are permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-InputObject

Specifies ServiceController objects that represent the services to restart. Enter a


variable
that contains the objects, or type a command or expression that gets the
objects.

Type: ServiceController[]

Position: 0
Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies the service names of the services to restart.

Type: String[]

Aliases: ServiceName

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-PassThru

Returns an object that represents the service. By default, this cmdlet does not
generate any output.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False


Accept pipeline input: False

Accept wildcard characters: False

Inputs
ServiceController

You can pipe a service object to this cmdlet.

String

You can pipe a string that contains a service name to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

ServiceController

When you use the PassThru parameter, this cmdlet returns a ServiceController object
representing the restarted service.

Notes
Restart-Service can control services only when the current user has permission to

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

Related Links
Get-Service
New-Service
Resume-Service
Set-Service
Start-Service
Stop-Service
Suspend-Service
Restore-Computer
Reference
Module: Microsoft.PowerShell.Management

Starts a system restore on the local computer.

Syntax
PowerShell

Restore-Computer

[-RestorePoint] <Int32>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Restore-Computer cmdlet restores the local computer to the specified system
restore point.

Restore-Computer restarts the computer. The restore is completed during the restart

operation.

System restore points and Restore-Computer are supported only on client operating
systems, such as
Windows 7, Windows Vista, and Windows XP.

Examples

Example 1: Restore the local computer


PowerShell

Restore-Computer -RestorePoint 253

This command restores the local computer to the restore point that has sequence
number 253.

Example 2: Restore the local computer with confirmation


PowerShell

PS> Restore-Computer -RestorePoint 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"):

This command restores the local computer to the restore point that has sequence
number 255. It uses
the Confirm parameter to prompt the user before actually
performing the operation.

Example 3: Restore a computer and check the status


PowerShell

Get-ComputerRestorePoint

Restore-Computer -RestorePoint 255

Get-ComputerRestorePoint -LastStatus

These commands run a system restore and then check its status.

The first command uses Get-ComputerRestorePoint to get the restore points on the local
computer.

The second command restores 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 Restore-Computer forces a restart,
this command would
be entered after the computer restarts.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named
Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-RestorePoint

Specifies the sequence number of the restore point. To find the sequence number,
use the
Get-ComputerRestorePoint cmdlet. This parameter is required.

Type: Int32

Aliases: SequenceNumber, SN, RP

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

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 the
Windows operating
system, open Windows PowerShell by using the Run as
administrator option.
This cmdlet uses the Windows Management Instrumentation (WMI)
SystemRestore class.

Related Links
Checkpoint-Computer
Disable-ComputerRestore
Enable-ComputerRestore
Get-ComputerRestorePoint
Restart-Computer
Resume-Service
Reference
Module: Microsoft.PowerShell.Management

Resumes one or more suspended (paused) services.

Syntax
PowerShell

Resume-Service

[-InputObject] <ServiceController[]>

[-PassThru]

[-Include <String[]>]

[-Exclude <String[]>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Resume-Service

[-Name] <String[]>

[-PassThru]

[-Include <String[]>]

[-Exclude <String[]>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Resume-Service

[-PassThru]

-DisplayName <String[]>

[-Include <String[]>]

[-Exclude <String[]>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Resume-Service cmdlet sends a resume message to the Windows Service Controller
for each of the
specified services. If a service is suspended, it resumes. If it is 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.

Examples

Example 1: Resume a service on the local computer


PowerShell

PS C:\> Resume-Service "sens"

This command resumes the System Event Notification service on the local computer.
The service name
is represented in the command by sens. 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: Resume all suspended services


PowerShell

PS C:\> Get-Service | Where-Object {$_.Status -eq "Paused"} | Resume-Service

This command resumes all of the suspended services on the computer. The Get-Service
cmdlet command
gets all of the services on the computer. The pipeline operator ( | )
passes the results to the
Where-Object cmdlet, which selects the services that have 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
you run it.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.


Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-DisplayName

Specifies the display names of the services to be resumed.


Wildcard characters are
permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Exclude

Specifies services that this cmdlet omits. The value of this parameter qualifies the
Name
parameter. Enter a name element or pattern, such as s*. Wildcard characters
are permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Include

Specifies services to resume. The value of this parameter qualifies Name parameter.
Enter a name
element or pattern, such as s*. Wildcard characters are permitted.
Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-InputObject

Specifies ServiceController objects that represent the services to resumed. Enter a


variable
that contains the objects, or type a command or expression that gets the
objects.

Type: ServiceController[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies the service names of the services to be resumed.

Type: String[]

Aliases: ServiceName

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-PassThru

Returns an object that represents the service. By default, this cmdlet does not
generate any output.

Type: SwitchParameter
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
ServiceController

You can pipe a service object to this cmdlet.

String

You can pipe a string that contains a service name to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

ServiceController

When you use the PassThru parameter, this cmdlet returns a ServiceController object
representing the resumed service.

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

Related Links
Get-Service
New-Service
Restart-Service
Set-Service
Start-Service
Stop-Service
Suspend-Service
Set-Clipboard
Reference
Module: Microsoft.PowerShell.Management

Sets the current Windows clipboard entry.

Syntax
PowerShell

Set-Clipboard

[-Append]

[-AsHtml]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Set-Clipboard

[-Value] <String[]>

[-Append]

[-AsHtml]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Set-Clipboard

[-Append]

-Path <String[]>

[-AsHtml]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Set-Clipboard

[-Append]

-LiteralPath <String[]>

[-AsHtml]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Set-Clipboard cmdlet sets the current Windows clipboard entry.

Examples

Example 1: Copy text to the clipboard


PowerShell

Set-Clipboard -Value "This is a test string"

Example 2: Copy the contents of a directory to the


clipboard
This example copies the content of the specified folder to the clipboard.

PowerShell

Set-Clipboard -Path "C:\Staging\"

Example 3: Copy the contents of a file to the clipboard


This example pipes the contents of a file to the clipboard. In this example, we are
getting a public
ssh key so that it can be pasted into another application, like GitHub.

PowerShell

Get-Content C:\Users\user1\.ssh\id_ed25519.pub | Set-Clipboard

Parameters
-Append

Indicates that the cmdlet does not clear the clipboard and appends content to it.
Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-AsHtml

Indicates that the cmdlet renders the content as HTML to the clipboard.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-LiteralPath

Specifies the path to the item that is copied to the clipboard. 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.
Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Path

Specifies the path to the item that is copied to the clipboard. Wildcard characters are
permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-Value

Specifies, as a string array, the content to copy to the clipboard.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi
Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a string containing the content to set to the clipboard to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
Windows PowerShell includes the following aliases for Set-Clipboard :

scb

In rare cases when using Set-Clipboard with a high number of values in rapid
succession, like in a
loop, you might sporadically get a blank value from the clipboard.
This can be fixed by using
Start-Sleep -Milliseconds 1 in the loop.

Related Links
Get-Clipboard
Set-Content
Reference
Module: Microsoft.PowerShell.Management

Writes new content or replaces existing content in a file.

Syntax
PowerShell

Set-Content

[-Path] <string[]>

[-Value] <Object[]>

[-PassThru]

[-Filter <string>]

[-Include <string[]>]

[-Exclude <string[]>]

[-Force]

[-Credential <pscredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[-NoNewline]

[-Encoding <FileSystemCmdletProviderEncoding>]

[-Stream <string>]

[<CommonParameters>]

PowerShell

Set-Content

[-Value] <Object[]>

-LiteralPath <string[]>

[-PassThru]

[-Filter <string>]

[-Include <string[]>]

[-Exclude <string[]>]

[-Force]

[-Credential <pscredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[-NoNewline]

[-Encoding <FileSystemCmdletProviderEncoding>]

[-Stream <string>]

[<CommonParameters>]

PowerShell
Set-Content

[-Path] <string[]>

[-Value] <Object[]>

[-PassThru]

[-Filter <string>]

[-Include <string[]>]

[-Exclude <string[]>]

[-Force]

[-Credential <pscredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

PowerShell

Set-Content

[-Value] <Object[]>

-LiteralPath <string[]>

[-PassThru]

[-Filter <string>]

[-Include <string[]>]

[-Exclude <string[]>]

[-Force]

[-Credential <pscredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

Description
Set-Content is a string-processing cmdlet that writes new content or replaces the

content in a
file. Set-Content replaces the existing content and differs from the Add-
Content cmdlet that
appends content to a file. To send content to Set-Content you can

use the Value parameter on


the command line or send content through the pipeline.

If you need to create files or directories for the following examples, see New-Item.

Examples

Example 1: Replace the contents of multiple files in a


directory
This example replaces the content for multiple files in the current directory.

PowerShell

Get-ChildItem -Path .\Test*.txt

Test1.txt

Test2.txt

Test3.txt

Set-Content -Path .\Test*.txt -Value 'Hello, World'

Get-Content -Path .\Test*.txt

Hello, World

Hello, World

Hello, World

The Get-ChildItem cmdlet uses the Path parameter to list .txt files that begin with
Test* in the current directory. The Set-Content cmdlet uses the Path parameter to

specify
the Test*.txt files. The Value parameter provides the text string Hello, World
that
replaces the existing content in each file. The Get-Content cmdlet uses the Path
parameter to
specify the Test*.txt files and displays each file's content in the
PowerShell console.

Example 2: Create a new file and write content


This example creates a new file and writes the current date and time to the file.

PowerShell

Set-Content -Path .\DateTime.txt -Value (Get-Date)

Get-Content -Path .\DateTime.txt

1/30/2019 09:55:08

Set-Content uses the Path and Value parameters to create a new file named

DateTime.txt
in the current directory. The Value parameter uses Get-Date to get the
current date and time.
Set-Content writes the DateTime object to the file as a string.
The Get-Content cmdlet uses
the Path parameter to display the content of DateTime.txt
in the PowerShell console.

Example 3: Replace text in a file


This command replaces all instances of word within an existing file.
PowerShell

Get-Content -Path .\Notice.txt

Warning

Replace Warning with a new word.

The word Warning was replaced.

(Get-Content -Path .\Notice.txt) |

ForEach-Object {$_ -Replace 'Warning', 'Caution'} |

Set-Content -Path .\Notice.txt

Get-Content -Path .\Notice.txt

Caution

Replace Caution with a new word.

The word Caution was replaced.

The Get-Content cmdlet uses the Path parameter to specify the Notice.txt file in the
current directory. The Get-Content command is wrapped with parentheses so that the
command
finishes before being sent down the pipeline.

The contents of the Notice.txt file are sent down the pipeline to the ForEach-Object
cmdlet.
ForEach-Object uses the automatic variable $_ and replaces each occurrence of
Warning with
Caution. The objects are sent down the pipeline to the Set-Content
cmdlet. Set-Content uses
the Path parameter to specify the Notice.txt file and writes
the updated content to the
file.

The last Get-Content cmdlet displays the updated file content in the PowerShell console.

Example 4: Use Filters with Set-Content


You can specify a filter to the Set-Content cmdlet. When using filters to qualify the Path
parameter, you need to include a trailing asterisk ( * ) to indicate the contents of the
path.

The following command set the content all *.txt files in the C:\Temp
directory to the
Value empty.

PowerShell

Set-Content -Path C:\Temp\* -Filter *.txt -Value "Empty"

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Credential

7 Note

This parameter is not supported by any providers installed with PowerShell.


To
impersonate another user, or elevate your credentials when running this cmdlet,
use Invoke-Command.

Type: PSCredential

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Encoding

This is a dynamic parameter made available by the FileSystem provider. For more
information, see
about_FileSystem_Provider.

Specifies the type of encoding for the target file. The default value is Default .

Encoding is a dynamic parameter that the FileSystem provider adds to Set-Content .


This parameter
works only in file system drives.

The acceptable values for this parameter are as follows:

Ascii Uses ASCII (7-bit) character set.


BigEndianUnicode Uses UTF-16 with the big-endian byte order.

BigEndianUTF32 Uses UTF-32 with the big-endian byte order.


Byte Encodes a set of characters into a sequence of bytes.

Default Uses the encoding that corresponds to the system's active code page
(usually ANSI).
Oem Uses the encoding that corresponds to the system's current OEM code

page.
String Same as Unicode .

Unicode Uses UTF-16 with the little-endian byte order.


Unknown Same as Unicode .

UTF7 Uses UTF-7.

UTF8 Uses UTF-8.


UTF32 Uses UTF-32 with the little-endian byte order.

Encoding is a dynamic parameter that the FileSystem provider adds to Set-Content .


This parameter
works only in file system drives.

Type: FileSystemCmdletProviderEncoding

Accepted values: ASCII, BigEndianUnicode, BigEndianUTF32, Byte, Default, OEM,


String, Unicode, Unknown, UTF7, UTF8, UTF32

Position: Named

Default value: Default

Accept pipeline input: False

Accept wildcard characters: False

-Exclude

Specifies, as a string array, an item or items that this cmdlet excludes in the
operation. The value
of this parameter qualifies the Path parameter. Enter a path
element or pattern, such as
*.txt . Wildcard characters 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.

Type: String[]

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: True

-Filter

Specifies a filter to qualify the Path parameter. The


FileSystem provider is the only
installed PowerShell provider that supports the use of filters. You can find the syntax
for the
FileSystem filter language in
about_Wildcards. Filters are more efficient
than
other parameters, because the provider applies them when the cmdlet gets the
objects rather
than having PowerShell filter the objects after they are retrieved.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Force

Forces 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. The Force parameter
does not override security restrictions.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Include

Specifies, as a string array, an item or items that this cmdlet includes in the
operation. The value
of this parameter qualifies the Path parameter. Enter a path
element or pattern, such as
"*.txt" . Wildcard characters 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.
Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-LiteralPath

Specifies a path to one or more locations. 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
PowerShell not to interpret any characters
as escape sequences.

For more information, see about_Quoting_Rules.

Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-NoNewline

This is a dynamic parameter made available by the FileSystem provider. For more
information, see
about_FileSystem_Provider.

The string representations of the input objects are concatenated to form the output.
No spaces or
newlines are inserted between the output strings. No newline is added
after the last output string.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-PassThru

Returns an object that represents the content. By default, this cmdlet does not
generate any output.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Path

Specifies the path of the item that receives the content.


Wildcard characters are
permitted.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-Stream

This is a dynamic parameter made available by the FileSystem provider. This


Parameter is only
available on Windows. For more information, see
about_FileSystem_Provider.

Specifies an alternative data stream for content. If the stream does not exist, this
cmdlet creates
it. Wildcard characters are not supported.

Stream is a dynamic parameter that the FileSystem provider adds to Set-Content .


This
parameter works only in file system drives.

You can use the Set-Content cmdlet to create or update the content of any alternate
data stream,
such as Zone.Identifier . However, we do not recommend this as a way
to eliminate security checks
that block files that are downloaded from the Internet. If
you verify that a downloaded file is
safe, use the Unblock-File cmdlet.

This parameter was introduced in PowerShell 3.0.

Type: String

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.

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Value

Specifies the new content for the item.

Type: Object[]

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
Object

You can pipe an object that contains the new value for the item to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

String

When you use the PassThru parameter, this cmdlet returns a string representing the
content.

Notes
Windows PowerShell includes the following aliases for Set-Content :

sc

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.
Related Links
about_Aliases
about_Automatic_Variables.md
about_Providers
about_Transactions
Add-Content
Clear-Content
Get-ChildItem
Get-Content
ForEach-Object
New-Item
Set-Item
Reference
Module: Microsoft.PowerShell.Management

Changes the value of an item to the value specified in the command.

Syntax
PowerShell

Set-Item

[-Path] <string[]>

[[-Value] <Object>]

[-Force]

[-PassThru]

[-Filter <string>]

[-Include <string[]>]

[-Exclude <string[]>]

[-Credential <pscredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

PowerShell

Set-Item

[[-Value] <Object>]

-LiteralPath <string[]>

[-Force]

[-PassThru]

[-Filter <string>]

[-Include <string[]>]

[-Exclude <string[]>]

[-Credential <pscredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

PowerShell

Set-Item

[-Path] <string[]>

[[-Value] <Object>]

[-Force]

[-PassThru]

[-Filter <string>]

[-Include <string[]>]

[-Exclude <string[]>]

[-Credential <pscredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[-Options <ScopedItemOptions>]
[<CommonParameters>]

PowerShell

Set-Item

[[-Value] <Object>]

-LiteralPath <string[]>

[-Force]

[-PassThru]

[-Filter <string>]

[-Include <string[]>]

[-Exclude <string[]>]

[-Credential <pscredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[-Options <ScopedItemOptions>]
[<CommonParameters>]

PowerShell

Set-Item

[-Path] <string[]>

[[-Value] <Object>]

[-Force]

[-PassThru]

[-Filter <string>]

[-Include <string[]>]

[-Exclude <string[]>]

[-Credential <pscredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[-Type <RegistryValueKind>]

[<CommonParameters>]

PowerShell

Set-Item

[[-Value] <Object>]

-LiteralPath <string[]>

[-Force]

[-PassThru]

[-Filter <string>]

[-Include <string[]>]

[-Exclude <string[]>]

[-Credential <pscredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[-Type <RegistryValueKind>]

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

Examples

Example 1: Create an alias


This command creates an alias of np for Notepad.

PowerShell

Set-Item -Path alias:np -Value "c:\windows\notepad.exe"

Example 2: Change the value of an environment variable


This command changes the value of the UserRole environment variable to
Administrator.

PowerShell

Set-Item -Path env:UserRole -Value "Administrator"

Example 3: Modify your prompt function


This command changes the prompt function so that it displays the time before the path.

PowerShell
Set-Item -Path function:prompt -Value {'PS '+ (Get-Date -Format t) + " " +
(Get-Location) + '> '}

Example 4: Set options for your prompt function


This command sets the AllScope and ReadOnly options for the prompt function.
This
command uses the Options dynamic parameter of Set-Item .
The Options parameter is
available in Set-Item only when you use it with the Alias or
Function provider.

PowerShell

Set-Item -Path function:prompt -Options "AllScope,ReadOnly"

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Credential

7 Note

This parameter is not supported by any providers installed with PowerShell.


To
impersonate another user, or elevate your credentials when running this cmdlet,
use Invoke-Command.

Type: PSCredential

Position: Named
Default value: Current user

Accept pipeline input: True

Accept wildcard characters: False

-Exclude

Specifies, as a string array, an item or items that this cmdlet excludes in the
operation. The value
of this parameter qualifies the Path parameter. Enter a path
element or pattern, such as
*.txt . Wildcard characters 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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Filter

Specifies a filter to qualify the Path parameter. The FileSystem


provider is the only
installed PowerShell provider that supports the use of filters. You can find
the syntax
for the FileSystem filter language in about_Wildcards.
Filters are more efficient than
other parameters, because the provider applies them when the cmdlet
gets the
objects rather than having PowerShell filter the objects after they are retrieved.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

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

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Include

Specifies, as a string array, an item or items that this cmdlet includes in the
operation. The value
of this parameter qualifies the Path parameter. Enter a path
element or pattern, such as
"*.txt" . Wildcard characters 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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-LiteralPath

Specifies a path to one or more locations. 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
PowerShell not to interpret any characters
as escape sequences.

For more information, see about_Quoting_Rules.

Type: String[]
Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Options

This is a dynamic parameter made available by the Alias and Function providers. For
more
information, see about_Alias_Provider
and about_Function_Provider.

Specifies the value of the Options property of an alias.

Valid values are:

None : The alias has no constraints (default value)

ReadOnly : The alias can be deleted but can't be changed without using the
Force parameter
Constant : The alias can't be deleted or changed

Private : The alias is available only in the current scope


AllScope : The alias is copied to any new scopes that are created

Unspecified : The option isn't specified

Type: ScopedItemOptions

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-PassThru

Passes an object that represents the item to the pipeline.


By default, this cmdlet does
not generate any output.

Type: SwitchParameter

Position: Named

Default value: False


Accept pipeline input: False

Accept wildcard characters: False

-Path

Specifies a path of the location of the items.


Wildcard characters are permitted.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-Type

This is a dynamic parameter made available by the Registry provider. The Registry
provider
and this parameter are only available on Windows.

Specifies the type of property that this cmdlet adds. The acceptable values for this
parameter are:

String : Specifies a null-terminated string. Used for REG_SZ values.

ExpandString : Specifies a null-terminated string that contains unexpanded


references to
environment variables that are expanded when the value is
retrieved. Used for REG_EXPAND_SZ
values.
Binary : Specifies binary data in any form. Used for REG_BINARY values.

DWord : Specifies a 32-bit binary number. Used for REG_DWORD values.

MultiString : Specifies an array of null-terminated strings terminated by two


null characters.
Used for REG_MULTI_SZ values.
Qword : Specifies a 64-bit binary number. Used for REG_QWORD values.
Unknown : Indicates an unsupported registry data type, such as

REG_RESOURCE_LIST values.

Type: RegistryValueKind

Position: Named

Default value: None

Accept pipeline input: True


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.

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Value

Specifies a new value for the item.

Type: Object

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs.


The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


Inputs
Object

You can pipe an object that represents the new value of the item to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

Object

When you use the PassThru parameter, this cmdlet returns an object representing the
item.

Notes
Windows PowerShell includes the following aliases for Set-Item :

si

Set-Item is not supported by the PowerShell FileSystem provider. To change the


values of items in
the file system, use the Set-Content cmdlet.

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 the New-Item and Rename-
Item cmdlet.
To change the names and data in registry values, use the New-ItemProperty ,
Set-ItemProperty , and
Rename-ItemProperty cmdlets.

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

Related Links
Clear-Item
Copy-Item
Get-Item
Invoke-Item
Move-Item
New-Item
Remove-Item
Rename-Item
about_Providers
Set-ItemProperty
Reference
Module: Microsoft.PowerShell.Management

Creates or changes the value of a property of an item.

Syntax
PowerShell

Set-ItemProperty

[-Path] <string[]>

[-Name] <string>

[-Value] <Object>

[-PassThru]

[-Force]

[-Filter <string>]

[-Include <string[]>]

[-Exclude <string[]>]

[-Credential <pscredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

PowerShell

Set-ItemProperty

[-Path] <string[]>

-InputObject <psobject>

[-PassThru]

[-Force]

[-Filter <string>]

[-Include <string[]>]

[-Exclude <string[]>]

[-Credential <pscredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

PowerShell

Set-ItemProperty

[-Name] <string>

[-Value] <Object>

-LiteralPath <string[]>

[-PassThru]

[-Force]

[-Filter <string>]

[-Include <string[]>]

[-Exclude <string[]>]

[-Credential <pscredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

PowerShell

Set-ItemProperty

-LiteralPath <string[]>

-InputObject <psobject>

[-PassThru]

[-Force]

[-Filter <string>]

[-Include <string[]>]

[-Exclude <string[]>]

[-Credential <pscredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

PowerShell

Set-ItemProperty

[-Path] <string[]>

[-Name] <string>

[-Value] <Object>

[-PassThru]

[-Force]

[-Filter <string>]

[-Include <string[]>]

[-Exclude <string[]>]

[-Credential <pscredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[-Type <RegistryValueKind>]

[<CommonParameters>]

PowerShell

Set-ItemProperty

[-Path] <string[]>

-InputObject <psobject>

[-PassThru]

[-Force]

[-Filter <string>]

[-Include <string[]>]

[-Exclude <string[]>]

[-Credential <pscredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[-Type <RegistryValueKind>]

[<CommonParameters>]

PowerShell

Set-ItemProperty

[-Name] <string>

[-Value] <Object>

-LiteralPath <string[]>

[-PassThru]

[-Force]

[-Filter <string>]

[-Include <string[]>]

[-Exclude <string[]>]

[-Credential <pscredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[-Type <RegistryValueKind>]

[<CommonParameters>]

PowerShell

Set-ItemProperty

-LiteralPath <string[]>

-InputObject <psobject>

[-PassThru]

[-Force]

[-Filter <string>]

[-Include <string[]>]

[-Exclude <string[]>]

[-Credential <pscredential>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[-Type <RegistryValueKind>]

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

Examples

Example 1: Set a property of a file


This command sets the value of the IsReadOnly property of the "final.doc" file to "true".
It uses Path to specify the file, Name to specify the name of the property, and the
Value
parameter to specify the new value.

The file is a System.IO.FileInfo object and IsReadOnly is just one of its properties.
To see
all of the properties, type Get-Item C:\GroupFiles\final.doc | Get-Member -MemberType
Property .

The $true automatic variable represents a value of "TRUE". For more information, see
about_Automatic_Variables.

PowerShell

Set-ItemProperty -Path C:\GroupFiles\final.doc -Name IsReadOnly -Value $true

Example 2: Create a registry entry and value


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

PowerShell

Set-ItemProperty -Path "HKLM:\Software\ContosoCompany" -Name "NoOfEmployees"


-Value 823

Get-ItemProperty -Path "HKLM:\Software\ContosoCompany"

PSPath :
Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software\contosocompa
ny

PSParentPath :
Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software

PSChildName : contosocompany

PSDrive : HKLM

PSProvider : Microsoft.PowerShell.Core\Registry

NoOfLocations : 2

NoOfEmployees : 823

Set-ItemProperty -Path "HKLM:\Software\ContosoCompany" -Name "NoOfEmployees"


-Value 824

Get-ItemProperty -Path "HKLM:\Software\ContosoCompany"

PSPath :
Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software\contosocompa
ny

PSParentPath :
Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software

PSChildName : contosocompany

PSDrive : HKLM

PSProvider : Microsoft.PowerShell.Core\Registry

NoOfLocations : 2

NoOfEmployees : 824

The first command creates the registry entry.


It uses Path to specify the path of the
HKLM: drive and the Software\MyCompany key.
The command uses Name to specify the

entry name and Value 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 how to use PowerShell to manage the registry, type Get-Help
Registry .

Example 3: Modify an item by using the pipeline


Th example uses Get-ChildItem to get the weekly.txt file. The file object is piped to
Set-ItemProperty . The Set-ItemProperty command uses the Name and Value
parameters to
specify the property and its new value.

PowerShell

Get-ChildItem weekly.txt | Set-ItemProperty -Name IsReadOnly -Value $True

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Credential

7 Note

This parameter is not supported by any providers installed with PowerShell.


To
impersonate another user, or elevate your credentials when running this cmdlet,
use Invoke-Command.

Type: PSCredential

Position: Named

Default value: Current user

Accept pipeline input: True

Accept wildcard characters: False

-Exclude
Specifies, as a string array, an item or items that this cmdlet excludes in the
operation. The value
of this parameter qualifies the Path parameter. Enter a path
element or pattern, such as
*.txt . Wildcard characters 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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Filter

Specifies a filter to qualify the Path parameter. The


FileSystem provider is the only
installed PowerShell provider that supports the use of filters. You can find the syntax
for the
FileSystem filter language in
about_Wildcards. Filters are more efficient
than
other parameters, because the provider applies them when the cmdlet gets the
objects rather
than having PowerShell filter the objects after they are retrieved.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Force

Forces the cmdlet to set a property on items that cannot otherwise be accessed by
the user.
Implementation varies by provider. For more information, see
about_Providers.

Type: SwitchParameter

Position: Named

Default value: False


Accept pipeline input: False

Accept wildcard characters: False

-Include

Specifies, as a string array, an item or items that this cmdlet includes in the
operation. The value
of this parameter qualifies the Path parameter. Enter a path
element or pattern, such as
"*.txt" . Wildcard characters 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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-InputObject

Specifies the object that has the properties that this cmdlet changes.
Enter a variable
that contains the object or a command that gets the object.

Type: PSObject

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-LiteralPath

Specifies a path to one or more locations. 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
PowerShell not to interpret any characters
as escape sequences.

For more information, see


about_Quoting_Rules.
Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies the name of the property.

Type: String

Aliases: PSProperty

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-PassThru

Returns an object that represents the item property.


By default, this cmdlet does not
generate any output.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Path

Specifies the path of the items with the property to modify.


Wildcard characters are
permitted.

Type: String[]
Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-Type

This is a dynamic parameter made available by the Registry provider. The Registry
provider
and this parameter are only available on Windows.

Specifies the type of property that this cmdlet adds. The acceptable values for this
parameter are:

String : Specifies a null-terminated string. Used for REG_SZ values.


ExpandString : Specifies a null-terminated string that contains unexpanded

references to
environment variables that are expanded when the value is
retrieved. Used for REG_EXPAND_SZ
values.
Binary : Specifies binary data in any form. Used for REG_BINARY values.

DWord : Specifies a 32-bit binary number. Used for REG_DWORD values.


MultiString : Specifies an array of null-terminated strings terminated by two

null characters.
Used for REG_MULTI_SZ values.
Qword : Specifies a 64-bit binary number. Used for REG_QWORD values.

Unknown : Indicates an unsupported registry data type, such as


REG_RESOURCE_LIST values.

Type: RegistryValueKind

Position: Named

Default value: None

Accept pipeline input: True

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.

Type: SwitchParameter
Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Value

Specifies the value of the property.

Type: Object

Position: 2

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs.


The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSObject

You can pipe objects to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

PSCustomObject

When you use the PassThru parameter, this cmdlet returns a PSCustomObject object
representing the item that was changed and its new property value.

Notes
Windows PowerShell includes the following aliases for Set-ItemProperty :

sp

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

Related Links
Clear-ItemProperty
Copy-ItemProperty
Get-ItemProperty
Move-ItemProperty
New-ItemProperty
Remove-ItemProperty
Rename-ItemProperty
about_Providers
Set-Location
Reference
Module: Microsoft.PowerShell.Management

Sets the current working location to a specified location.

Syntax
PowerShell

Set-Location

[[-Path] <String>]

[-PassThru]

[-UseTransaction]

[<CommonParameters>]

PowerShell

Set-Location

-LiteralPath <String>

[-PassThru]

[-UseTransaction]

[<CommonParameters>]

PowerShell

Set-Location

[-PassThru]

[-StackName <String>]

[-UseTransaction]

[<CommonParameters>]

Description
The Set-Location cmdlet sets the working location to a specified location. That location
could be
a directory, a subdirectory, a registry location, or any provider path.

You can also use the StackName parameter to make a named location stack the current
location
stack. For more information about location stacks, see the Notes.

Examples
Example 1: Set the current location
PowerShell

PS C:\> Set-Location -Path "HKLM:\"

PS HKLM:\>

This command sets the current location to the root of the HKLM: drive.

Example 2: Set the current location and display that


location
PowerShell

PS C:\> Set-Location -Path "Env:\" -PassThru

Path

----

Env:\

PS Env:\>

This command sets the current location to the root of the Env: drive. It uses the
PassThru
parameter to direct PowerShell to return a PathInfo object that represents the
Env:\ location.

Example 3: Set location to the current location in the C:


drive
PowerShell

PS C:\Windows\> Set-Location HKLM:\

PS HKLM:\> Set-Location C:

PS C:\Windows\>

The first command sets the location to the root of the HKLM: drive in the Registry
provider.
The second command sets the location to the current location of the C: drive
in the FileSystem
provider.
When the drive name is specified in the form <DriveName>:
(without backslash), the cmdlet sets
the location to the current location in the PSDrive.
To get the current location in the PSDrive use Get-Location -PSDrive <DriveName>
command.
Example 4: Set the current location to a named stack
PowerShell

PS C:\> Push-Location -Path 'C:\Program Files\PowerShell\' -StackName


"Paths"

PS C:\Program Files\PowerShell\> Set-Location -StackName "Paths"

PS C:\Program Files\PowerShell\> Get-Location -Stack

Path

----

C:\

The first command adds the current location to the Paths stack.
The second command
makes the Paths location stack the current location stack.
The third command displays
the locations in the current location stack.

The *-Location cmdlets use the current location stack unless a different location stack is
specified in the command. For information about location stacks, see the Notes.

Parameters
-LiteralPath

Specifies a path of the location. The value of the LiteralPath parameter is used
exactly as it
is typed. No characters are interpreted as wildcard characters. If the path
includes escape
characters, enclose it in single quotation marks. Single quotation
marks tell PowerShell not to
interpret any characters as escape sequences.

Type: String

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-PassThru

Returns a PathInfo object that represents the location. By default, this cmdlet does
not
generate any output.
Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Path

Specify the path of a new working location. If no path is provided, Set-Location


defaults to the
current user's home directory. When wildcards are used, the cmdlet
chooses the container (directory,
registry key, certificate store) that matches the
wildcard pattern. If the wildcard pattern matches
more than one container, the
cmdlet returns an error.

Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-StackName

Specifies an existing location stack name that this cmdlet makes the current location
stack. Enter
a location stack name. To indicate the unnamed default location stack,
type $null or an empty
string ( "" ).

Using this parameter does not change the current location. It only changes the stack
used by the
*-Location cmdlets. The *-Location cmdlets act on the current stack
unless you use the
StackName parameter to specify a different stack. For more
information about location stacks,
see the Notes.

Type: String

Position: Named

Default value: None

Accept pipeline input: True


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.

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a string that contains a path, but not a literal path, to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

PathInfo

When you use the PassThru parameter with Path or LiteralPath, this cmdlet returns a
PathInfo object representing the new location.

PathInfoStack

When you use the PassThru parameter with StackName, this cmdlet returns a
PathInfoStack
object representing the new stack context.

Notes
Windows PowerShell includes the following aliases for Set-Location :
cd

chdir
sl

PowerShell supports multiple runspaces per process. Each runspace has its own current
directory.
This is not the same as [System.Environment]::CurrentDirectory . This behavior
can be an issue
when calling .NET APIs or running native applications without providing
explicit directory paths.

Even if the location cmdlets did set the process-wide current directory, you can't depend
on it
because another runspace might change it at any time. You should use the location
cmdlets to perform
path-based operations using the current working directory specific
to the current runspace.

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.

A stack is a last-in, first-out list in which only the most recently added item can be
accessed. You
add items to a stack in the order that you use them, and then retrieve
them for use in the reverse
order. PowerShell lets you store provider locations in
location stacks. PowerShell creates an
unnamed default location stack. You can create
multiple named location stacks. If you do not specify
a stack name, PowerShell uses the
current location stack. By default, the unnamed default location
is the current location
stack, but you can use the Set-Location cmdlet to change the current
location stack.

To manage location stacks, use the *-Location cmdlets, as follows:

To add a location to a location stack, use the Push-Location cmdlet.

To get a location from a location stack, use the Pop-Location cmdlet.

To display the locations in the current location stack, use the Stack parameter of
the
Get-Location cmdlet. To display the locations in a named location stack, use
the StackName
parameter of Get-Location .

To create a new location stack, use the StackName parameter of Push-Location . If


you specify
a stack that does not exist, Push-Location creates the stack.

To make a location stack the current location stack, use the StackName parameter
of
Set-Location .
The unnamed default location stack is fully accessible only when it is the current location
stack.
If you make a named location stack the current location stack, you can no longer
use the
Push-Location or Pop-Location cmdlets to add or get items from the default
stack or use the
Get-Location cmdlet to display the locations in the unnamed stack. To
make the unnamed stack
the current stack, use the StackName parameter of the Set-
Location cmdlet with a value of
$null or an empty string ( "" ).

Related Links
Get-Location
Pop-Location
Push-Location
Set-Service
Reference
Module: Microsoft.PowerShell.Management

Starts, stops, and suspends a service, and changes its properties.

Syntax
PowerShell

Set-Service

[-ComputerName <String[]>]

[-Name] <String>

[-DisplayName <String>]

[-Description <String>]

[-StartupType <ServiceStartMode>]

[-Status <String>]

[-PassThru]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Set-Service

[-ComputerName <String[]>]

[-DisplayName <String>]

[-Description <String>]

[-StartupType <ServiceStartMode>]

[-Status <String>]

[-InputObject <ServiceController>]

[-PassThru]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Set-Service cmdlet changes the properties of a service such as the Status,
Description, DisplayName, and StartupType. Set-Service can start, stop, suspend, or
pause a service. To identify a service, enter its service name or submit a service object.
Or, send
a service name or service object down the pipeline to Set-Service .
Examples

Example 1: Change a display name


In this example, a service's display name is changed. To view the original display name,
use
Get-Service .

PowerShell

Set-Service -Name LanmanWorkstation -DisplayName "LanMan Workstation"

Set-Service uses the Name parameter to specify the service's name,


LanmanWorkstation. The
DisplayName parameter specifies the new display name,
LanMan Workstation.

Example 2: Change the startup type of services


This example shows how to change a service's startup type.

PowerShell

Set-Service -Name BITS -StartupType Automatic

Get-Service BITS | Select-Object -Property Name, StartType, Status

Name StartType Status

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

BITS Automatic Running

Set-Service uses the Name parameter to specify the service's name, BITS. The
StartupType parameter sets the service to Automatic.

Get-Service uses the Name parameter to specify the BITS service and sends the object
down
the pipeline. Select-Object uses the Property parameter to display the BITS
service's
status.

Example 3: Change the description of a service


This example changes the BITS service's description and displays the result.

The Get-CimInstance cmdlet is used because it returns a Win32_Service object that


includes the
service's Description.
PowerShell

Get-CimInstance Win32_Service -Filter 'Name = "BITS"' | Format-List Name,


Description

Name : BITS

Description : Transfers files in the background using idle network


bandwidth. If the service is

disabled, then any applications that depend on BITS, such as


Windows Update or MSN

Explorer, will be unable to automatically download programs


and other information.

Set-Service -Name BITS -Description "Transfers files in the background using


idle network bandwidth."

Get-CimInstance Win32_Service -Filter 'Name = "BITS"' | Format-List Name,


Description

Name : BITS

Description : Transfers files in the background using idle network


bandwidth.

Get-CimInstance sends the object down the pipeline to Format-List and displays the

service's
name and description. For comparison purposes, the command is run before
and after the description
is updated.

Set-Service uses the Name parameter to specify the BITS service. The Description

parameter specifies the updated text for the services' description.

Example 4: Start a service


In this example, a service is started.

PowerShell

Set-Service -Name WinRM -Status Running -PassThru

Status Name DisplayName

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

Running WinRM Windows Remote Management (WS-Manag...

Set-Service uses the Name parameter to specify the service, WinRM. The Status
parameter uses the value Running to start the service. The PassThru parameter outputs
a
ServiceController object that displays the results.

Example 5: Suspend a service


This example uses the pipeline to pause to service.

PowerShell

Get-Service -Name Schedule | Set-Service -Status Paused

Get-Service uses the Name parameter to specify the Schedule service, and sends the
object
down the pipeline. Set-Service uses the Status parameter to set the service to
Paused.

Example 6: Stop a service


This example uses a variable to stop a service.

PowerShell

$S = Get-Service -Name Schedule

Set-Service -InputObject $S -Status Stopped

Get-Service uses the Name parameter to specify the service, Schedule. The object is
stored
in the variable, $S . Set-Service uses the InputObject parameter and specifies
the object
stored $S . The Status parameter sets the service to Stopped.

Parameters
-ComputerName

Specifies one or more computers. For remote computers, type the NetBIOS name, an
IP address, or a
fully qualified domain name. If the ComputerName parameter isn't
specified, the command runs on
the local computer.

This parameter doesn't rely on PowerShell remoting. You can use the
ComputerName parameter even
if your computer isn't configured to run remote
commands.

Type: String[]

Aliases: cn

Position: Named

Default value: Local computer


Accept pipeline input: True

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running Set-Service .

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Description

Specifies a new description for the service.

The service description appears in Computer Management, Services. The


Description isn't a
property of the Get-Service ServiceController object. To see the
service description, use
Get-CimInstance that returns a Win32_Service object that
represents the service.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-DisplayName

Specifies a new display name for the service.

Type: String

Aliases: DN

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies a ServiceController object that represents the service to change. 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 use the pipeline to send a service
object to Set-Service .

Type: ServiceController

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies the service name of the service to be changed. Wildcard characters aren't
permitted. You
can use the pipeline to send a service name to Set-Service .

Type: String

Aliases: ServiceName, SN

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-PassThru

Returns a ServiceController object that represents the services that were changed.
By default,
Set-Service doesn't generate any output.

Type: SwitchParameter
Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-StartupType

Sets the startup type of the service. The acceptable values for this parameter are:

Automatic - The service is 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.
Manual - The service is started only manually, by a user, using the Service
Control Manager,
or by an application.
Boot - Indicates that the service is a device driver started by the system loader.
This
value is valid only for device drivers.
System - Indicates that the service is a device driver started by the
'IOInitSystem()'
function. This value is valid only for device drivers.

The default value is Automatic.

Type: ServiceStartMode

Aliases: StartMode, SM, ST

Accepted values: Boot, System, Automatic, Manual, Disabled

Position: Named

Default value: Automatic

Accept pipeline input: False

Accept wildcard characters: False

-Status

Specifies the status for the service.

The acceptable values for this parameter are as follows:


Paused. Suspends the service.
Running. Starts the service.
Stopped. Stops the service.

Type: String

Accepted values: Paused, Running, Stopped

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if Set-Service runs. The cmdlet isn't run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
ServiceController

You can pipe a service object to this cmdlet.

String

You can pipe a string that contains a service name to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.


ServiceController

When you use the PassThru parameter, this cmdlet returns a ServiceController object.

Notes
Set-Service requires elevated permissions. Use the Run as administrator option.

Set-Service can only control services when the current user has permissions to manage

services. If
a command doesn't work correctly, you might not have the required
permissions.

To find a service's service name or display name, use Get-Service . The service names are
in the
Name column and the display names are in the DisplayName column.

Related Links
Get-Service
New-Service
Restart-Service
Resume-Service
Start-Service
Stop-Service
Suspend-Service
Set-TimeZone
Reference
Module: Microsoft.PowerShell.Management

Sets the system time zone to a specified time zone.

Syntax
PowerShell

Set-TimeZone

[-Name] <String>

[-PassThru]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Set-TimeZone

-Id <String>

[-PassThru]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Set-TimeZone

[-InputObject] <TimeZoneInfo>

[-PassThru]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Set-TimeZone cmdlet sets the system time zone to a specified time zone.

Examples
Example 1: Set the time zone by Id
This example sets the time zone on the local computer to UTC.

PowerShell

Set-TimeZone -Id "UTC"

Id : UTC

DisplayName : (UTC) Coordinated Universal Time

StandardName : Coordinated Universal Time

DaylightName : Coordinated Universal Time

BaseUtcOffset : 00:00:00

SupportsDaylightSavingTime : False

Example 2: Set the time zone by name


This example sets the time zone on the local computer to UTC.

PowerShell

Set-TimeZone -Name 'Coordinated Universal Time' -PassThru

As we saw in the previous example, the Id and the Name of the Time Zone do not
always match.
The Name parameter must match the StandardName or DaylightName
properties of the
TimeZoneInfo object.

7 Note

The time zone names can vary based on the Culture settings in Windows. This
example shows the
values for a system set to en-US .

Example 3 - List all available time zones


A full list of Time Zone IDs can be obtained by running the following command:

PowerShell

Get-TimeZone -ListAvailable

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Id

Specifies the ID of the time zone that this cmdlet sets.

Type: String

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-InputObject

Specifies a TimeZoneInfo object to use as input.

Type: TimeZoneInfo

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies the name of the time zone that this cmdlet sets. A full list of Time Zone
names can be
obtained by running the following command: Get-TimeZone -
ListAvailable .

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-PassThru

Returns an object representing the item with which you are working. By default, this
cmdlet does not
generate any output.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

TimeZoneInfo
Outputs
None

By default, this cmdlet returns no output.

TimeZoneInfo

When you use the PassThru parameter, this cmdlet returns a TimeZoneInfo object.

Related Links
Get-TimeZone
Set-WmiInstance
Reference
Module: Microsoft.PowerShell.Management

Creates or updates an instance of an existing Windows Management Instrumentation


(WMI) class.

Syntax
PowerShell

Set-WmiInstance

[-Class] <String>

[-Arguments <Hashtable>]

[-PutType <PutType>]

[-AsJob]

[-Impersonation <ImpersonationLevel>]

[-Authentication <AuthenticationLevel>]

[-Locale <String>]

[-EnableAllPrivileges]

[-Authority <String>]

[-Credential <PSCredential>]

[-ThrottleLimit <Int32>]

[-ComputerName <String[]>]

[-Namespace <String>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Set-WmiInstance

-InputObject <ManagementObject>

[-Arguments <Hashtable>]

[-PutType <PutType>]

[-AsJob]

[-ThrottleLimit <Int32>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Set-WmiInstance

-Path <String>

[-Arguments <Hashtable>]

[-PutType <PutType>]

[-AsJob]

[-Impersonation <ImpersonationLevel>]

[-Authentication <AuthenticationLevel>]

[-Locale <String>]

[-EnableAllPrivileges]

[-Authority <String>]

[-Credential <PSCredential>]

[-ThrottleLimit <Int32>]

[-ComputerName <String[]>]

[-Namespace <String>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Set-WmiInstance

[-PutType <PutType>]

[-AsJob]

[-Impersonation <ImpersonationLevel>]

[-Authentication <AuthenticationLevel>]

[-Locale <String>]

[-EnableAllPrivileges]

[-Authority <String>]

[-Credential <PSCredential>]

[-ThrottleLimit <Int32>]

[-ComputerName <String[]>]

[-Namespace <String>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Set-WmiInstance

[-PutType <PutType>]

[-AsJob]

[-Impersonation <ImpersonationLevel>]

[-Authentication <AuthenticationLevel>]

[-Locale <String>]

[-EnableAllPrivileges]

[-Authority <String>]

[-Credential <PSCredential>]

[-ThrottleLimit <Int32>]

[-ComputerName <String[]>]

[-Namespace <String>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]
PowerShell

Set-WmiInstance

[-PutType <PutType>]

[-AsJob]

[-Impersonation <ImpersonationLevel>]

[-Authentication <AuthenticationLevel>]

[-Locale <String>]

[-EnableAllPrivileges]

[-Authority <String>]

[-Credential <PSCredential>]

[-ThrottleLimit <Int32>]

[-ComputerName <String[]>]

[-Namespace <String>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Set-WmiInstance cmdlet creates or updates an instance of an existing Windows
Management
Instrumentation (WMI) class. The created or updated instance is written to
the WMI repository.

New CIM cmdlets, introduced Windows PowerShell 3.0, perform the same tasks as the
WMI cmdlets. The
CIM cmdlets comply with WS-Management (WSMan) standards and
with the Common Information Model (CIM)
standard. this enables cmdlets to use the
same techniques to manage Windows-based computers and
those running other
operating systems. Instead of using Set-WmiInstance , consider using the Set-
CimInstance
or New-CimInstance cmdlets.

Examples

Example 1: Set WMI logging level


PowerShell

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 :

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 class information that is returned
reflects the new value.

Example 2: Create an environment variable and its value


PowerShell

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

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. This
operation requires appropriate
credentials and that you may have to restart Windows
PowerShell to see the new environment variable.

Example 3: Set WMI logging level for several remote


computers
PowerShell

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 :

...

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.

Parameters
-Arguments

Specifies the name of the property to be changed and the new value for that
property. The name and
value must be a name-value pair. The name-value pair is
passed on the command line as a hash table.
For example:

@{Setting1=1; Setting2=5; Setting3="test"}

Type: Hashtable

Aliases: Args, Property

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-AsJob

Indicates that this cmdlet runs as a background job. Use this parameter to run
commands that take a
long time to finish.

When you specify 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 is used for 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.

To use this parameter together 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 the Windows operating system. For more
information, see
about_Remote_Requirements.

For more information about Windows PowerShell background jobs, see about_Jobs
and about_Remote_Jobs.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Authentication

Specifies the authentication level that must be used with the WMI connection. The
acceptable values
for this parameter 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 start 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.

Type: AuthenticationLevel

Accepted values: Default, None, Connect, Call, Packet, PacketIntegrity,


PacketPrivacy, Unchanged

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Authority

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.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Class

Specifies the name of a WMI class.

Type: String

Position: 0

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-ComputerName

Specifies the name of the computer on which this cmdlet runs. 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 even if your computer is not configured to run remote
commands.

Type: String[]

Aliases: Cn

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Credential
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,
this cmdlet prompts for a password.

This parameter is not supported by any providers installed with parameter is not
supported by any
providers installed with Windows PowerShell.

Type: PSCredential

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-EnableAllPrivileges

Indicates that this cmdlet enables all the permissions of the current user before the
command it
makes the WMI call.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Impersonation

Specifies the impersonation level to use. The acceptable values for this parameter
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.

Type: ImpersonationLevel

Accepted values: Default, Anonymous, Identify, Impersonate, Delegate

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies a ManagementObject object to use as input.


When this parameter is used,
all other parameters ,except the Arguments parameter, are ignored.

Type: ManagementObject

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Locale

Specifies the preferred locale for WMI objects.


The Locale parameter is specified in
an array in the MS_<LCID> format in the preferred order.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Namespace
Specifies the WMI repository namespace where the referenced WMI class is located
when it is used
with the Class parameter.

Type: String

Aliases: NS

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Path

Specifies a WMI object path of the instance that you want to create or update.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-PutType

Indicates whether to create or update the WMI instance. The acceptable values for
this parameter
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.

Type: PutType

Accepted values: None, UpdateOnly, CreateOnly, UpdateOrCreate

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-ThrottleLimit

Specifies the maximum number of concurrent connections that can be established to


run this command.
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.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs.


The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

This cmdlet does not accept input.

Outputs
None

This cmdlet does not generate output.


Related Links
Get-WmiObject
Invoke-WmiMethod
Remove-WmiObject
Show-ControlPanelItem
Reference
Module: Microsoft.PowerShell.Management

Opens control panel items.

Syntax
PowerShell

Show-ControlPanelItem

[-Name] <String[]>

[<CommonParameters>]

PowerShell

Show-ControlPanelItem

-CanonicalName <String[]>

[<CommonParameters>]

PowerShell

Show-ControlPanelItem

[[-InputObject] <ControlPanelItem[]>]

[<CommonParameters>]

Description
The Show-ControlPanelItem cmdlet opens control panel items on the local computer.
You can use it
to open control panel items by name, category, or description, even on
systems that do not have a
user interface. You can pipe control panel items from the
Get-ControlPanelItem cmdlet to
Show-ControlPanelItem .

Show-ControlPanelItem searches only control panel items that can be opened on the

system. On
computers that do not have Control Panel or File Explorer, Show-
ControlPanelItem searches
only control panel items that can open without these

components.

This cmdlet was introduced in Windows PowerShell 3.0 and works on Windows 8,
Windows Server 2012,
and higher versions.
Examples

Example 1: Show a control panel item


This example launches the AutoPlay control panel item.

PowerShell

Show-ControlPanelItem -Name "AutoPlay"

Example 2: Pipe a control panel item to this cmdlet


This example opens the Windows Defender Firewall control panel item on the local
computer.
The name of the Windows Firewall control panel item has changed over the
versions of Windows. This
example uses a wildcard pattern to find the control panel
item.

PowerShell

Get-ControlPanelItem -Name "*Firewall" | Show-ControlPanelItem

Get-ControlPanelItem gets the control panel item and the Show-ControlPanelItem

cmdlet opens
it.

Example 3: Use a file name to open a control panel item


This example opens the Programs and Features control panel item by using its
application name.

PowerShell

appwiz.cpl

This method is an alternative to using a Show-ControlPanelItem command.

7 Note

In PowerShell, you can omit the .cpl file extension for control panel files because it's
included
in the value of the $env:PathExt environment variable.
Parameters
-CanonicalName

Specifies control panel items by using the specified canonical names or name
patterns. Wildcard
characters are permitted. If you enter multiple names, this cmdlet
opens control panel items that
match any of the names, as if the items in the name
list were separated by an OR operator.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-InputObject

Specifies control panel items to open by submitting control panel item objects. Enter
a variable
that contains control panel item objects, or type a command or expression
that gets control panel
item objects, such as Get-ControlPanelItem .

Type: ControlPanelItem[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies names of control panel items. Wildcard characters are permitted. If you
enter multiple
names, this cmdlet opens control panel items that match any of the
names, as if the items in the
name list were separated by an OR operator.

Type: String[]

Position: 0

Default value: None


Accept pipeline input: True

Accept wildcard characters: True

Inputs
System.String, Microsoft.PowerShell.Commands.ControlPanelItem

You can pipe a name or control panel item object to this cmdlet.

Outputs
None

This cmdlet does not return any output.

Related Links
Get-ControlPanelItem
Show-EventLog
Reference
Module: Microsoft.PowerShell.Management

Displays the event logs of the local or a remote computer in Event Viewer.

Syntax
PowerShell

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 the Windows operating
system, 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 the Windows operating system, use the Get-
WinEvent cmdlet.

Examples

Example 1: Display event logs for the local computer


PowerShell

Show-EventLog

This command opens Event Viewer and displays in it the classic event logs on the local
computer.
Example 2: Display event logs for a remote computer
PowerShell

Show-EventLog -ComputerName "Server01"

This command opens Event Viewer and displays in it the classic event logs on the
Server01 computer.

Parameters
-ComputerName

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 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 even if your computer is not configured to run remote
commands.

Type: String

Aliases: CN

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

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.

Related Links
Clear-EventLog
Get-EventLog
Limit-EventLog
New-EventLog
Remove-EventLog
Write-EventLog
Split-Path
Reference
Module: Microsoft.PowerShell.Management

Returns the specified part of a path.

Syntax
PowerShell

Split-Path

[-Path] <String[]>

[-Parent]

[-Resolve]

[-Credential <PSCredential>]
[-UseTransaction]

[<CommonParameters>]

PowerShell

Split-Path

[-Path] <String[]>

[-NoQualifier]

[-Resolve]

[-Credential <PSCredential>]
[-UseTransaction]

[<CommonParameters>]

PowerShell

Split-Path

[-Path] <String[]>

[-Leaf]

[-Resolve]

[-Credential <PSCredential>]
[-UseTransaction]

[<CommonParameters>]

PowerShell

Split-Path

[-Path] <String[]>

[-Qualifier]

[-Resolve]

[-Credential <PSCredential>]
[-UseTransaction]

[<CommonParameters>]

PowerShell

Split-Path

[-Path] <String[]>

[-Resolve]

[-IsAbsolute]

[-Credential <PSCredential>]
[-UseTransaction]

[<CommonParameters>]

PowerShell

Split-Path

-LiteralPath <String[]>

[-Resolve]

[-Credential <PSCredential>]
[-UseTransaction]

[<CommonParameters>]

Description
The Split-Path cmdlet returns only the specified part of a path, such as the parent
folder, a
subfolder, or a file name. It can also get items that are referenced by the split
path and tell
whether the path is relative or absolute.

You can use this cmdlet to get or submit only a selected part of a path.

Examples

Example 1: Get the qualifier of a path


PowerShell

Split-Path -Path "HKCU:\Software\Microsoft" -Qualifier

HKCU:

This command returns only the qualifier of the path. The qualifier is the drive.
Example 2: Display file names
PowerShell

Split-Path -Path "C:\Test\Logs\*.log" -Leaf -Resolve

Pass1.log

Pass2.log

...

This command displays the files that are referenced by the split path. Because this path
is split to
the last item, also known as the leaf, the command displays only the file
names.

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 that represent the files.

Example 3: Get the parent container


PowerShell

Split-Path -Path "C:\WINDOWS\system32\WindowsPowerShell\V1.0\about_*.txt"

C:\WINDOWS\system32\WindowsPowerShell\V1.0

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: Determines whether a path is absolute


PowerShell

Split-Path -Path ".\My Pictures\*.jpg" -IsAbsolute

False

This command determines whether the path is relative or absolute. In this case, because
the path is
relative to the current folder, which is represented by a dot ( . ), it returns
$False.
Example 5: Change location to a specified path
PowerShell

PS C:> Set-Location (Split-Path -Path $profile)

PS C:\Documents and Settings\User01\My Documents\WindowsPowerShell>

This command changes your location to the folder that contains the PowerShell profile.

The command in parentheses uses Split-Path to return only the parent of the path
stored in the
built-in $Profile variable. The Parent parameter is the default split
location parameter.
Therefore, you can omit it from the command. The parentheses
direct PowerShell to run the command
first. This is a useful way to move to a folder that
has a long path name.

Example 6: Split a path by using the pipeline


PowerShell

'C:\Documents and Settings\User01\My Documents\My Pictures' | Split-Path

C:\Documents and Settings\User01\My Documents

This command uses a pipeline operator ( | ) to send a path to Split-Path .


The path is
enclosed in quotation marks to indicate that it is a single token.

Parameters
-Credential

7 Note

This parameter is not supported by any providers installed with PowerShell.


To
impersonate another user, or elevate your credentials when running this cmdlet,
use Invoke-Command.

Type: PSCredential

Position: Named

Default value: None


Accept pipeline input: True

Accept wildcard characters: False

-IsAbsolute

Indicates that this cmdlet 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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Leaf

Indicates that this cmdlet 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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-LiteralPath

Specifies the paths to be split. Unlike Path, the value of LiteralPath is used exactly as
it
is typed. No characters are interpreted as wildcard characters. If the path includes
escape
characters, enclose it in single quotation marks. Single quotation marks tell
PowerShell not to
interpret any characters as escape sequences.

Type: String[]

Aliases: PSPath

Position: Named
Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-NoQualifier

Indicates that this cmdlet 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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Parent

Indicates that this cmdlet 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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Path

Specifies the paths to be split. Wildcard characters are permitted. If the path includes
spaces,
enclose it in quotation marks. You can also pipe a path to this cmdlet.

Type: String[]

Position: 0
Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-Qualifier

Indicates that this cmdlet 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:.

Type: SwitchParameter

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Resolve

Indicates that this cmdlet displays the items that are referenced by the resulting split
path
instead of displaying the path elements.

Type: SwitchParameter

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.

Type: SwitchParameter

Aliases: usetx

Position: Named
Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a string that contains a path to this cmdlet.

Outputs
String

This cmdlet returns text strings. When you specify the Resolve parameter, it 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.

Boolean

When you specify the IsAbsolute parameter, this cmdlet returns a Boolean value.

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) work with path names
and return
the names in a concise format that all 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 in the way that
you would use Dirname, Normpath, Realpath, Join,
or other path manipulators.

You can use the Path cmdlets together with several providers. These include the
FileSystem,
Registry, and Certificate providers.

Split-Path 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.
Related Links
Convert-Path
Join-Path
Resolve-Path
Test-Path
Start-Process
Reference
Module: Microsoft.PowerShell.Management

Starts one or more processes on the local computer.

Syntax
PowerShell

Start-Process

[-FilePath] <string>

[[-ArgumentList] <string[]>]
[-Credential <pscredential>]
[-WorkingDirectory <string>]
[-LoadUserProfile]

[-NoNewWindow]

[-PassThru]

[-RedirectStandardError <string>]

[-RedirectStandardInput <string>]

[-RedirectStandardOutput <string>]

[-WindowStyle <ProcessWindowStyle>]

[-Wait]

[-UseNewEnvironment]

[<CommonParameters>]

PowerShell

Start-Process

[-FilePath] <string>

[[-ArgumentList] <string[]>]
[-WorkingDirectory <string>]
[-PassThru]

[-Verb <string>]

[-WindowStyle <ProcessWindowStyle>]

[-Wait]

[<CommonParameters>]

Description
The Start-Process cmdlet starts one or more processes on the local computer. By
default,
Start-Process creates a new process that inherits all the environment variables
that are defined
in the current process.
To specify the program that runs in the process, enter an executable file or script file, or
a file
that can be opened using a program on the computer. If you specify a non-
executable file,
Start-Process starts the program that's associated with the file, similar
to 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.

Examples

Example 1: Start a process that uses default values


This example starts a process that uses the Sort.exe file in the current folder. The
command uses
all the default values, including the default window style, working folder,
and credentials.

PowerShell

Start-Process -FilePath "sort.exe"

Example 2: Print a text file


This example starts a process that prints the C:\PS-Test\MyFile.txt file.

PowerShell

Start-Process -FilePath "myfile.txt" -WorkingDirectory "C:\PS-Test" -Verb


Print

Example 3: Start a process to sort items to a new file


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

PowerShell

$processOptions = @{

FilePath = "sort.exe"

RedirectStandardInput = "TestSort.txt"

RedirectStandardOutput = "Sorted.txt"

RedirectStandardError = "SortError.txt"

UseNewEnvironment = $true

Start-Process @processOptions

This example uses splatting to pass parameters to the cmdlet. For more information, see
about_Splatting.

Example 4: Start a process in a maximized window


This example starts the Notepad.exe process. It maximizes the window and retains the
window until
the process completes.

PowerShell

Start-Process -FilePath "notepad" -Wait -WindowStyle Maximized

Example 5: Start PowerShell as an administrator


This example starts PowerShell using the Run as administrator option.

PowerShell

Start-Process -FilePath "powershell" -Verb RunAs

Example 6: Using different verbs to start a process


This example shows how to find the verbs that can be used when starting a process. The
available
verbs are determined by the filename extension of the file that runs in the
process.

PowerShell

$startExe = New-Object System.Diagnostics.ProcessStartInfo -Args


powershell.exe

$startExe.verbs

open

runas

runasuser
The example uses New-Object to create a System.Diagnostics.ProcessStartInfo object
for
powershell.exe , the file that runs in the PowerShell process. The Verbs property of
the
ProcessStartInfo object shows that you can use the Open and RunAs verbs with
powershell.exe , or with any process that runs a .exe file.

Example 7: Specifying arguments to the process


Both commands start the Windows command interpreter, issuing a dir command on
the Program Files
folder. Because this foldername contains a space, the value needs
surrounded with escaped quotes.
Note that the first command specifies a string as
ArgumentList. The second command is a string
array.

PowerShell

Start-Process -FilePath "$env:comspec" -ArgumentList "/c dir


`"%SystemDrive%\Program Files`""

Start-Process -FilePath "$env:comspec" -ArgumentList


"/c","dir","`"%SystemDrive%\Program Files`""

Example 8: Run a command as an Administrator using


alternate credentials
On Windows, you can run Start-Process -Verb RunAs to start a process with elevated
permissions.
This elevates the current user's context. The Credential parameter allows
you to specify an
alternate username and password, allowing you to start a process in a
different user content.
However, the Credential and Verb parameters can't be used
together.

To start a process with elevated rights, using alternate credentials, you must first start
PowerShell using the alternate credentials, then use Start-Process to start the process
with
elevated rights.

PowerShell

$cred = Get-Credential

$args = '-noprofile -command "Start-Process cmd.exe -Verb RunAs -args /k"'

Start-Process pwsh.exe -Credential $cred -WindowStyle Hidden -ArgumentList


$args

The example starts cmd.exe with elevated permissions from a PowerShell session that is
running
under alternate credentials.
Parameters
-ArgumentList

Specifies parameters or parameter values to use when this cmdlet starts the process.
Arguments can
be accepted as a single string with the arguments separated by
spaces, or as an array of strings
separated by commas. The cmdlet joins the array
into a single string with each element of the array
separated by a single space.

The outer quotes of the PowerShell strings aren't included when the ArgumentList
values are
passed to the new process. If parameters or parameter values contain a
space or quotes, they need to
be surrounded with escaped double quotes. For more
information, see
about_Quoting_Rules.

For the best results, use a single ArgumentList value containing all the arguments
and any
needed quote characters.

Type: String[]

Aliases: Args

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Credential

Specifies a user account that has permission to perform this action. By default, the
cmdlet uses the
credentials of the current user.

Type a user name, such as User01 or Domain01\User01, or enter a PSCredential


object
generated by the Get-Credential cmdlet. If you type a user name, you're
prompted to enter the
password.

Credentials are stored in a PSCredential


object and the password is stored as a
SecureString.

7 Note

For more information about SecureString data protection, see


How secure is
SecureString?.
Type: PSCredential

Aliases: RunAs

Position: Named

Default value: Current user

Accept pipeline input: False

Accept wildcard characters: False

-FilePath

Specifies the optional path and filename 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's associated with a
program on the computer. This parameter is required.

If you specify only a filename, use the WorkingDirectory parameter to specify the
path.

Type: String

Aliases: PSPath

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-LoadUserProfile

Indicates that this cmdlet loads the Windows user profile stored in the HKEY_USERS
registry key
for the current user.

This parameter doesn't affect the PowerShell profiles. For more information, see
about_Profiles.

Type: SwitchParameter

Aliases: Lup

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-NoNewWindow

Start the new process in the current console window. By default on Windows,
PowerShell opens a new
window.

You can't use the NoNewWindow and WindowStyle parameters in the same
command.

Type: SwitchParameter

Aliases: nnw

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-PassThru

Returns a process object for each process that the cmdlet started. By default, this
cmdlet doesn't
generate any output.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RedirectStandardError

Specifies a file. This cmdlet sends any errors generated by the process to a file that
you specify.
Enter the path and filename. By default, the errors are displayed in the
console.

Type: String
Aliases: RSE

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RedirectStandardInput

Specifies a file. This cmdlet reads input from the specified file. Enter the path and
filename of
the input file. By default, the process gets its input from the keyboard.

Type: String

Aliases: RSI

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RedirectStandardOutput

Specifies a file. This cmdlet sends the output generated by the process to a file that
you specify.
Enter the path and filename. By default, the output is displayed in the
console.

Type: String

Aliases: RSO

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-UseNewEnvironment
Indicates that this cmdlet uses new environment variables specified for the process.
By default, the
started process runs with the environment variables inherited from
the parent process.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Verb

Specifies a verb to use when this cmdlet starts the process. The verbs that are
available are
determined by the filename extension of the file that runs in the
process.

The following table shows the verbs for some common process file types.

File type Verbs

.cmd Edit , Open , Print , RunAs , RunAsUser

.exe Open , RunAs , RunAsUser

.txt Open , Print , PrintTo

.wav Open , Play

To find the verbs that can be used with the file that runs in a process, use the New-
Object cmdlet
to create a System.Diagnostics.ProcessStartInfo object for the file.
The available verbs are in
the Verbs property of the ProcessStartInfo object. For
details, see the examples.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-Wait

Indicates that this cmdlet waits for the specified process and its descendants to
complete before
accepting more input. This parameter suppresses the command
prompt or retains the window until the
processes finish.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WindowStyle

Specifies the state of the window that's used for the new process. The default value
is Normal .
The acceptable values for this parameter are:

Normal
Hidden

Minimized
Maximized

You can't use the WindowStyle and NoNewWindow parameters in the same
command.

Type: ProcessWindowStyle

Accepted values: Normal, Hidden, Minimized, Maximized

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WorkingDirectory

Specifies the location that the new process should start in. The default is the location
of the
executable file or document being started. Wildcards aren't supported. The
path must not contain
characters that would be interpreted as wildcards.
Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

Process

When you use the PassThru parameter, this cmdlet returns a Process object.

Notes
Windows PowerShell includes the following aliases for Start-Process :

saps

start

Native commands are executable files installed in the operating system. These
executables can be run
from any command-line shell, like PowerShell. Usually you run
the command exactly as you would in
bash or cmd.exe . The Start-Process cmdlet can
be used to run any native commands, but should
only be used when you need to
control how the command is executed.

By default, Start-Process launches a process asynchronously. Control is instantly


returned to
PowerShell even if the new process is still running.

On the local system, the launched process lives on independent from the calling
process.
On a remote system, the new process is terminated when the remote session ends,
immediately
following the Start-Process command. Therefore, you can't use
Start-Process in a remote
session expecting the launched process to outlive the

session.

If you do need to use Start-Process in a remote session, invoke it with the Wait
parameter. Or
you could use other methods to create a new process on the remote
system.

When using the Wait parameter, Start-Process waits for the process tree (the process
and all
its descendants) to exit before returning control. This is different than the
behavior of the
Wait-Process cmdlet, which only waits for the specified processes to
exit.

On Windows, the most common use case for Start-Process is to use the Wait
parameter to block
progress until the new process exits. On non-Windows system, this
is rarely needed since the default
behavior for command-line applications is equivalent
to Start-Process -Wait .

This cmdlet is implemented using the Start method of the System.Diagnostics.Process


class. For more information about this method, see
Process.Start Method.

Related Links
about_Quoting_Rules
Debug-Process
Get-Process
Start-Service
Stop-Process
Wait-Process
Start-Service
Reference
Module: Microsoft.PowerShell.Management

Starts one or more stopped services.

Syntax
PowerShell

Start-Service

[-InputObject] <ServiceController[]>

[-PassThru]

[-Include <String[]>]

[-Exclude <String[]>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Start-Service

[-Name] <String[]>

[-PassThru]

[-Include <String[]>]

[-Exclude <String[]>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Start-Service

[-PassThru]

-DisplayName <String[]>

[-Include <String[]>]

[-Exclude <String[]>]

[-WhatIf]

[-Confirm]

[<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 that represents the
services that you want to start.

Examples

Example 1: Start a service by using its name


This example starts the EventLog service on the local computer. The Name parameter
identifies
the service by its service name.

PowerShell

Start-Service -Name "eventlog"

Example 2: Display information without starting a service


This example shows what would occur if you started the services that have a display
name that
includes "remote".

PowerShell

Start-Service -DisplayName *remote* -WhatIf

The DisplayName parameter identifies the services by their display name instead of
their service
name. The WhatIf parameter causes the cmdlet to display what would
happen when you run the
command but does not make changes.

Example 3: Start a service and record the action in a text


file
This example starts the Windows Management Instrumentation (WMI) service on the
computer and adds a
record of the action to the services.txt file.

PowerShell

$s = Get-Service wmi

Start-Service -InputObject $s -PassThru | Format-List >> services.txt


First we use Get-Service to get an object that represent the WMI service and store it in
the $s
variable. Next, we start the service. Without the PassThru parameter, Start-
Service does not
create any output. The pipeline operator ( | ) passes the object output

by Start-Service to the
Format-List cmdlet to format the object as a list of its
properties. The append redirection
operator ( >> ) redirects the output to the services.txt
file. The output is added to the end of the
existing file.

Example 4: Start a disabled service


This example shows how to start a service when the start type of the service is Disabled.

PowerShell

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

PS> Get-CimInstance win32_service | Where-Object Name -eq "tlntsvr"

ExitCode : 0

Name : TlntSvr

ProcessId : 0

StartMode : Disabled

State : Stopped

Status : OK

PS> Set-Service tlntsvr -StartupType manual

PS> Start-Service tlntsvr

The first attempt to start the Telnet service (tlntsvr) fails. The Get-CimInstance command
shows
that the StartMode property of the Tlntsvr service is Disabled. The Set-Service
cmdlet
changes the start type to Manual. Now, we can resubmit the Start-Service
command. This time,
the command succeeds. To verify that the command succeeded,
run Get-Service .

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter
Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-DisplayName

Specifies the display names of the services to start. Wildcard characters are
permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Exclude

Specifies services that this cmdlet omits. The value of this parameter qualifies the
Name
parameter. Enter a name element or pattern, such as s* . Wildcard characters
are permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Include

Specifies services that this cmdlet starts. The value of this parameter qualifies the
Name
parameter. Enter a name element or pattern, such as s* . Wildcard characters
are permitted.

Type: String[]
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-InputObject

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.

Type: ServiceController[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

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.

Type: String[]

Aliases: ServiceName

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-PassThru

Returns an object that represents the service. By default, this cmdlet does not
generate any output.
Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs.


The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
ServiceController

You can pipe a service object to this cmdlet.

String

You can pipe a string that contains the service name to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

ServiceController

When you use the PassThru parameter, this cmdlet returns a ServiceController object
representing the service.
Notes
Windows PowerShell includes the following aliases for Start-Service :

sasv

Start-Service can control services only if the current user has permission to do
this. 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, Automatic, or
Automatic (Delayed
Start). You cannot start the services that have a start type of
Disabled. If a Start-Service
command fails with the message Cannot start
service \<service-name\> on computer , use
Get-CimInstance to find the start type

of the service and, if you have to, use the Set-Service


cmdlet 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 PowerShell starts a service that
stops itself almost immediately, it displays the
following message: Service \
<display-name\> start failed.

Related Links
Get-Service
New-Service
Restart-Service
Resume-Service
Set-Service
Stop-Service
Suspend-Service
Start-Transaction
Reference
Module: Microsoft.PowerShell.Management

Starts a transaction.

Syntax
PowerShell

Start-Transaction

[-Timeout <Int32>]

[-Independent]

[-RollbackPreference <RollbackSeverity>]

[-WhatIf]

[-Confirm]

[<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, or committed. Alternatively, it
can be completely undone,
or 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, if any command in the transaction generates an error, transactions are rolled
back
automatically. 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 the Windows operating system supports
transactions. You can also use the
Microsoft.PowerShell.Commands.Management.TransactedString class to include
expressions in
transactions on any version of the Windows system 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, the new transaction becomes the active transaction,
and you must commit
or roll back the new transaction before you make any changes to
the original transaction.

Start-Transaction cmdlet is one of a set of cmdlets that support the transactions

feature in
Windows PowerShell. For more information, see about_Transactions.

Examples

Example 1: Start and roll back a transaction


PowerShell

Set-Location hkcu:\software

Start-Transaction

New-Item "ContosoCompany" -UseTransaction

New-ItemProperty "ContosoCompany" -Name "MyKey" -Value 123 -UseTransaction

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: Start and complete a transaction


PowerShell

Set-Location hkcu:\software

Start-Transaction

New-Item "ContosoCompany" -UseTransaction

New-ItemProperty "ContosoCompany" -Name "MyKey" -Value 123 -UseTransaction

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: Use different rollback preferences


PowerShell

Set-Location HKCU:\software

Start-Transaction

New-Item -Path "NoPath" -Name "ContosoCompany" -UseTransaction

New-Item -Path . -Name "ContosoCompany" -UseTransaction

Start-Transaction -RollbackPreference never

New-Item -Path "NoPath" -Name "ContosoCompany" -UseTransaction

New-Item -Path . -Name "ContosoCompany" -UseTransaction

# Start-Transaction (-rollbackpreference error)

Start-Transaction

New-Item -Path "NoPath" -Name "ContosoCompany" -UseTransaction

New-Item : The registry key at the specified path does not exist.

At line:1 char:9

+ new-item <<<< -Path NoPath -Name ContosoCompany -UseTransaction

New-Item -Path . -Name "Contoso" -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 ContosoCompany -UseTransaction

# Start-Transaction (-rollbackpreference never)

Start-Transaction -RollbackPreference never

New-Item -Path "NoPath" -Name "ContosoCompany" -UseTransaction

New-Item : The registry key at the specified path does not exist.

At line:1 char:9

+ New-Item <<<< -Path NoPath -Name "ContosoCompany" -UseTransaction

New-Item -Path . -Name "ContosoCompany" -UseTransaction

Hive: HKEY_CURRENT_USER\Software

SKC VC Name Property

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

0 0 ContosoCompany {}

Complete-Transaction

# Succeeds

This example demonstrates the effect of changing the RollbackPreference parameter


value.

In the first set of commands, Start-Transaction does not use RollbackPreference. As a


result,
the default value (Error) is used. When an error occurs in a transaction command,
that is, the
specified path does not exist, the transaction is automatically rolled back.

In the second set of commands, Start-Transaction uses RollbackPreference 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
RollbackPreference is typically preferred.

Example 4: Use this cmdlet while a transaction is in


progress
PowerShell

Set-Location HKCU:\software

Start-Transaction

New-Item "ContosoCompany" -UseTransaction

Start-Transaction

Get-Transaction

New-Item "ContosoCompany2" -UseTransaction

Complete-Transaction

Complete-Transaction

Get-Transaction

RollbackPreference SubscriberCount Status

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

Error 2 Active

This example shows the effect of using Start-Transaction while a transaction is in


progress.
The effect is much like joining the transaction in progress.

Although this is a simplified command, this scenario frequently 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 whole 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, all the transaction
would be rolled back for both
subscribers.

Example 5: Start an independent transaction while one is


in progress
PowerShell
Set-Location HKCU:\software

Start-Transaction

New-Item "ContosoCompany" -UseTransaction

Start-Transaction -Independent

Get-Transaction

Undo-Transaction

New-ItemProperty -Path "ContosoCompany" -Name "MyKey" -Value 123 -


UseTransaction

Complete-Transaction

Get-ChildItem contoso*

Get-Transaction

RollbackPreference SubscriberCount Status

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

Error 1 Active

Undo-Transaction

New-ItemProperty -Path "ContosoCompany" -Name "MyKey" -Value 123 -


UseTransaction

MyKey

-----

123

Complete-Transaction

Get-ChildItem contoso*

Hive: HKEY_CURRENT_USER\Software

SKC VC Name Property

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

0 1 MyCompany {MyKey}

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, which is the newest one.
The subscriber count is equal to 1, that
shows 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, finishes
without error, and the original transaction can be completed by using the Complete-
Transaction command.
As a result, the registry is changed.

Example 6: Run commands that are not part of a


transaction
PowerShell

Set-Location hkcu:\software

Start-Transaction

New-Item "ContosoCompany1" -UseTransaction

New-Item "ContosoCompany2"

New-Item "ContosoCompany3" -UseTransaction

Get-ChildItem contoso*

Hive: HKEY_CURRENT_USER\Software

SKC VC Name Property

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

0 0 ContosoCompany2 {}

Complete-Transaction

Get-ChildItem contoso*

Hive: HKEY_CURRENT_USER\Software

SKC VC Name Property

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

0 0 ContosoCompany1 {}

0 0 ContosoCompany2 {}

0 0 ContosoCompany3 {}

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 Get-ChildItem 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


Get-ChildItem
command shows that all of the new items are added to the registry.
Example 7: Roll back a transaction that does not finish in
a specified time
PowerShell

Start-Transaction -Timeout 2

# Wait two minutes...

Get-Transaction

New-Item HKCU:\Software\ContosoCompany -UseTransaction

Start-Transaction -Timeout 2

# Wait two minutes...

Get-Transaction

RollbackPreference SubscriberCount Status

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

Error 1 RolledBack

New-Item HKCU:\Software\ContosoCompany -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

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 finished when the
time-out expires, it is
rolled back automatically.

When the time-out 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.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named
Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Independent

Indicates that this cmdlet 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 whole 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 specify the Independent parameter, this cmdlet creates a new transaction 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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RollbackPreference

Specifies the conditions under which a transaction is automatically rolled back. The
acceptable
values for this parameter are:

Error
The transaction is rolled back automatically if a terminating or non-

terminating error occurs.


TerminatingError
The transaction is rolled back automatically if a terminating

error occurs.
Never
The transaction is never rolled back automatically.
The default value is Error .

Type: RollbackSeverity

Accepted values: Error, TerminatingError, Never

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Timeout

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.

Type: Int32

Aliases: TimeoutMins

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


Inputs
None

You cannot pipe input to this cmdlet.

Outputs
None

This cmdlet does not generate any output.

Related Links
Complete-Transaction
Get-Transaction
Undo-Transaction
Use-Transaction
Stop-Computer
Reference
Module: Microsoft.PowerShell.Management

Stops (shuts down) local and remote computers.

Syntax
PowerShell

Stop-Computer

[-AsJob]

[-DcomAuthentication <AuthenticationLevel>]

[-WsmanAuthentication <String>]

[-Protocol <String>]

[[-ComputerName] <String[]>]

[[-Credential] <PSCredential>]

[-Impersonation <ImpersonationLevel>]

[-ThrottleLimit <Int32>]

[-Force]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Stop-Computer cmdlet shuts down the local computer and remote computers.

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 doesn't require PowerShell remoting unless you use the AsJob parameter.

Examples

Example 1: Shut down the local computer


This example shuts down the local computer.
PowerShell

Stop-Computer -ComputerName localhost

Example 2: Shut down two remote computers and the


local computer
This example stops two remote computers and the local computer.

PowerShell

Stop-Computer -ComputerName "Server01", "Server02", "localhost"

Stop-Computer uses the ComputerName parameter to specify two remote computers

and the local


computer. Each computer is shut down.

Example 3: Shut down remote computers as a


background job
In this example, Stop-Computer runs as a background job on two remote computers.

PowerShell

$j = Stop-Computer -ComputerName "Server01", "Server02" -AsJob

$results = $j | Receive-Job

$results

Stop-Computer uses the ComputerName parameter to specify two remote computers.

The AsJob
parameter runs the command as a background job. The job objects are
stored in the $j variable.

The job objects in the $j variable are sent down the pipeline to Receive-Job , which gets
the job
results. The objects are stored in the $results variable. The $results variable
displays the job
information in the PowerShell console.

Because AsJob creates the job on the local computer and automatically returns the
results to the
local computer, you can run Receive-Job as a local command.

Example 4: Shut down a remote computer


This example shuts down a remote computer using specified authentication.
PowerShell

Stop-Computer -ComputerName "Server01" -Impersonation Anonymous -


DcomAuthentication PacketIntegrity

Stop-Computer uses the ComputerName parameter to specify the remote computer. The

Impersonation parameter specifies a customized impersonation and the


DcomAuthentication
parameter specifies authentication-level settings.

Example 5: Shut down computers in a domain


In this example, the commands force an immediate shut down of all computers in a
specified domain.

PowerShell

$s = Get-Content -Path ./Domain01.txt

$c = Get-Credential -Credential Domain01\Admin01

Stop-Computer -ComputerName $s -Force -ThrottleLimit 10 -Credential $c

Get-Content uses the Path parameter to get a file in the current directory with the list of
domain computers. The objects are stored in the $s variable.

Get-Credential uses the Credential parameter to specify the credentials of a domain

administrator. The credentials are stored in the $c variable.

Stop-Computer shuts down the computers specified with the ComputerName

parameter's list of
computers in the $s variable. The Force parameter forces an
immediate shutdown. The
ThrottleLimit parameter limits the command to 10
concurrent connections. The Credential
parameter submits the credentials saved in the
$c variable.

Parameters
-AsJob

Indicates that this cmdlet runs as a background job.

To use this parameter, the local and remote computers must be configured for
remoting and, on
Windows Vista and later versions of the Windows operating
system, you must open PowerShell by using
the Run as administrator option. For
more information, see
about_Remote_Requirements.
When you specify 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 finishes. 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 PowerShell background jobs, see


about_Jobs and
about_Remote_Jobs.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-ComputerName

Specifies the computers to stop. 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
computer name or localhost.

This parameter doesn't rely on PowerShell remoting. You can use the
ComputerName parameter even
if your computer isn't configured to run remote
commands.

Type: String[]

Aliases: CN, __SERVER, Server, IPAddress

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.


Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Credential

Specifies a user account that has permission to do this action. The default is the
current user.

Type a user name, such as User01 or Domain01\User01, or enter a PSCredential


object
generated by the Get-Credential cmdlet. If you type a user name, you're
prompted to enter the
password.

Credentials are stored in a PSCredential


object and the password is stored as a
SecureString.

7 Note

For more information about SecureString data protection, see


How secure is
SecureString?.

Type: PSCredential

Position: 1

Default value: Current user

Accept pipeline input: False

Accept wildcard characters: False

-DcomAuthentication

Specifies the authentication level that this cmdlet uses with WMI. Stop-Computer uses
WMI. The
default value is Packet.

The acceptable values for this parameter are:


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.
Unchanged: Same as the previous command.

For more information about the values of this parameter, see


AuthenticationLevel.

Type: AuthenticationLevel

Aliases: Authentication

Accepted values: Default, None, Connect, Call, Packet, PacketIntegrity,


PacketPrivacy, Unchanged

Position: Named

Default value: Packet

Accept pipeline input: False

Accept wildcard characters: False

-Force

Forces an immediate shut down of the computer.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Impersonation

Specifies the impersonation level to use when this cmdlet calls WMI. The default
value is
Impersonate.

Stop-Computer uses WMI. The acceptable values for this parameter 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.

Type: ImpersonationLevel

Accepted values: Default, Anonymous, Identify, Impersonate, Delegate

Position: Named

Default value: Impersonate

Accept pipeline input: False

Accept wildcard characters: False

-Protocol

Specifies which protocol to use to restart the computers. The acceptable values for
this parameter
are: WSMan and DCOM. The default value is DCOM.

This parameter was introduced in PowerShell 3.0.

Type: String

Accepted values: DCOM, WSMan

Position: Named

Default value: DCOM

Accept pipeline input: False

Accept wildcard characters: False

-ThrottleLimit

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.

Type: Int32

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet isn't run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-WsmanAuthentication

Specifies the mechanism that is used to authenticate the user credentials when this
cmdlet uses the
WSMan protocol. The default value is Default.

The acceptable values for this parameter are:

Basic
CredSSP
Default
Digest
Kerberos
Negotiate.

For more information about the values of this parameter, see


AuthenticationMechanism.

U Caution

Credential Security Service Provider (CredSSP) authentication, in which the user


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.

This parameter was introduced in PowerShell 3.0.

Type: String

Accepted values: Default, Basic, Negotiate, CredSSP, Digest, Kerberos

Position: Named

Default value: Default

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

System.Management.Automation.RemotingJob

When you use the AsJob parameter, this cmdlet returns a RemotingJob object.

Notes
This cmdlet uses the
Win32Shutdown
method of the Win32_OperatingSystem WMI
class. This method requires the SeShutdownPrivilege privilege be enabled for the user
account
used to shutdown the machine.

Related Links
Add-Computer
Checkpoint-Computer
Remove-Computer
Rename-Computer
Restart-Computer
Restore-Computer
Test-Connection
Stop-Process
Reference
Module: Microsoft.PowerShell.Management

Stops one or more running processes.

Syntax
PowerShell

Stop-Process

[-Id] <Int32[]>

[-PassThru]

[-Force]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Stop-Process

-Name <String[]>

[-PassThru]

[-Force]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Stop-Process

[-InputObject] <Process[]>

[-PassThru]

[-Force]

[-WhatIf]

[-Confirm]

[<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 the Windows operating system, to stop a
process that is not
owned by the current user, you must start PowerShell by using the
Run as administrator option. Also,
you are not prompted for confirmation unless you
specify the Confirm parameter.

Examples

Example 1: Stop all instances of a process


PowerShell

PS C:\> 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: Stop a specific instance of a process


PowerShell

PS C:\> 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

This command stops a particular instance of the Notepad process. It uses the process ID,
3952, to
identify the process. The Confirm parameter directs PowerShell to prompt you
before it stops the
process. Because the prompt includes the process namein addition to
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: Stop a process and detect that it has stopped


PowerShell

calc

$p = Get-Process -Name "calc"

Stop-Process -InputObject $p

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 starts an instance of the calculator.

The second command uses Get-Process gets an object that represents the Calc
process, and then
stores it in the $p variable.

The third command stops 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 Get-Process 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: Stop a process not owned by the current user


PowerShell

PS> Get-Process -Name "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 -Name "lsass" | Stop-Process <<<<

[ADMIN]: PS> Get-Process -Name "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]: PS> Get-Process -Name "lsass" | Stop-Process -Force

[ADMIN]: PS>
These commands show the effect of using Force to stop a process that is not owned by
the user.

The first command uses Get-Process to get the Lsass process. A pipeline operator sends
the process
to Stop-Process 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 group on
the computer.

When PowerShell is opened by using the Run as administrator option, and the
command is repeated,
PowerShell prompts you for confirmation.

The second command specifies Force to suppress the prompt. As a result, the process is
stopped
without confirmation.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-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-CimInstance cmdlet to get a


Win32_Process object
that represents the process, and then use the GetOwner
method of the object.

Type: SwitchParameter

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Id

Specifies the process IDs of the processes to stop. To specify multiple IDs, use
commas to separate
the IDs. To find the PID of a process, type Get-Process .

Type: Int32[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-InputObject

Specifies the process objects to stop. Enter a variable that contains the objects, or
type a command
or expression that gets the objects.

Type: Process[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies the process names of the processes to stop. You can type multiple process
names, separated
by commas, or use wildcard characters.

Type: String[]

Aliases: ProcessName

Position: Named

Default value: None


Accept pipeline input: True

Accept wildcard characters: True

-PassThru

Returns an object that represents the process. By default, this cmdlet does not
generate any output.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
Process

You can pipe a process object to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.


Process

When you use the PassThru parameter, this cmdlet returns a Process object
representing the
stopped process.

Notes
Windows PowerShell includes the following aliases for Stop-Process :

kill

spps

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-CimInstance and
the WMI SDK.

When stopping processes, realize that stopping a process can stop process and
services that depend
on the process. In an extreme case, stopping a process can
stop Windows.

Related Links
Debug-Process
Get-Process
Start-Process
Stop-Process
Wait-Process
Stop-Service
Reference
Module: Microsoft.PowerShell.Management

Stops one or more running services.

Syntax
PowerShell

Stop-Service

[-Force]

[-NoWait]

[-InputObject] <ServiceController[]>

[-PassThru]

[-Include <String[]>]

[-Exclude <String[]>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Stop-Service

[-Force]

[-NoWait]

[-Name] <String[]>

[-PassThru]

[-Include <String[]>]

[-Exclude <String[]>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Stop-Service

[-Force]

[-NoWait]

[-PassThru]

-DisplayName <String[]>

[-Include <String[]>]

[-Exclude <String[]>]

[-WhatIf]

[-Confirm]

[<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 that
represents the service that you want
to stop.

Examples

Example 1: Stop a service on the local computer


PowerShell

PS C:\> Stop-Service -Name "sysmonlog"

This command stops the Performance Logs and Alerts (SysmonLog) service on the local
computer.

Example 2: Stop a service by using the display name


PowerShell

PS C:\> Get-Service -DisplayName "telnet" | Stop-Service

This command stops the Telnet service on the local computer. The command uses Get-
Service to get
an object that represents the Telnet service. The pipeline operator ( | )
pipes the object to
Stop-Service , which stops the service.

Example 3: Stop a service that has dependent services


PowerShell

PS C:\> Get-Service -Name "iisadmin" | Format-List -Property Name,


DependentServices

PS C:\> Stop-Service -Name "iisadmin" -Force -Confirm

This example 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
Stop-Service 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 Get-Service to get
an object
that represents 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 it stops each service.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-DisplayName

Specifies the display names of the services to stop.


Wildcard characters are
permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Exclude
Specifies services that this cmdlet omits. The value of this parameter qualifies the
Name
parameter. Enter a name element or pattern, such as s*. Wildcard characters
are permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Force

Forces the cmdlet to stop a service even if that service has dependent services.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Include

Specifies services that this cmdlet stops. The value of this parameter qualifies the
Name
parameter. Enter a name element or pattern, such as s*. Wildcard characters
are permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-InputObject

Specifies ServiceController objects that represent the services to stop. Enter a


variable that
contains the objects, or type a command or expression that gets the
objects.

Type: ServiceController[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies the service names of the services to stop. Wildcard characters are
permitted.

Type: String[]

Aliases: ServiceName

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-NoWait

Indicates that this cmdlet uses the no wait option.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-PassThru

Returns an object that represents the service. By default, this cmdlet does not
generate any output.

Type: SwitchParameter
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
ServiceController

You can pipe a service object to this cmdlet.

String

You can pipe a string that contains the name of a service to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

ServiceController

When you use the PassThru parameter, this cmdlet returns a ServiceController object
representing the service.
Notes
Windows PowerShell includes the following aliases for Stop-Service :

spsv

Stop-Service can control services only when the current user has permission to do this.
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.

Related Links
Get-Service
New-Service
Restart-Service
Resume-Service
Set-Service
Start-Service
Suspend-Service
Suspend-Service
Reference
Module: Microsoft.PowerShell.Management

Suspends (pauses) one or more running services.

Syntax
PowerShell

Suspend-Service

[-InputObject] <ServiceController[]>

[-PassThru]

[-Include <String[]>]

[-Exclude <String[]>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Suspend-Service

[-Name] <String[]>

[-PassThru]

[-Include <String[]>]

[-Exclude <String[]>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Suspend-Service

[-PassThru]

-DisplayName <String[]>

[-Include <String[]>]

[-Exclude <String[]>]

[-WhatIf]

[-Confirm]

[<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 stopped
until resumed, such as by usingthe Resume-Service cmdlet. 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 suspend.

Examples

Example 1: Suspend a service


PowerShell

PS C:\> Suspend-Service -DisplayName "Telnet"

This command suspends the Telnet service (Tlntsvr) service on the local computer.

Example 2: Display what would happen if you suspend


services
PowerShell

PS C:\> Suspend-Service -Name lanman* -WhatIf

This command tells what would happen if you suspended the services that have a
service name that
starts with lanman. To suspend the services, rerun the command
without the WhatIf parameter.

Example 3: Get and suspend a service


PowerShell

PS C:\> 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
Suspend-Service , which suspends the service.

Example 4: Suspend all services that can be suspended


PowerShell

PS C:\> 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
Get-Service to get objects that represent 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
Suspend-Service . The Confirm parameter
prompts you for confirmation before suspending each of
the services.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-DisplayName

Specifies the display names of the services to be suspended. Wildcard characters are
permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True


-Exclude

Specifies services to omit from the specified services. The value of this parameter
qualifies the
Name parameter. Enter a name element or pattern, such as "s*".
Wildcard characters are
permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Include

Specifies services to suspend. The value of this parameter qualifies the Name
parameter. Enter a
name element or pattern, such as "s*". Wildcard characters are
permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-InputObject

Specifies ServiceController objects that represent the services to suspend. Enter a


variable
that contains the objects, or type a command or expression that gets the
objects.

Type: ServiceController[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False


-Name

Specifies the service names of the services to suspend. Wildcard characters are
permitted.

The parameter name is optional. You can use Name or its alias, ServiceName, or you
can omit
the parameter name.

Type: String[]

Aliases: ServiceName

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-PassThru

Returns an object representing the item with which you are working. By default, this
cmdlet does not
generate any output.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs.


The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


Inputs
ServiceController

You can pipe a service object to this cmdlet.

String

You can pipe a string that contains a service name to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

ServiceController

When you use the PassThru parameter, this cmdlet returns a ServiceController object
representing the service.

Notes
Suspend-Service can control services only when the current user has permission to

do this. If a
command does not work correctly, you might not have the required
permissions.
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 together 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.

Related Links
Get-Service
New-Service
Restart-Service
Resume-Service
Set-Service
Start-Service
Stop-Service
Test-ComputerSecureChannel
Reference
Module: Microsoft.PowerShell.Management

Tests and repairs the secure channel between the local computer and its domain.

Syntax
PowerShell

Test-ComputerSecureChannel

[-Repair]

[-Server <String>]

[-Credential <PSCredential>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Test-ComputerSecureChannel cmdlet verifies that the 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 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.

Examples

Example 1: Test a channel between the local computer


and its domain
PowerShell

Test-ComputerSecureChannel
This command tests the channel between the local computer and the domain to which it
is joined.

Example 2: Test a channel between the local computer


and a domain controller
PowerShell

Test-ComputerSecureChannel -Server "DCName.fabrikam.com"

True

This command specifies a preferred domain controller for the test.

Example 3: Reset the channel between the local computer


and its domain
PowerShell

Test-ComputerSecureChannel -Repair

This command resets the channel between the local computer and its domain.

Example 4: Display detailed information about the test


PowerShell

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

This command uses the Verbose common parameter to request detailed messages
about the operation.
For more information about Verbose, see
about_CommonParameters.

Example 5: Test a connection before you run a script


PowerShell
if (!(Test-ComputerSecureChannel)) {

Write-Host "Connection failed. Reconnect and retry."

else {

&(.\Get-Servers.ps1)

This example shows how to use Test-ComputerSecureChannel to test a connection before


you run a
script that requires the connection.

The if statement checks the value that Test-ComputerSecureChannel returns before it


runs a script.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Credential

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 that the Get-Credential
cmdlet returns. By default, the cmdlet uses the
credentials of the current user.

The Credential parameter is designed for use in commands that use the Repair
parameter to
repair the channel between the computer and the domain.

Type: PSCredential

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Repair

Indicates that this cmdlet removes and then rebuilds the channel established by the
NetLogon
service. Use this parameter to try to restore a connection that has failed
the test.

To use this parameter, the current user must be a member of the Administrators
group on the local
computer.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Server

Specifies the domain controller to run the command. If this parameter is not
specified, this cmdlet
selects a default domain controller for the operation.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi
Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You cannot pipe input to this cmdlet.

Outputs
Boolean

This cmdlet returns $True if the connection is working correctly and $False if it is not.

Notes
To run a Test-ComputerSecureChannel command on Windows Vista and later
versions of the Windows
operating system, open Windows PowerShell by using the
Run as administrator option.
Test-ComputerSecureChannel is implemented by using the I_NetLogonControl2

function, which
controls various aspects of the Netlogon service.

Related Links
Checkpoint-Computer
Reset-ComputerMachinePassword
Restart-Computer
Stop-Computer
Test-Connection
Reference
Module: Microsoft.PowerShell.Management

Sends ICMP echo request packets, or pings, to one or more computers.

Syntax
PowerShell

Test-Connection

[-AsJob]

[-DcomAuthentication <AuthenticationLevel>]

[-WsmanAuthentication <String>]

[-Protocol <String>]

[-BufferSize <Int32>]

[-ComputerName] <String[]>

[-Count <Int32>]

[-Impersonation <ImpersonationLevel>]

[-ThrottleLimit <Int32>]

[-TimeToLive <Int32>]

[-Delay <Int32>]

[<CommonParameters>]

PowerShell

Test-Connection

[-AsJob]

[-DcomAuthentication <AuthenticationLevel>]

[-WsmanAuthentication <String>]

[-Protocol <String>]

[-BufferSize <Int32>]

[-ComputerName] <String[]>

[-Count <Int32>]

[-Credential <PSCredential>]

[-Source] <String[]>

[-Impersonation <ImpersonationLevel>]

[-ThrottleLimit <Int32>]

[-TimeToLive <Int32>]

[-Delay <Int32>]

[<CommonParameters>]

PowerShell

Test-Connection

[-DcomAuthentication <AuthenticationLevel>]

[-WsmanAuthentication <String>]

[-Protocol <String>]

[-BufferSize <Int32>]

[-ComputerName] <String[]>

[-Count <Int32>]

[-Impersonation <ImpersonationLevel>]

[-TimeToLive <Int32>]

[-Delay <Int32>]

[-Quiet]

[<CommonParameters>]

Description
The Test-Connection cmdlet sends Internet Control Message Protocol (ICMP) echo
request packets,
or 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 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 time-out and
number of pings, and to
configure the connection and authentication.

Unlike the familiar ping command, Test-Connection returns a Win32_PingStatus object


that
you can investigate in PowerShell. The Quiet parameter returns a Boolean value in a
System.Boolean object for each tested connection. If multiple connections are tested, an
array
of Boolean values is returned.

Examples

Example 1: Send echo requests to a remote computer


This example sends echo request packets from the local computer to the Server01
computer.

PowerShell

Test-Connection -ComputerName Server01

Source Destination IPV4Address IPV6Address Bytes Time(ms)

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

ADMIN1 Server01 10.59.137.44 32 0

ADMIN1 Server01 10.59.137.44 32 0

ADMIN1 Server01 10.59.137.44 32 0

ADMIN1 Server01 10.59.137.44 32 1


Test-Connection uses the ComputerName parameter to specify the Server01 computer.

Example 2: Send echo requests to several computers


This example sends pings from the local computer to several remote computers.

PowerShell

Test-Connection -ComputerName Server01, Server02, Server12

Example 3: Send echo requests from several computers to


a computer
This example sends pings from different source computers to a single remote computer,
Server01.

PowerShell

Test-Connection -Source Server02, Server12, localhost -ComputerName Server01


-Credential Domain01\Admin01

Test-Connection uses the Credential parameter to specify the credentials of a user who

has
permission to send a ping request from the source computers. Use this command
format to test the
latency of connections from multiple points.

Example 4: Use parameters to customize the test


command
This example uses the parameters of Test-Connection to customize the command. The
local computer
sends a ping test to a remote computer.

PowerShell

Test-Connection -ComputerName Server01 -Count 3 -Delay 2 -TTL 255 -


BufferSize 256 -ThrottleLimit 32

Test-Connection uses the ComputerName parameter to specify Server01. The Count


parameter
specifies three pings are sent to the Server01 computer with a Delay of 2-
second intervals.
You might use these options 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: Run a test as a background job


This example shows how to run a Test-Connection command as a PowerShell
background job.

PowerShell

$job = Test-Connection -ComputerName (Get-Content Servers.txt) -AsJob

if ($job.JobStateInfo.State -ne "Running") {$Results = Receive-Job $job}

The Test-Connection command pings many computers in an enterprise. The value of the
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
and it saves the job in the $job variable.

The if command checks to see that the job isn't still running. If the job isn't running,
Receive-Job gets the results and stores them in the $Results variable.

Example 6: Ping a remote computer with credentials


This command uses the Test-Connection cmdlet to ping a remote computer.

PowerShell

Test-Connection Server55 -Credential Domain55\User01 -Impersonation Identify

The command uses the Credential parameter to specify a user account that has
permission to ping
the remote computer and the Impersonation parameter to change
the impersonation level to
Identify.

Example 7: Create a session only if a connection test


succeeds
This example creates a session on the Server01 computer only if at least one of the
pings sent to
the computer succeeds.

PowerShell
if (Test-Connection -ComputerName Server01 -Quiet) {New-PSSession Server01}

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

Parameters
-AsJob

Indicates that this cmdlet runs as a background job.

To use this parameter, the local and remote computers must be configured for
remoting and, on
Windows Vista and later versions of the Windows operating
system, you must open PowerShell by using
the Run as administrator option. For
more information, see
about_Remote_Requirements.

When you specify 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 finishes. 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 PowerShell background jobs, see


about_Jobs and
about_Remote_Jobs.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-BufferSize
Specifies the size, in bytes, of the buffer sent with this command. The default value is
32.

Type: Int32

Aliases: Size, Bytes, BS

Position: Named

Default value: 32

Accept pipeline input: False

Accept wildcard characters: False

-ComputerName

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 doesn't rely on PowerShell remoting. You can use the
ComputerName parameter even
if your computer isn't configured to run remote
commands.

7 Note

The ComputerName parameter is renamed to TargetName in PowerShell 6.0


and above.

Type: String[]

Aliases: CN, IPAddress, __SERVER, Server, Destination

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Count

Specifies the number of echo requests to send. The default value is 4.


Type: Int32

Position: Named

Default value: 4

Accept pipeline input: False

Accept wildcard characters: False

-Credential

Specifies a user account that has permission to send a ping request from the source
computer. Type a
user name, such as User01 or Domain01\User01, or enter a
PSCredential object, such as one from
the Get-Credential cmdlet.

The Credential parameter is valid only when the Source parameter is used in the
command. The
credentials don't affect the destination computer.

Type: PSCredential

Position: Named

Default value: Current user

Accept pipeline input: False

Accept wildcard characters: False

-DcomAuthentication

Specifies the authentication level that this cmdlet uses with WMI.
Test-Connection
uses WMI.
The acceptable values for this parameter are:

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
Unchanged. Same as the previous command

The default value is Packet that has an enumerated value of 4. For more information
about
the values of this parameter, see
AuthenticationLevel enumeration.
Type: AuthenticationLevel

Aliases: Authentication

Accepted values: Default, None, Connect, Call, Packet, PacketIntegrity,


PacketPrivacy, Unchanged

Position: Named

Default value: Packet (enumerated value of 4)

Accept pipeline input: False

Accept wildcard characters: False

-Delay

Specifies the interval between pings, in seconds.

Type: Int32

Position: Named

Default value: 1 (second)

Accept pipeline input: False

Accept wildcard characters: False

-Impersonation

Specifies the impersonation level to use when this cmdlet calls WMI. Test-
Connection uses WMI.

The acceptable values for this parameter are as follows:

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.

The default value is Impersonate.

Type: ImpersonationLevel

Accepted values: Default, Anonymous, Identify, Impersonate, Delegate

Position: Named
Default value: Impersonate

Accept pipeline input: False

Accept wildcard characters: False

-Protocol

Specifies a protocol. The acceptable values for this parameter are DCOM and
WSMan.

Type: String

Accepted values: DCOM, WSMan

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Quiet

The Quiet parameter returns a Boolean value in a System.Boolean object. Using this
parameter suppresses all errors.

Each connection that's tested returns a Boolean value. If the ComputerName


parameter
specifies multiple computers, an array of Boolean values is returned.

If any ping succeeds, $True is returned.

If all pings fail, $False is returned.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Source
Specifies the names of the computers where the ping originates. Enter a comma-
separated list of
computer names. The default is the local computer.

Type: String[]

Aliases: FCN, SRC

Position: 1

Default value: Local computer

Accept pipeline input: False

Accept wildcard characters: False

-ThrottleLimit

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.

Type: Int32

Position: Named

Default value: 32

Accept pipeline input: False

Accept wildcard characters: False

-TimeToLive

Specifies the maximum times a packet can be forwarded. For every hop in gateways,
routers etc. the
TimeToLive value is decreased by one. At zero the packet is
discarded and an error is returned.
In Windows, The default value is 128. The alias of
the TimeToLive parameter is TTL.

Type: Int32

Aliases: TTL

Position: Named

Default value: 128 in Windows


Accept pipeline input: False

Accept wildcard characters: False

-WsmanAuthentication

Specifies the mechanism that is used to authenticate the user credentials when this
cmdlet uses the WSMan protocol.
The acceptable values for this parameter are:

Basic
CredSSP
Default
Digest
Kerberos
Negotiate.

The default value is Default.

For more information about the values of this parameter, see


AuthenticationMechanism Enumeration.

Caution: Credential Security Service Provider (CredSSP) authentication, in which the


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

This parameter was introduced in Windows PowerShell 3.0.

Type: String

Accepted values: Default, Basic, Negotiate, CredSSP, Digest, Kerberos

Position: Named

Default value: Default

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None
You can't pipe objects to this cmdlet.

Outputs
ManagementObject

By default, this cmdlet returns a Win32_PingStatus object for each ping reply.

System.Management.Automation.RemotingJob

This cmdlet returns a job object, if you specify the AsJob parameter.

Boolean

When you use the Quiet parameter, this returns a Boolean value. If the cmdlet tests
multiple connections, it returns an array of Boolean values.

Notes
This cmdlet uses the Win32_PingStatus class. A Get-WMIObject Win32_PingStatus
command is
equivalent to a Test-Connection command.

The Source parameter set was introduced in PowerShell 3.0.

Related Links
Add-Computer
Restart-Computer
Stop-Computer
Test-Path
Reference
Module: Microsoft.PowerShell.Management

Determines whether all elements of a path exist.

Syntax
PowerShell

Test-Path

[-Path] <string[]>

[-Filter <string>]

[-Include <string[]>]

[-Exclude <string[]>]

[-PathType <TestPathType>]

[-IsValid]

[-Credential <pscredential>]

[-UseTransaction]

[-OlderThan <datetime>]

[-NewerThan <datetime>]

[<CommonParameters>]

PowerShell

Test-Path

-LiteralPath <string[]>

[-Filter <string>]

[-Include <string[]>]

[-Exclude <string[]>]

[-PathType <TestPathType>]

[-IsValid]

[-Credential <pscredential>]

[-UseTransaction]

[-OlderThan <datetime>]

[-NewerThan <datetime>]

[<CommonParameters>]

PowerShell

Test-Path

[-Path] <string[]>

[-Filter <string>]

[-Include <string[]>]

[-Exclude <string[]>]

[-PathType <TestPathType>]

[-IsValid]

[-Credential <pscredential>]

[-UseTransaction]

[<CommonParameters>]

PowerShell

Test-Path

-LiteralPath <string[]>

[-Filter <string>]

[-Include <string[]>]

[-Exclude <string[]>]

[-PathType <TestPathType>]

[-IsValid]

[-Credential <pscredential>]

[-UseTransaction]

[<CommonParameters>]

Description
The Test-Path cmdlet determines whether all elements of the path exist. It returns
$True if all
elements exist and $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 or leaf
element. If the Path is a
whitespace or empty string, then $False is returned. If the Path
is $null , array of $null
or empty array, a non-terminating error is returned.

Examples

Example 1: Test a path


PowerShell

Test-Path -Path "C:\Documents and Settings\DavidC"

True

This command checks whether all elements in the path exist, that is, the C: directory,
the
Documents and Settings directory, and the DavidC directory. If any are missing, the
cmdlet
returns $False . Otherwise, it returns $True .

Example 2: Test the path of a profile


PowerShell

Test-Path -Path $profile

False

Test-Path -Path $profile -IsValid

True

These commands test the path of the 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: Check whether there are any files besides a


specified type
PowerShell

Test-Path -Path "C:\CAD\Commercial Buildings\*" -Exclude *.dwg

False

This command checks 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 the path includes a
space, the
path is enclosed in quotation marks. The asterisk at the end of the path
indicates the contents of
the Commercial Building directory. With long paths, such as
this one, type the first few letters of
the path, and then use the TAB key to complete the
path.

The command specifies 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: Check for a file


PowerShell

Test-Path -Path $profile -PathType leaf

True

This command checks whether the path stored in the $profile variable leads to a file. In
this
case, because the PowerShell profile is a .ps1 file, the cmdlet returns $True .

Example 5: Check paths in the Registry


These commands use Test-Path with the PowerShell registry provider.

The first command tests whether the registry path of the Microsoft.PowerShell registry
key is
correct on the system. If PowerShell is installed correctly, the cmdlet returns
$True .

) Important

Test-Path does not work correctly with all PowerShell providers. For example, you
can use
Test-Path to test the path of a registry key, but if you use it to test the
path of a registry
entry, it always returns $False , even if the registry entry is
present.

PowerShell

Test-Path -Path
"HKLM:\Software\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell"

True

Test-Path -Path
"HKLM:\Software\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell\Executi
onPolicy"

False

Example 6: Test if a file is newer than a specified date


This command uses the NewerThan dynamic parameter to determine whether the
"PowerShell.exe" file
on the computer is newer than "July 13, 2009".

The NewerThan parameter works only in file system drives.


PowerShell

Test-Path $pshome\PowerShell.exe -NewerThan "July 13, 2009"

True

Example 7: Test a path with null as the value


The error returned for null , array of null or empty array is a non-terminating error. It
can be
suppress by using -ErrorAction SilentlyContinue . The following example shows
all cases which
return the NullPathNotPermitted error.

PowerShell

Test-Path $null

Test-Path $null, $null

Test-Path @()

Test-Path : Cannot bind argument to parameter 'Path' because it is null.

At line:1 char:11

+ Test-Path $null

+ ~~~~~

+ CategoryInfo : InvalidData: (:) [Test-Path],


ParameterBindingValidationException

+ FullyQualifiedErrorId :
ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands
.TestPathCommand

Example 8: Test a path with whitespace as the value


When a whitespace string is provided for the the Path parameter, it returns True. When
an
empty string is provided, Test-Path returns an error. The following example shows
whitespace and
empty string.

PowerShell

Test-Path ' '

Test-Path ''

True

Test-Path : Cannot bind argument to parameter 'Path' because it is an empty


string.

At line:1 char:11

+ Test-Path ''

+ ~~

+ CategoryInfo : InvalidData: (:) [Test-Path],


ParameterBindingValidationException

+ FullyQualifiedErrorId :
ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.C
ommands.TestPathCommand

Parameters
-Credential

7 Note

This parameter isn't supported by any providers installed with PowerShell. To


impersonate another
user, or elevate your credentials when running this cmdlet,
use
Invoke-Command.

Type: PSCredential

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Exclude

Specifies items that this cmdlet omits. The value of this parameter qualifies the Path
parameter. Enter a path element or pattern, such as "*.txt". Wildcard characters are
permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Filter

Specifies a filter in the format or language of the provider. The value of this
parameter qualifies
the Path parameter. The syntax of the filter, including the use of
wildcard characters, depends
on the provider. Filters are more efficient than other
parameters, because the provider applies them
when it retrieves the objects instead
of having PowerShell filter the objects after they are
retrieved.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Include

Specifies paths that this cmdlet tests. The value of this parameter qualifies the Path
parameter. Enter a path element or pattern, such as "*.txt". Wildcard characters are
permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-IsValid

Indicates that this cmdlet tests the syntax of the path, regardless of whether the
elements of the
path exist. This cmdlet returns $True if the path syntax is valid and
$False if it is not.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-LiteralPath
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 wildcard characters. If the
path includes
characters that could be interpreted by PowerShell as escape
sequences, you must enclose the path in
single quote so that they won't be
interpreted.

Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-NewerThan

This is a dynamic parameter made available by the FileSystem provider.

Specify a time as a DateTime object.

For more information, see


about_FileSystem_Provider.

Type: Nullable<T>[[DateTime]]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-OlderThan

This is a dynamic parameter made available by the FileSystem provider.

Specify a time as a DateTime object.

For more information, see


about_FileSystem_Provider.

Type: Nullable<T>[[DateTime]]

Position: Named

Default value: None


Accept pipeline input: True

Accept wildcard characters: False

-Path

Specifies a path to be tested. Wildcard characters are permitted. If the path includes
spaces,
enclose it in quotation marks.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-PathType

Specifies the type of the final element in the path. This cmdlet returns $True if the
element is
of the specified type and $False if it is not. The acceptable values for this
parameter 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.

U Caution

Up to PowerShell version 6.1.2, when the IsValid and PathType switches are
specified together, the Test-Path cmdlet ignores the PathType switch and only
validates the syntactic path without validating the path type.

According to issue #8607 , fixing this


behavior may be a breaking change in a
future version, where the IsValid and PathType
switches belong to separate
parameter sets, and thus, cannot be used together avoiding this
confusion.

Type: TestPathType
Aliases: Type

Accepted values: Any, Container, Leaf

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

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a string that contains a path, but not a literal path, to this cmdlet.

Outputs
Boolean

The cmdlet returns a Boolean value.

Notes
The cmdlets that contain the Path noun (the Path cmdlets) work with path names and
return
the names in a concise format that all 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 as you would use Dirname, Normpath,
Realpath, Join, or other path
manipulators.

The Test-Path 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.

Related Links
Convert-Path
Join-Path
Resolve-Path
Split-Path
Undo-Transaction
Reference
Module: Microsoft.PowerShell.Management

Rolls back the active transaction.

Syntax
PowerShell

Undo-Transaction

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Undo-Transaction cmdlet rolls back the active transaction. When you roll back a
transaction,
the changes that were 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 whole
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 by using 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.

Examples

Example 1: Roll back the current transaction


PowerShell

Undo-Transaction
This command rolls back the current, active, transaction.

Example 2: Start and roll back a transaction


PowerShell

Set-Location hkcu:\software

Start-Transaction

New-Item -Path "ContosoCompany" -UseTransaction

Undo-Transaction

This example starts a transaction and then rolls it back. As a result, no changes are made
to the
registry.

Example 3: Roll back a transaction for all subscribers


PowerShell

Set-Location hkcu:\software

Start-Transaction

New-Item -Path "ContosoCompany" -UseTransaction

Get-Transaction

RollbackPreference SubscriberCount Status

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

Error 1 Active

Start-Transaction

Get-Transaction

RollbackPreference SubscriberCount Status

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

Error 2 Active

Undo-Transaction

Get-Transaction

RollbackPreference SubscriberCount Status

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

Error 0 RolledBack

This example demonstrates that when any subscriber rolls back a transaction, the whole
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 that is used by
the main transaction
includes its own complete transaction. This example is performed
interactively so that you can
examine it in stages. When you run 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 Undo-Transaction 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.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf
Shows what would happen if the cmdlet runs.
The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

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.

Related Links
Complete-Transaction
Get-Transaction
Start-Transaction
Use-Transaction
Use-Transaction
Reference
Module: Microsoft.PowerShell.Management

Adds the script block to the active transaction.

Syntax
PowerShell

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 by 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 you
use this
cmdlet.

Use-Transaction is one of a set of cmdlets that support the transactions feature in

Windows
PowerShell. For more information, see about_Transactions.

Examples

Example 1: Script by using a transaction-enabled object


PowerShell

Start-Transaction

$transactedString = New-Object
Microsoft.PowerShell.Commands.Management.TransactedString

$transactedString.Append("Hello")

Use-Transaction -TransactedScript { $transactedString.Append(", World") } -


UseTransaction

$transactedString.ToString()

Hello

Use-Transaction -TransactedScript { $transactedString.ToString() } -


UseTransaction

Hello, World

Complete-Transaction

$transactedString.ToString()

Hello, World

This example shows how to use Use-Transaction 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
command 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 Use-Transaction to add text to the string in 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 transaction 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 Use-Transaction to run the same command in the transaction.
Because the
command is part of the transaction, it displays the current value of the
string in 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: Roll back a transaction


PowerShell

Start-Transaction

$transactedString = New-Object
Microsoft.PowerShell.Commands.Management.TransactedString

$transactedString.Append("Hello")

Use-Transaction -TransactedScript { $transactedString.Append(", World") } -


UseTransaction

Undo-Transaction

$transactedString.ToString()

Hello

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 Start-Transaction to start a transaction.

The second command uses New-Object 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 Use-Transaction to run another command that uses the
Append method in
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 in 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 that were made

outside the transaction were


applied to the object.
Parameters
-TransactedScript

Specifies the script block that is run in the transaction. Enter any valid script block
enclosed in
braces ( {} ). This parameter is required.

Type: ScriptBlock

Position: 0

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.

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You cannot pipe input to this cmdlet.

Outputs
PSObject

This cmdlet returns the result of the transaction.


Notes
The UseTransaction 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.

Related Links
Complete-Transaction
Get-Transaction
Start-Transaction
Undo-Transaction
Wait-Process
Reference
Module: Microsoft.PowerShell.Management

Waits for the processes to be stopped before accepting more input.

Syntax
PowerShell

Wait-Process

[-Name] <String[]>

[[-Timeout] <Int32>]

[<CommonParameters>]

PowerShell

Wait-Process

[-Id] <Int32[]>

[[-Timeout] <Int32>]

[<CommonParameters>]

PowerShell

Wait-Process

[[-Timeout] <Int32>]

-InputObject <Process[]>

[<CommonParameters>]

Description
The Wait-Process cmdlet waits for one or more running processes to be stopped before
accepting
input. In the 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.

Examples
Example 1: Stop a process and wait
PowerShell

PS C:\> $nid = (Get-Process notepad).id

PS C:\> Stop-Process -Id $nid

PS C:\> Wait-Process -Id $nid

This example stops the Notepad process and then waits for the process to be stopped
before it
continues with the next command.

The first command uses the Get-Process cmdlet to get the ID of the Notepad process. It
stores the
ID in the $nid variable.

The second command uses the Stop-Process cmdlet to stop the process with the ID
stored in $nid .

The third command uses Wait-Process to wait until the Notepad process is stopped. It
uses the
Id parameter of Wait-Process to identify the process.

Example 2: Specifying a process


PowerShell

PS C:\> $p = Get-Process notepad

PS C:\> Wait-Process -Id $p.id

PS C:\> Wait-Process -Name "notepad"

PS C:\> Wait-Process -InputObject $p

These commands show three different methods of specifying a process to Wait-Process .


The first
command gets the Notepad process and stores 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: Wait for processes for a specified time


PowerShell

PS C:\> 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.

Parameters
-Id

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 .

Type: Int32[]

Aliases: PID, ProcessId

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-InputObject

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 the Get-Process
cmdlet.

Type: Process[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies the process names of the processes. To specify multiple names, use
commas to separate the
names. Wildcard characters are not supported.

Type: String[]
Aliases: ProcessName

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Timeout

Specifies the maximum time, in seconds, that this cmdlet 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. By
default, there is no time-out.

Type: Int32

Aliases: TimeoutSec

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
Process

You can pipe a process object to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
This cmdlet uses the WaitForExit method of the System.Diagnostics.Process class.
Unlike Start-Process -Wait , Wait-Process only waits for the processes identified.
Start-Process -Wait waits for the process tree (the process and all its
descendants) to exit
before returning control.

Related Links
Debug-Process
Get-Process
Start-Process
Stop-Process
Wait-Process
Write-EventLog
Reference
Module: Microsoft.PowerShell.Management

Writes an event to an event log.

Syntax
PowerShell

Write-EventLog

[-LogName] <String>

[-Source] <String>

[[-EntryType] <EventLogEntryType>]

[-Category <Int16>]

[-EventId] <Int32>

[-Message] <String>

[-RawData <Byte[]>]

[-ComputerName <String>]

[<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 the Windows operating system, use the Get-
WinEvent cmdlet.

Examples

Example 1: Write an event to the Application event log


PowerShell

PS C:\> 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: Write an event to the Application event log of


a remote computer
PowerShell

PS C:\> 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.

Parameters
-Category

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.

Type: Int16

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ComputerName

Specifies a remote computer. The default is the local computer.

Type the NetBIOS name, an 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 the Get-EventLog cmdlet even if your computer is not
configured to run remote
commands.
Type: String

Aliases: CN

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-EntryType

Specifies the entry type of the event. The acceptable values for this parameter are:
Error, Warning,
Information, SuccessAudit, and FailureAudit. The default value is
Information.

For a description of the values, see


EventLogEntryType Enumeration.

Type: EventLogEntryType

Aliases: ET

Accepted values: Error, Information, FailureAudit, SuccessAudit, Warning

Position: 3

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-EventId

Specifies the event identifier. This parameter is required. The maximum value for the
EventId
parameter is 65535.

Type: Int32

Aliases: ID, EID

Position: 2

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-LogName

Specifies the name of the log to which the event is written. Enter the log name. The
log name is the
value of the Log property, not the LogDisplayName. Wildcard
characters are not permitted.
This parameter is required.

Type: String

Aliases: LN

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Message

Specifies the event message. This parameter is required.

Type: String

Aliases: MSG

Position: 4

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RawData

Specifies the binary data that is associated with the event, in bytes.

Type: Byte[]

Aliases: RD

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-Source

Specifies the event source, which is typically the name of the application that is
writing the event
to the log.

Type: String

Aliases: SRC

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You cannot pipe input to this cmdlet.

Outputs
EventLogEntry

This cmdlet returns objects that represents the events in the logs.

Notes
For some Windows event logs, writing events requires administrator rights. You must
start
PowerShell using the Run as Administrator option.

Related Links
Clear-EventLog
Get-EventLog
Limit-EventLog
New-EventLog
Remove-EventLog
Show-EventLog
Write-EventLog
Microsoft.PowerShell.ODataUtils
Reference

This section contains the help topics for the Microsoft.PowerShell.ODataUtils module.
The Microsoft.PowerShell.ODataUtils module is installed with Windows PowerShell 5.1.

Microsoft.PowerShell.ODataUtils
Export-ODataEndpointProxy Generates a module that contains cmdlets to manage an OData
endpoint.
Export-ODataEndpointProxy
Reference
Module: Microsoft.PowerShell.ODataUtils

Generates a module that contains cmdlets to manage an OData endpoint.

Syntax
PowerShell

Export-ODataEndpointProxy

[-Uri] <String>

[-OutputModule] <String>

[[-MetadataUri] <String>]

[[-Credential] <PSCredential>]

[[-CreateRequestMethod] <String>]

[[-UpdateRequestMethod] <String>]

[[-CmdletAdapter] <String>]
[[-ResourceNameMapping] <Hashtable>]

[-Force]

[[-CustomData] <Hashtable>]
[-AllowClobber]

[-AllowUnsecureConnection]

[[-Headers] <Hashtable>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Export-ODataEndpointProxy cmdlet uses the metadata of an OData endpoint to
generate a module
that contains cmdlets you can use to manage that OData endpoint.
The module is based on CDXML. After
this cmdlet generates the module, it saves that
module to the path and file name specified by the
OutputModule parameter.

Export-ODataEndpointProxy generates cmdlets for create, read, update, and delete

(CRUD)
operations, non-CRUD actions, and association manipulation.

Export-ODataEndpointProxy generates one CDXML file per endpoint resource. You can

edit these CDXML


files after the module is generated. For example, if you want to
change the noun or verb names of
the cmdlets to align with Windows PowerShell
cmdlet naming guidelines, you can modify the file.
Every cmdlet in a generated module must include a ConnectionURI parameter in order
to connect to
the endpoint that the module manages.

Examples

Example 1: Generate a module to manage a retail web


service endpoint
PowerShell

PS C:\> Export-ODataEndpointProxy -Uri


'http://services.odata.org/v3/(S(snyobsk1hhutkb2yulwldgf1))/odata/odata.svc'
-MetadataUri
'http://services.odata.org/v3/(S(snyobsk1hhutkb2yulwldgf1))/odata/odata.svc/
$metadata' -AllowUnsecureConnection -OutputModule
'C:\Users\user\GeneratedScript.psm1' -ResourceNameMapping @{Products =
'Merchandise'}

This command generates a module to manage a retail service endpoint. The command
specifies the URI
of the endpoint and the URI of the endpoint metadata. The command
also provides an output path and
script module name as the value of the
OutputModule parameter. For the value of the
ResourceNameMapping parameter, the
command provides a hashtable that maps the resource
collection name to the desired
noun for the cmdlet set. In this example, Products is the resource
collection name and
Merchandise is the noun. To allow connections to non-SSL sites, HTTP, as
opposed to
HTTPS, add the AllowUnsecureConnection parameter.

Parameters
-AllowClobber

Indicates that this cmdlet replaces an existing module.

Type: SwitchParameter

Position: 10

Default value: None

Accept pipeline input: True

Accept wildcard characters: False


-AllowUnsecureConnection

Indicates that this module can connect to URIs that are not SSL-secured. The module
can manage HTTP
sites in addition to HTTPS sites.

Type: SwitchParameter

Position: 11

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-CmdletAdapter

Specifies the cmdlet adapter. The acceptable values for this parameter are:
ODataAdapter and
NetworkControllerAdapter.

Type: String

Accepted values: ODataAdapter, NetworkControllerAdapter, ODataV4Adapter

Position: 6

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-CreateRequestMethod
Specifies the request method. The acceptable values for this parameter are: PUT,
POST, and PATCH.

Type: String

Accepted values: Put, Post, Patch

Position: 4

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Credential

Specifies a user account that has access to the OData endpoint. The default value is
the current
user. If a remote computer runs Windows Vista or a later release of the
Windows operating system,
the cmdlet prompts you for credentials.

Type: PSCredential

Position: 3

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-CustomData

Specifies a hash table of custom data.

Type: Hashtable

Position: 9

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Force
Indicates that this cmdlet overwrites an existing generated module of the same
name in an existing
Modules folder.

Type: SwitchParameter

Position: 8

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Headers

Specifies the headers of the web request. Enter a hash table or dictionary.

Type: Hashtable

Position: 12

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-MetadataUri

Specifies the URI of the metadata of the endpoint.

Type: String

Position: 2

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-OutputModule

Specifies the path and module name to which this cmdlet saves the generated
module of proxy
commands.

This cmdlet copies a binary module, module manifest, and formatting file, if
applicable, to the
specified folder. If you specify only the name of the module,
Export-ODataEndpointProxy saves the
module in the

$HOME\Documents\WindowsPowerShell\Modules folder. If you specify a path, the cmdlet


creates the module folder in that path.

Type: String

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-ResourceNameMapping

Specifies a hashtable that contains mappings that let you customize the generated
cmdlets. In this
hashtable, the resource collection name is the key. The desired
cmdlet noun is the value.

For example, in the hash table @{Products = 'Merchandise'} , Products is the


resource
collection name that serves as the key. Merchandise is the resulting cmdlet
noun. The generated
cmdlet names might not align to Windows PowerShell cmdlet
naming guidelines. You can modify the
resource CDXML file to change the cmdlet
names after this cmdlet creates the module. For more
information, see
Strongly
Encouraged Development Guidelines.

Type: Hashtable

Position: 7

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-UpdateRequestMethod

Specifies the update request method. The acceptable values for this parameter are:
PUT, POST, and
PATCH.

Type: String

Accepted values: Put, Post, Patch

Position: 5
Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Uri

Specifies the URI of the endpoint.

Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs.


The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Related Links
OData Library
What is the OData Protocol?
Invoke-RestMethod
Microsoft.PowerShell.Operation.
Validation
Reference

This section has links to the Operation Validation Framework cmdlets.

Microsoft.PowerShell.Operation.Validation
Get-OperationValidation Gets Operation Validation Framework tests.

Invoke-OperationValidation Invokes Operation Validation Framework tests.


Get-OperationValidation
Reference
Module: Microsoft.PowerShell.Operation.Validation

Gets Operation Validation Framework tests.

Syntax
PowerShell

Get-OperationValidation

[[-ModuleName] <String[]>]

[-TestType <String[]>]

[<CommonParameters>]

Description
The Get-OperationValidation cmdlet gets Operation Validation Framework tests for
installed
modules.

Modules that include a Diagnostics folder are inspected for Pester tests in the Simple or
Comprehensive subfolder, or both.

Examples

Example 1: Get Operation Validation tests


PowerShell

Get-OperationValidation -ModuleName "C:\temp\modules\AddNumbers"

Type: Simple

File: addnum.tests.ps1

FilePath: C:\temp\modules\AddNumbers\Diagnostics\Simple\addnum.tests.ps1

Name:

Add-Em

Subtract em

Add-Numbers

Type: Comprehensive

File: Comp.Adding.Tests.ps1

FilePath:
C:\temp\modules\AddNumbers\Diagnostics\Comprehensive\Comp.Adding.Tests.ps1

Name:

Comprehensive Adding Tests

Comprehensive Subtracting Tests

Comprehensive Examples

This command gets validation tests from the module named AddNumbers in the
C:\temp\modules folder.

Parameters
-ModuleName

Specifies an array of names of modules.

Type: String[]

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-TestType

Specifies an array of test types. Valid values are:

Simple

Comprehensive

The default is Simple,Comprehensive .

Type: String[]

Accepted values: Simple, Comprehensive

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


Inputs
None

You can't pipe objects to this cmdlet.

Outputs
PSCustomObject

This cmdlet returns a PSCustomObject describing the validation.

Related Links
Invoke-OperationValidation
Invoke-OperationValidation
Reference
Module: Microsoft.PowerShell.Operation.Validation

Invokes Operation Validation Framework tests.

Syntax
PowerShell

Invoke-OperationValidation

[-TestInfo <PSObject[]>]

[-IncludePesterOutput]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Invoke-OperationValidation

[-testFilePath <String[]>]

[-IncludePesterOutput]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Invoke-OperationValidation

[-ModuleName <String[]>]

[-TestType <String[]>]

[-IncludePesterOutput]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Invoke-OperationValidation cmdlet invokes Operation Validation Framework tests
for a specified module.

Examples
Example 1: Invoke an Operation Validation test
PowerShell

Get-OperationValidation -ModuleName "OperationValidation" | Invoke-


OperationValidation -IncludePesterOutput

Describing Simple Test Suite

[+] first Operational test 20ms

[+] second Operational test 19ms


[+] third Operational test 9ms

Tests completed in 48ms

Passed: 3 Failed: 0 Skipped: 0 Pending: 0

Describing Scenario targeted tests

Context The RemoteAccess service

[+] The service is running 37ms

Context The Firewall Rules

[+] A rule for TCP port 3389 is enabled 1.19s

[+] A rule for UDP port 3389 is enabled 11ms

Tests completed in 1.24s

Passed: 3 Failed: 0 Skipped: 0 Pending: 0

Module: OperationValidation

Result Name

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

Passed Simple Test Suite::first Operational test

Passed Simple Test Suite::second Operational test

Passed Simple Test Suite::third Operational test

Passed Scenario targeted tests:The RemoteAccess service:The service is


running

Passed Scenario targeted tests:The Firewall Rules:A rule for TCP port 3389
is enabled

Passed Scenario targeted tests:The Firewall Rules:A rule for UDP port 3389
is enabled

This command gets the module named OperationValidation, and uses the pipeline
operator ( | ) to
pass it to the Invoke-OperationValidation cmdlet, which runs the test.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf
Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-IncludePesterOutput

Includes Pester test output. The default is $False .

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ModuleName

Specifies an array of names of modules.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-testFilePath

Specifies the path of an Operation Validation Framework test file.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False


-TestInfo

Specifies a custom object that specifies the path to the file and the name of the test
to run.

Type: PSObject[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-TestType

Specifies an array of test types. Valid values are:

Simple

Comprehensive

The default is Simple,Comprehensive .

Type: String[]

Accepted values: Simple, Comprehensive

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False


Accept wildcard characters: False

Inputs
PSCustomObject

You can pipe the output of Get-OperationValidation to this cmdlet.

Outputs
PSCustomObject

This cmdlet returns a PSCustomObject object describing whether the validation was
successful.

Related Links
Get-OperationValidation
Microsoft.PowerShell.Security
Reference

This section contains the help topics for the cmdlets that are installed with PowerShell
Microsoft.PowerShell.Security module. The Security module contains cmdlets and
providers that manage
the basic security features of Windows.

Microsoft.PowerShell.Security
ConvertFrom-SecureString Converts a secure string to an encrypted standard string.

ConvertTo-SecureString Converts plain text or encrypted strings to secure strings.

Get-Acl Gets the security descriptor for a resource, such as a file or


registry key.

Get-AuthenticodeSignature Gets information about the Authenticode signature for a file.

Get-CmsMessage Gets content that has been encrypted by using the


Cryptographic Message Syntax format.

Get-Credential Gets a credential object based on a user name and password.

Get-ExecutionPolicy Gets the execution policies for the current session.

Get-PfxCertificate Gets information about PFX certificate files on the computer.

New-FileCatalog New-FileCatalog creates a catalog file of file hashes that can be


used to validate the
authenticity of a file.

Protect-CmsMessage Encrypts content by using the Cryptographic Message Syntax


format.

Set-Acl Changes the security descriptor of a specified item, such as a file


or a registry key.

Set-AuthenticodeSignature Adds an Authenticode signature to a PowerShell


script or other
file.

Set-ExecutionPolicy Sets the PowerShell execution policies for Windows computers.

Test-FileCatalog Test-FileCatalog validates whether the hashes contained in a


catalog file (.cat) matches the
hashes of the actual files in order
to validate their authenticity.

This cmdlet is only supported on Windows.

Unprotect-CmsMessage Decrypts content that has been encrypted by using the


Cryptographic Message Syntax format.
about_Certificate_Provider
Article • 09/19/2022 • 10 minutes to read

Provider name
Certificate

Drives
Cert:

Capabilities
ShouldProcess

Short description
Provides access to X.509 certificate stores and certificates in PowerShell.

Detailed description
The PowerShell Certificate provider lets you get, add, change, clear, and
delete
certificates and certificate stores in PowerShell.

The Certificate drive is a hierarchical namespace containing the certificate


stores and
certificates on your computer.

The Certificate provider supports the following cmdlets, which are covered
in this
article.

Get-Location
Set-Location
Get-Item
Get-ChildItem
Invoke-Item
Move-Item
New-Item
Remove-Item
Get-ItemProperty
Set-ItemProperty
Clear-ItemProperty
Get-AuthenticodeSignature
Set-AuthenticodeSignature

Types exposed by this provider


The Certificate drive exposes the following types.

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 System.Security.Cryptography.X509Certificates.X509Certificate2
certificates, each of which represent an X.509 certificate on the computer.
Certificates are identified by their thumbprints.

Navigating the Certificate drive


The Certificate provider exposes the certificate namespace as the Cert:
drive in
PowerShell. 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.

PowerShell

Set-Location Cert:

You can also work with the certificate provider from any other PowerShell drive.
To
reference an alias from another location, use the Cert: drive name in the
path.

PowerShell

PS Cert:\> Set-Location -Path LocalMachine\Root

To return to a file system drive, type the drive name. For example, type:

PowerShell
Set-Location C:

7 Note

PowerShell uses aliases to allow you a familiar way to work with provider
paths.
Commands such as dir and ls are now aliases for
Get-ChildItem, cd is
an alias for
Set-Location. and pwd
is an alias for
Get-Location.

Displaying the Contents of the Cert: drive


This command uses the Get-ChildItem cmdlet to display the certificate stores
in the
CurrentUser certificate store location.

If you are not in the Cert: drive, use an absolute path.

PowerShell

PS Cert:\CurrentUser\> Get-ChildItem

Displaying certificate properties within the Cert: drive


This example gets a certificate with Get-Item and stores it in a variable. The
example
shows the new certificate script properties (DnsNameList,
EnhancedKeyUsageList,
SendAsTrustedIssuer) using Select-Object .

PowerShell

$c = Get-Item cert:\LocalMachine\My\52A149D0393CE8A8D4AF0B172ED667A9E3A1F44E

$c | Format-List DnsNameList, EnhancedKeyUsageList, SendAsTrustedIssuer

Output

DnsNameList : {SERVER01.contoso.com}

EnhancedKeyUsageList : {WiFi-Machine (1.3.6.1.4.1.311.42.2.6),

Client Authentication (1.3.6.1.5.5.7.3.2)}

SendAsTrustedIssuer : False

Find all CodeSigning certificates


This command uses the CodeSigningCert and Recurse parameters of the
Get-ChildItem
cmdlet to get all of the certificates on the computer that have
code-signing authority.

PowerShell

Get-ChildItem -Path cert: -CodeSigningCert -Recurse

Find expired certificates


This command uses the ExpiringInDays parameter of the Get-ChildItem cmdlet
to get
certificates that will expire within the next 30 days.

PowerShell

Get-ChildItem -Path cert:\LocalMachine\WebHosting -ExpiringInDays 30

Find Server SSL Certificates


This command uses the SSLServerAuthentication parameter of the
Get-ChildItem
cmdlet to get all Server SSL Certificates in the My and
WebHosting stores.

PowerShell

Get-ChildItem -Path cert:\LocalMachine\My, cert:\LocalMachine\WebHosting `

-SSLServerAuthentication

Find expired certificates on remote computers


This command uses the Invoke-Command cmdlet to run a Get-ChildItem command
on
the Srv01 and Srv02 computers. A value of zero ( 0 ) in the
ExpiringInDays parameter
gets certificates on the Srv01 and Srv02 computers
that have expired.

PowerShell

Invoke-Command -ComputerName Srv01, Srv02 {Get-ChildItem -Path cert:\* `

-Recurse -ExpiringInDays 0}

Combining filters to find a specific set of certificates


This command gets all certificates in the LocalMachine store location that
have the
following attributes:

fabrikam in their DNS name

Client Authentication in their EKU


a value of $true for the SendAsTrustedIssuer property
do not expire within the next 30 days.

The NotAfter property stores the certificate expiration date.

PowerShell

[DateTime] $ValidThrough = (Get-Date) + (New-TimeSpan -Days 30)

Get-ChildItem -Path cert:\* -Recurse -DNSName "*fabrikam*" `

-EKU "*Client Authentication*" | Where-Object {

$_.SendAsTrustedIssuer -and `
$_.NotAfter -gt $ValidThrough

Opening the Certificates MMC Snap-in


The Invoke-Item cmdlet will use the default application to open a path you
specify. For
certificates, the default application is the Certificates MMC
snap-in.

This command opens the Certificates MMC snap-in to manage the specified
certificate.

PowerShell

Invoke-Item cert:\CurrentUser\my\6B8223358119BB08840DEE50FD8AF9EA776CE66B

Copying Certificates
Copying certificates is not supported by the Certificate provider. When you
attempt to
copy a certificate, you see this error.

$path = "Cert:\LocalMachine\Root\E2C0F6662D3C569705B4B31FE2CBF3434094B254"

PS Cert:\LocalMachine\> Copy-Item -Path $path -Destination .\CA\

Copy-Item : Provider operation stopped because the provider does not support

this operation.

At line:1 char:1

+ Copy-Item -Path $path -Destination .\CA\

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : NotImplemented: (:) [Copy-Item],

PSNotSupportedException

+ FullyQualifiedErrorId : NotSupported,

Microsoft.PowerShell.Commands.CopyItemCommand

Moving Certificates

Move all SSL Server authentication certs to the


WebHosting store
This command uses the Move-Item cmdlet to move a certificate from the My
store to the
WebHosting store.

Move-Item will not move certificate stores and it will not move certificates
to a different

store location, such as moving a certificate from LocalMachine


to CurrentUser . The
Move-Item cmdlet moves certificates, but it does not
move private keys.

This command uses the SSLServerAuthentication parameter of the


Get-ChildItem
cmdlet to get SSL server authentication certificates in the My
certificate store.

The returned certificates are piped to the Move-Item cmdlet, which moves the
certificates to the WebHosting store.

PowerShell

Get-ChildItem cert:\LocalMachine\My -SSLServerAuthentication | Move-Item `

-Destination cert:\LocalMachine\WebHosting

Deleting Certificates and Private Keys


The Remove-Item cmdlet will remove certificates that you specify. The
DeleteKey
dynamic parameter deletes the private key.

Delete a Certificate from the CA store


This command deletes a certificate from the CA certificate store, but leaves the
associated private key intact.

In the Cert: drive, the Remove-Item cmdlet supports only the DeleteKey,
Path, WhatIf,
and Confirm parameters. All other parameters are
ignored.
PowerShell

Remove-Item cert:\LocalMachine\CA\5DDC44652E62BF9AA1116DC41DE44AB47C87BDD0

Delete a Certificate using a wildcards in the DNS name


This command deletes all certificates that have a DNS name that contains
Fabrikam . It
uses the DNSName parameter of the Get-ChildItem cmdlet to
get the certificates and
the Remove-Item cmdlet to delete them.

PowerShell

Get-ChildItem -Path cert:\LocalMachine -DnsName *Fabrikam* | Remove-Item

Delete private keys from a remote computer


This series of commands enables delegation and then deletes the certificate and
associated private key on a remote computer. To delete a private key on a
remote
computer, you must use delegated credentials.

Use the Enable-WSManCredSSP cmdlet to enable Credential Security Service


Provider
(CredSSP) authentication on a client on the S1 remote computer.
CredSSP permits
delegated authentication.

PowerShell

Enable-WSManCredSSP -Role Client -DelegateComputer S1

Use the Connect-WSMan cmdlet to connect the S1 computer to the WinRM service on
the
local computer. When this command completes, the S1 computer appears in the
local
WSMan: drive in PowerShell.

PowerShell

Connect-WSMan -ComputerName S1 -Credential Domain01\Admin01

Now, you can use the Set-Item cmdlet in the WSMan: drive to enable the
CredSSP
attribute for the WinRM service.

PowerShell
Set-Item -Path WSMan:\S1\Service\Auth\CredSSP -Value $true

Start a remote session on the S1 computer using the New-PSSession cmdlet, and
specify
CredSSP authentication. Saves the session in the $s variable.

PowerShell

$s = New-PSSession S1 -Authentication CredSSP -Credential Domain01\Admin01

Finally, use the Invoke-Command cmdlet to run a Remove-Item command in the


session in
the $s variable. The Remove-Item command uses the DeleteKey
parameter to remove
the private key along with the specified certificate.

PowerShell

Invoke-Command -Session $s { Remove-Item `

-Path cert:\LocalMachine\My\D2D38EBA60CAA1C12055A2E1C83B15AD450110C2 `

-DeleteKey

Delete expired Certificates


This command uses the ExpiringInDays parameter of the Get-ChildItem cmdlet
with a
value of 0 to get certificates in the WebHosting store that have
expired.

The variable containing the returned certificates is piped to the Remove-Item


cmdlet,
which deletes them. The command uses the DeleteKey parameter to
delete the private
key along with the certificate.

PowerShell

$expired = Get-ChildItem cert:\LocalMachine\WebHosting -ExpiringInDays 0

$expired | Remove-Item -DeleteKey

Creating Certificates
The New-Item cmdlet does not create new certificates in the Certificate
provider. Use the
New-SelfSignedCertificate
cmdlet to create a certificate for testing purposes.

Creating Certificate Stores


In the Cert: drive, the New-Item cmdlet creates certificate stores in the
LocalMachine
store location. It supports the Name, Path, WhatIf,
and Confirm parameters. All other
parameters are ignored. The command
returns a
System.Security.Cryptography.X509Certificates.X509Store that
represents the new
certificate store.

This command creates a new certificate store named CustomStore in the


LocalMachine
store location.

PowerShell

New-Item -Path cert:\LocalMachine\CustomStore

Create a new certificate store on a remote computer


This command creates a new certificate store named HostingStore in the
LocalMachine
store location on the Server01 computer.

The command uses the Invoke-Command cmdlet to run a New-Item command on the
Server01 computer. The command returns a
System.Security.Cryptography.X509Certificates.X509Store that represents the
new
certificate store.

PowerShell

Invoke-Command { New-Item -Path cert:\LocalMachine\CustomStore } `

-ComputerName Server01

Creating Client Certificates for WS-Man


This command creates ClientCertificate entry that can be used by the
WS-Management
client. The new ClientCertificate will show up under the
ClientCertificate directory as
ClientCertificate_1234567890 . All of the
parameters are mandatory. The Issuer needs to

be thumbprint of the issuer's


certificate.

PowerShell

$cred = Get-Credential

New-Item -Path WSMan:\localhost\ClientCertificate `

-Issuer 1b3fd224d66c6413fe20d21e38b304226d192dfe `

-URI wmicimv2/* -Credential $cred

Deleting Certificate Stores

Delete a certificate store from a remote computer


This command uses the Invoke-Command cmdlet to run a Remove-Item command on
the
S1 and S2 computers. The Remove-Item command includes the Recurse
parameter,
which deletes the certificates in the store before it deletes the
store.

PowerShell

Invoke-Command { Remove-Item -Path cert:\LocalMachine\TestStore -Recurse } `

-ComputerName S1, S2

Dynamic parameters
Dynamic parameters are cmdlet parameters that are added by a PowerShell provider
and are available only when the cmdlet is being used in the provider-enabled
drive.
These parameters are valid in all subdirectories of the Certificate
provider, but are
effective only on certificates.

7 Note

Parameters that perform filtering against the EnhancedKeyUsageList


property also
return items with an empty EnhancedKeyUsageList
property value. Certificates that
have an empty EnhancedKeyUsageList can
be used for all purposes.

CodeSigningCert
<System.Management.Automation.SwitchParameter>

Cmdlets supported

Get-Item
Get-ChildItem

This parameter gets certificates that have Code Signing in their


EnhancedKeyUsageList
property value.
DeleteKey
<System.Management.Automation.SwitchParameter>

Cmdlets supported
Remove-Item

This parameter deletes the associated private key when it deletes the
certificate.

) Important

To delete a private key that is associated with a user certificate in the


Cert:\CurrentUser store on a remote computer, you must use delegated
credentials. The Invoke-Command cmdlet supports credential delegation using
the
CredSSP parameter. You should consider any security risks before using
Remove-
Item with Invoke-Command and credential delegation.

This parameter was introduced in PowerShell 3.0.

DnsName
<Microsoft.PowerShell.Commands.DnsNameRepresentation>

Cmdlets supported

Get-ChildItem

This parameter gets certificates that have the specified domain name or name
pattern in
the DNSNameList property of the certificate. The value of this
parameter can either be
Unicode or ASCII . Punycode values are converted to
Unicode. Wildcard characters ( * )
are permitted.

This parameter was introduced in PowerShell 3.0.

DocumentEncryptionCert
<System.Management.Automation.SwitchParameter>

Cmdlets supported

Get-Item
Get-ChildItem

This parameter gets certificates that have Document Encryption in their


EnhancedKeyUsageList property value.

EKU <System.String>

Cmdlets supported
Get-ChildItem

This parameter gets certificates that have the specified text or text pattern in
the
EnhancedKeyUsageList property of the certificate. Wildcard
characters ( * ) are
permitted. The EnhancedKeyUsageList property contains
the friendly name and the OID
fields of the EKU.

This parameter was introduced in PowerShell 3.0.

ExpiringInDays <System.Int32>

Cmdlets supported
Get-ChildItem

This parameter gets certificates that are expiring in or before the specified
number of
days. A value of zero (0) gets certificates that have expired.

This parameter was introduced in PowerShell 3.0.

ItemType <System.String>
This parameter allows you to specify the type of item created by New-Item .

In a Certificate drive, the following values are allowed:

Certificate Provider

Certificate

Store
StoreLocation

Cmdlets Supported
New-Item

SSLServerAuthentication
<System.Management.Automation.SwitchParameter>

Cmdlets supported

Get-ChildItem

Gets only server certificates for SSL web hosting. This parameter gets
certificates that
have Server Authentication in their EnhancedKeyUsageList
property value.

This parameter was introduced in PowerShell 3.0.

Script properties
New script properties have been added to the x509Certificate2 object that
represents
the certificates to make it easy to search and manage the
certificates.

DnsNameList: To populate the DnsNameList property, the Certificate


provider
copies the content from the DNSName entry in the
SubjectAlternativeName (SAN)
extension. If the SAN extension is empty, the
property is populated with content
from the Subject field of the certificate.
EnhancedKeyUsageList: To populate the EnhancedKeyUsageList property,
the
Certificate provider copies the OID properties of the EnhancedKeyUsage
(EKU) field
in the certificate and creates a friendly name for it.
SendAsTrustedIssuer: To populate the SendAsTrustedIssuer property, the
Certificate provider copies the SendAsTrustedIssuer property from the
certificate.
For more information see
Management of trusted issuers for client authentication.

These new features let you search for certificates based on their DNS names and
expiration dates, and distinguish client and server authentication certificates
by the
value of their Enhanced Key Usage (EKU) properties.

Using the pipeline


Provider cmdlets accept pipeline input. You can use the pipeline to simplify
tasks by
sending provider data from one cmdlet to another provider cmdlet.
To read more about
how to use the pipeline with provider cmdlets, see the
cmdlet references provided
throughout this article.
Getting help
Beginning in PowerShell 3.0, you can get customized help topics for
provider cmdlets
that explain how those cmdlets behave in a file system drive.

To get the help topics that are customized for the file system drive, run a
Get-Help
command in a file system
drive or use the -Path parameter of Get-Help to specify a file
system drive.

PowerShell

Get-Help Get-ChildItem

PowerShell

Get-Help Get-ChildItem -Path cert:

See also
about_Providers
about_Signing
Get-AuthenticodeSignature
Set-AuthenticodeSignature
Get-PfxCertificate
ConvertFrom-SecureString
Reference
Module: Microsoft.PowerShell.Security

Converts a secure string to an encrypted standard string.

Syntax
PowerShell

ConvertFrom-SecureString

[-SecureString] <SecureString>

[[-SecureKey] <SecureString>]

[<CommonParameters>]

PowerShell

ConvertFrom-SecureString

[-SecureString] <SecureString>

[-Key <Byte[]>]

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


Advanced
Encryption Standard (AES) 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 AES encryption algorithm. If no
key is specified, the Windows Data Protection API
(DPAPI) is used to encrypt the standard string
representation.

Examples

Example 1: Create a secure string


PowerShell

$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 ( * ) is
displayed to represent each character that you type.

Example 2: Convert a secure string to an encrypted


standard string
PowerShell

$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: Convert a secure string to an encrypted


standard string with a 192-bit key
PowerShell

$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)

$StandardString = ConvertFrom-SecureString $SecureString -Key $Key

These commands use the Advanced Encryption Standard (AES) 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 decimal
numerals,
each of which must be less than 256 to fit within a single unsigned byte.

Because each decimal numeral represents a single 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 AES algorithm.

The second command uses the key in the $Key variable to convert the secure string to
an encrypted
standard string.
Parameters
-Key

Specifies the encryption key as a byte array.

Type: Byte[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SecureKey

Specifies the encryption key as a secure string. The secure string value is converted
to a byte
array before being used as the key.

Type: SecureString

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SecureString

Specifies the secure string to convert to an encrypted standard string.

Type: SecureString

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

Inputs
SecureString

You can pipe a SecureString object to this cmdlet.

Outputs
String

This cmdlet returns the created plain text string.

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 decimal numerals.
Similarly, 192-bit and 256-bit keys correspond to byte arrays
of 24 and 32 decimal numerals,
respectively.
Some characters, such as emoticons, correspond to several code points in the
string that contains
them. Avoid using these characters because they may cause
problems and misunderstandings when used
in a password.

Related Links
ConvertTo-SecureString
Read-Host
ConvertTo-SecureString
Reference
Module: Microsoft.PowerShell.Security

Converts plain text or encrypted strings to secure strings.

Syntax
PowerShell

ConvertTo-SecureString

[-String] <String>

[[-SecureKey] <SecureString>]

[<CommonParameters>]

PowerShell

ConvertTo-SecureString

[-String] <String>

[-AsPlainText]

[-Force]

[<CommonParameters>]

PowerShell

ConvertTo-SecureString

[-String] <String>

[-Key <Byte[]>]

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

Examples

Example 1: Convert a secure string to an encrypted string


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.

PowerShell

PS C:\> $Secure = Read-Host -AsSecureString

PS C:\> $Secure

System.Security.SecureString

PS C:\> $Encrypted = ConvertFrom-SecureString -SecureString $Secure

PS C:\> $Encrypted

01000000d08c9ddf0115d1118c7a00c04fc297eb010000001a114d45b8dd3f4aa11ad7c0abda
e98000000000

02000000000003660000a8000000100000005df63cea84bfb7d70bd6842e7efa798200000000
04800000a000

000010000000f10cd0f4a99a8d5814d94e0687d7430b100000008bf11f1960158405b2779613
e9352c6d1400

0000e6b7bf46a9d485ff211b9b2a2df3bd6eb67aae41

PS C:\> $Secure2 = ConvertTo-SecureString -String $Encrypted

PS C:\> $Secure2

System.Security.SecureString

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, 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: Create a secure string from an encrypted


string in a file
This example shows how to create a secure string from an encrypted standard string
that is saved in a file.

PowerShell

$Secure = Read-Host -AsSecureString

$Encrypted = ConvertFrom-SecureString -SecureString $Secure -Key (1..16)

$Encrypted | Set-Content Encrypted.txt

$Secure2 = Get-Content Encrypted.txt | ConvertTo-SecureString -Key (1..16)

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: Convert a plain text string to a secure string


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.

PowerShell
$Secure_String_Pwd = ConvertTo-SecureString "P@ssW0rD!" -AsPlainText -Force

U Caution

You should avoid using plain text strings in script or from the command line. The
plain text can
show up in event logs and command history logs.

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.

Type: SwitchParameter

Position: 1

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.

Type: SwitchParameter

Position: 2

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Key
Specifies the encryption key used to convert the original secure string into the
encrypted standard
string. Valid key lengths are 16, 24 and 32 bytes.

Type: Byte[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SecureKey

Specifies the encryption key used to convert the original secure string into the
encrypted standard
string. The key must be provided in the format of a secure string.
The secure string will be
converted to a byte array to be used as the key. Valid secure
key lengths are 8, 12 and 16 code
points.

Type: SecureString

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-String

Specifies the string to convert to a secure string.

Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

Inputs
String
You can pipe a standard encrypted string to this cmdlet.

Outputs
SecureString

This cmdlet returns the created SecureString object.

Notes
Some characters, such as emoticons, correspond to several code points in the string that
contains
them. Avoid using these characters because they may cause problems and
misunderstandings when used
in a password.

Related Links
ConvertFrom-SecureString
Read-Host
Get-Acl
Reference
Module: Microsoft.PowerShell.Security

Gets the security descriptor for a resource, such as a file or registry key.

Syntax
PowerShell

Get-Acl

[[-Path] <String[]>]

[-Audit]

[-AllCentralAccessPolicies]

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-UseTransaction]

[<CommonParameters>]

PowerShell

Get-Acl

-InputObject <PSObject>

[-Audit]

[-AllCentralAccessPolicies]

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-UseTransaction]

[<CommonParameters>]

PowerShell

Get-Acl

[-LiteralPath <String[]>]

[-Audit]

[-AllCentralAccessPolicies]

[-Filter <String>]

[-Include <String[]>]

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

Beginning in Windows PowerShell 3.0, you can use the InputObject parameter of Get-
Acl to get
the security descriptor of objects that do not have a path.

Examples

Example 1- Get an ACL for a folder


This example gets the security descriptor of the C:\Windows directory.

PowerShell

Get-Acl C:\Windows

Example 2 - Get an ACL for a folder using wildcards


This example gets the PowerShell path and SDDL for all of the .log files in the
C:\Windows
directory whose names begin with s .

PowerShell

Get-Acl C:\Windows\s*.log | Format-List -Property PSPath, Sddl

The command uses the Get-Acl cmdlet 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 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 - Get count of Audit entries for an ACL
This example gets the security descriptors of the .log files in the C:\Windows directory
whose
names begin with s .

PowerShell

Get-Acl C:\Windows\s*.log -Audit | ForEach-Object { $_.Audit.Count }

It uses the Audit parameter to get the audit records from the SACL in the security
descriptor.
Then it uses the ForEach-Object cmdlet 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 - Get an ACL for a registry key


This example uses the Get-Acl cmdlet to get the security descriptor of the Control
subkey
( HKLM:\SYSTEM\CurrentControlSet\Control ) of the registry.

PowerShell

Get-Acl -Path HKLM:\System\CurrentControlSet\Control | Format-List

The Path parameter specifies the Control subkey. The pipeline operator ( | ) passes the
security
descriptor that Get-Acl gets to the Format-List command, which formats the
properties of the
security descriptor as a list so that they are easy to read.

Example 5 - Get an ACL using **InputObject**


This example uses the InputObject parameter of Get-Acl to get the security descriptor
of a
storage subsystem object.

PowerShell

Get-Acl -InputObject (Get-StorageSubSystem -Name S087)

Parameters
-AllCentralAccessPolicies
Gets information about all central access policies that are enabled on the computer.

Beginning in Windows Server 2012, administrators can use Active Directory and
Group Policy to set
central access policies for users and groups. For more
information, see
Dynamic Access Control: Scenario Overview.

This parameter is introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Audit

Gets the audit data for the security descriptor from the system access control list
(SACL).

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Exclude

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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True


-Filter

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
getting the objects, rather than having PowerShell
filter the objects after they are retrieved.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Include

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

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-InputObject

Gets the security descriptor for the specified object. Enter a variable that contains the
object or
a command that gets the object.

You cannot pipe an object, other than a path, to Get-Acl . Instead, use the
InputObject
parameter explicitly in the command.

This parameter is introduced in Windows PowerShell 3.0.

Type: PSObject

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-LiteralPath

Specifies the path to a resource. 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 PowerShell not to
interpret any characters as escape sequences.

This parameter is introduced in Windows PowerShell 3.0.

Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Path

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.

Type: String[]

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

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

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a string that contains a path to this cmdlet.

Outputs
FileSecurity

DirectorySecurity

RegistrySecurity

This cmdlet 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 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, PowerShell displays the following properties and property values:

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. PowerShell uses the GetSddlForm
method of security
descriptors to get 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.

Related Links
Set-Acl
Get-AuthenticodeSignature
Reference
Module: Microsoft.PowerShell.Security

Gets information about the Authenticode signature for a file.

Syntax
PowerShell

Get-AuthenticodeSignature

[-FilePath] <String[]>

[<CommonParameters>]

PowerShell

Get-AuthenticodeSignature

-LiteralPath <String[]>

[<CommonParameters>]

PowerShell

Get-AuthenticodeSignature

-SourcePathOrExtension <String[]>

-Content <Byte[]>

[<CommonParameters>]

Description
The Get-AuthenticodeSignature cmdlet gets information about the Authenticode
signature for a
file or file content as a byte array.
If the file is both embedded signed and
Windows catalog signed,
the Windows catalog signature is used.
If the file is not signed,
the information is retrieved, but
the fields are blank.

Examples

Example 1: Get the Authenticode signature for a file


PowerShell
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: Get the Authenticode signature for multiple


files
PowerShell

Get-AuthenticodeSignature test.ps1, test1.ps1, sign-file.ps1, makexml.ps1

This command gets information about the Authenticode signature for the four files
listed at the
command line. In this example, the name of the FilePath parameter, which
is optional, is omitted.

Example 3: Get only valid Authenticode signatures for


multiple files
PowerShell

Get-ChildItem $PSHOME\*.* | ForEach-object {Get-AuthenticodeSignature $_} |


Where-Object {$_.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
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.

Example 4: Get the Authenticode signature for a file


content specified as byte array
PowerShell

Get-AuthenticodeSignature -Content (Get-Content foo.ps1 -AsByteStream) -


SourcePathorExtension ps1

This command gets information about the Authenticode signature for the content of a
file. In this
example, the file extension is specified along with the content of the file.

Parameters
-Content

Contents of a file as a byte array for which the Authenticode signature is retrieved.
This parameter
must be used with SourcePathOrExtension parameter. The contents
of the file must be in Unicode
(UTF-16LE) format.

Type: Byte[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-FilePath

Specifies the path to the file to examine. Wildcards are permitted, but they must lead
to a single
file. It is not necessary to type FilePath at the command line when you
specify a value for this
parameter.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-LiteralPath
Specifies the path to the file being examined. Unlike FilePath, the value of the
LiteralPath
parameter is used exactly as it is typed. No characters are interpreted as
wildcards. If the path
includes an escape character, enclose it in single quotation
marks. Single quotation marks tell
PowerShell not to interpret any characters as
escape characters.

Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-SourcePathOrExtension

Path to the file or file type of the content for which the Authenticode signature is
retrieved. This
parameter is used with Content where file content is passed as a byte
array.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

Inputs
String

You can pipe a string that contains a file path to this cmdlet.

Outputs
Signature

This cmdlet returns a signature object for each signature that it gets.
Notes
For information about Authenticode signatures in PowerShell, see
about_Signing.

Related Links
Get-ExecutionPolicy
Set-AuthenticodeSignature
Set-ExecutionPolicy
about_Execution_Policies
about_Signing
Get-CmsMessage
Reference
Module: Microsoft.PowerShell.Security

Gets content that has been encrypted by using the Cryptographic Message Syntax
format.

Syntax
PowerShell

Get-CmsMessage

[-Content] <String>

[<CommonParameters>]

PowerShell

Get-CmsMessage

[-Path] <String>

[<CommonParameters>]

PowerShell

Get-CmsMessage

[-LiteralPath] <String>

[<CommonParameters>]

Description
The Get-CmsMessage cmdlet gets content that has been encrypted using the
Cryptographic Message
Syntax (CMS) format.

The CMS cmdlets support encryption and decryption of content using the IETF format
for
cryptographically protecting messages, as documented by
RFC5652 .

The CMS encryption standard uses public key cryptography, where the keys used to
encrypt content
(the public key) and the keys used to decrypt content (the private key)
are separate. Your public
key can be shared widely, and is not sensitive data. If any
content is encrypted with this public
key, only your private key can decrypt it. For more
information, see
Public-key cryptography .
Get-CmsMessage gets content that has been encrypted in CMS format. It does not

decrypt or
unprotect content. You can run this cmdlet to get content that you have
encrypted by running the
Protect-CmsMessage cmdlet. You can specify content that you
want to decrypt as a string, or by
path to the encrypted content. You can pipe the results
of Get-CmsMessage to
Unprotect-CmsMessage to decrypt the content, provided that you
have information about the document
encryption certificate that was used to encrypt
the content.

Examples

Example 1: Get encrypted content


PowerShell

$Msg = Get-CmsMessage -Path


"C:\Users\Test\Documents\PowerShell\Future_Plans.txt"

$Msg.Content

-----BEGIN CMS-----

MIIBqAYJKoZIhvcNAQcDoIIBmTCCAZUCAQAxggFQMIIBTAIBADA0MCAxHjAcBgNVBAMBFWxlZWhv

bG1AbGljcm9zb2Z0LmNvbQIQQYHsbcXnjIJCtH+OhGmc1DANBgkqhkiG9w0BAQcwAASCAQAnkFHM

proJnFy4geFGfyNmxH3yeoPvwEYzdnsoVqqDPAd8D3wao77z7OhJEXwz9GeFLnxD6djKV/tF4PxR

E27aduKSLbnxfpf/sepZ4fUkuGibnwWFrxGE3B1G26MCenHWjYQiqv+Nq32Gc97qEAERrhLv6S4R

G+2dJEnesW8A+z9QPo+DwYP5FzD0Td0ExrkswVckpLNR6j17Yaags3ltNXmbdEXekhi6Psf2MLMP

TSO79lv2L0KeXFGuPOrdzPRwCkV0vNEqTEBeDnZGrjv/5766bM3GW34FXApod9u+VSFpBnqVOCBA

DVDraA6k+xwBt66cV84AHLkh0kT02SIHMDwGCSqGSIb3DQEHATAdBglghkgBZQMEASoEEJbJaiRl

KMnBoD1dkb/FzSWAEBaL8xkFwCu0e1AtDj7nSJc=

-----END CMS-----

This command gets encrypted content located at


C:\Users\Test\Documents\PowerShell\Future_Plans.txt.

Example 2: Pipe encrypted content to Unprotect-


CmsMessage
PowerShell

$Msg = Get-CmsMessage -Path


"C:\Users\Test\Documents\PowerShell\Future_Plans.txt"

$Msg | Unprotect-CmsMessage -To "cn=youralias@emailaddress.com"

Try the new Break All command


This command pipes the results of the Get-CmsMessage cmdlet from Example 1 to
Unprotect-CmsMessage , to decrypt the message and read it in plain text. In this case, the
value of
the To parameter is the value of the encrypting certificate's Subject line. The
decrypted
message, "Try the new Break All command," is the result.

Parameters
-Content

Specifies an encrypted string, or a variable containing an encrypted string.

Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-LiteralPath

Specifies the path to encrypted content that you want to get. Unlike Path, the value
of
LiteralPath is used exactly as it is typed. No characters are interpreted as wildcard
characters. If the path includes escape characters, enclose each one in single
quotation marks.
Single quotation marks tell PowerShell not to interpret enclosed
characters as escape characters.

Type: String

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Path

Specifies the path to encrypted content that you want to decrypt.

Type: String

Position: 1
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Related Links
about_Providers
Protect-CmsMessage
Unprotect-CmsMessage
Get-Credential
Reference
Module: Microsoft.PowerShell.Security

Gets a credential object based on a user name and password.

Syntax
PowerShell

Get-Credential

[-Credential] <PSCredential>

[<CommonParameters>]

PowerShell

Get-Credential

-Message <String>

[[-UserName] <String>]

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

Beginning in PowerShell 3.0, you can use the Message parameter to specify a
customized
message on the dialog box that prompts the user for their name and
password.

The Get-Credential cmdlet prompts the user for a password or a user name and
password. By default,
an authentication dialog box appears to prompt the user.
However, in some host programs, such as the
PowerShell console, you can prompt the
user at the command line by changing a registry entry. For
more information about this
registry entry, see the notes and examples.

Examples

Example 1
PowerShell

$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, some providers that are installed with
PowerShell do not support
the Credential parameter.

Example 2
PowerShell

$c = Get-Credential -credential User01

$c.Username

User01

This example creates a credential that includes a user name without a domain 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 3
PowerShell

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

The PromptForCredential method is an alternative to using the Get-Credential cmdlet.


When you
use PromptForCredential, you can specify the caption, messages, and user
name that appear in the
message box.

For more information, see the


PromptForCredential
documentation in the SDK.

Example 4
PowerShell

Set-ItemProperty "HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds" -Name


ConsolePrompting -Value $true

This example shows how to modify the registry so that the user is prompted at the
command line,
instead of by using a dialog box.

The command creates the ConsolePrompting registry entry and sets its value to True. To
run this
command, start PowerShell with the "Run as administrator" option.

To use a dialog box for prompting, set the value of the ConsolePrompting to false
($false) or use
the Remove-ItemProperty cmdlet to delete it.

The ConsolePrompting registry entry works in some host programs, such as the
PowerShell console. It
might not work in all host programs.

Example 5
This example shows how to create a credential object that is identical to the object that
Get-Credential returns without prompting the user. This method requires a plain text

password,
which might violate the security standards in some enterprises.

PowerShell

$User = "Domain01\User01"

$PWord = ConvertTo-SecureString -String "P@sSwOrd" -AsPlainText -Force

$Credential = New-Object -TypeName System.Management.Automation.PSCredential


-ArgumentList $User, $PWord

The first command saves the user account name in the $User parameter. The value must
have the
"Domain\User" or "ComputerName\User" format.

The second command uses the ConvertTo-SecureString cmdlet to create a secure string
from a plain
text password. The command uses the AsPlainText parameter to indicate
that the string is plain
text and the Force parameter to confirm that you understand the
risks of using plain text.
The third command uses the New-Object cmdlet to create a PSCredential object from
the values
in the $User and $PWord variables.

Example 6
PowerShell

Get-Credential -Message "Credential are required for access to the


\\Server1\Scripts file share." -User Server01\PowerUser

PowerShell Credential Request

Credential are required for access to the \\Server1\Scripts file share.

Password for user Server01\PowerUser:

This command uses the Message and UserName parameters of the Get-Credential
cmdlet. This
command format is designed for shared scripts and functions. In this case,
the message tells the
user why credentials are needed and gives them confidence that
the request is legitimate.

Example 7
PowerShell

Invoke-Command -ComputerName Server01 {Get-Credential Domain01\User02}

PowerShell Credential Request : PowerShell Credential Request

Warning: This credential is being requested by a script or application on


the SERVER01 remote computer. Enter your credentials only if you

trust the remote computer and the application or script requesting it.

Enter your credentials.

Password for user Domain01\User02: ***************

PSComputerName : Server01

RunspaceId : 422bdf52-9886-4ada-ab2f-130497c6777f

PSShowComputerName : True

UserName : Domain01\User01

Password : System.Security.SecureString

This command gets a credential from the Server01 remote computer. The command
uses the
Invoke-Command cmdlet to run a Get-Credential command on the remote
computer. The output shows
the remote security message that Get-Credential includes
in the authentication prompt.
Parameters
-Credential

Specifies a user name for the credential, such as User01 or Domain01\User01. The
parameter
name, -Credential , is optional.

When you submit the command and specify a user name, you're prompted for a
password. If you omit
this parameter, you're prompted for a user name and a
password.

Starting in PowerShell 3.0, if you enter a user name without a domain, Get-
Credential no longer
inserts a backslash before the name.

Credentials are stored in a PSCredential


object and the password is stored as a
SecureString.

7 Note

For more information about SecureString data protection, see


How secure is
SecureString?.

Type: PSCredential

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Message

Specifies a message that appears in the authentication prompt. This parameter is


designed for use in
a function or script. You can use the message to explain to the
user why you are requesting
credentials and how they will be used.

This parameter was introduced in PowerShell 3.0.

Type: String

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-UserName

Specifies a user name. The authentication prompt requests a password for the user
name. By default,
the user name is blank and the authentication prompt requests
both a user name and password.

When the authentication prompt appears in a dialog box, the user can edit the
specified user name.
However, the user cannot change the user name when the
prompt appears at the command line. When
using this parameter in a shared
function or script, consider all possible presentations.

This parameter was introduced in PowerShell 3.0.

Type: String

Position: 1

Default value: None (blank)

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
PSCredential

This cmdlet 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.
By default, the authentication prompt appears in a dialog box. To display the
authentication prompt
at the command line, add the ConsolePrompting registry entry
( HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\ConsolePrompting ) and set its value to
True.
If the ConsolePrompting registry entry does not exist or if its value is False, the
authentication prompt appears in a dialog box. For instructions, see the examples.

The ConsolePrompting registry entry works in the PowerShell console, but it does not
work in all host programs.

For example, it has no effect in the PowerShell Integrated Scripting Environment (ISE).
For
information about the effect of the ConsolePrompting registry entry, see the help
topics for the
host program.

The Credential parameter is not supported by all providers that are installed with
PowerShell.
Beginning in PowerShell 3.0, it is supported on select cmdlets, such as the
Get-Content
and New-PSDrive cmdlets.

Related Links
PromptForCredential
Get-ExecutionPolicy
Reference
Module: Microsoft.PowerShell.Security

Gets the execution policies for the current session.

Syntax
PowerShell

Get-ExecutionPolicy

[[-Scope] <ExecutionPolicyScope>]

[-List]

[<CommonParameters>]

Description
To display the execution policies for each scope in the order of precedence, use
Get-
ExecutionPolicy -List . To see the effective execution policy for your PowerShell session

use
Get-ExecutionPolicy with no parameters.

The effective execution policy is determined by execution policies that are set by
Set-
ExecutionPolicy and Group Policy settings.

For more information, see about_Execution_Policies.

Examples

Example 1: Get all execution policies


This command displays the execution policies for each scope in the order of precedence.

PowerShell

Get-ExecutionPolicy -List

Scope ExecutionPolicy

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

MachinePolicy Undefined

UserPolicy Undefined

Process Undefined

CurrentUser AllSigned

LocalMachine Undefined

The Get-ExecutionPolicy cmdlet uses the List parameter to display each scope's
execution
policy.

Example 2: Set an execution policy


This example shows how to set an execution policy for the local computer.

PowerShell

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope LocalMachine

Get-ExecutionPolicy -List

Scope ExecutionPolicy

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

MachinePolicy Undefined

UserPolicy Undefined

Process Undefined

CurrentUser AllSigned

LocalMachine RemoteSigned

The Set-ExecutionPolicy cmdlet uses the ExecutionPolicy parameter to specify the


RemoteSigned policy. The Scope parameter specifies the default scope value,
LocalMachine. To view the execution policy settings, use the Get-ExecutionPolicy
cmdlet with
the List parameter.

Example 3: Get the effective execution policy


This example shows how to display the effective execution policy for a PowerShell
session.

PowerShell

PS> Get-ExecutionPolicy -List

Scope ExecutionPolicy

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

MachinePolicy Undefined

UserPolicy Undefined

Process Undefined

CurrentUser AllSigned

LocalMachine RemoteSigned

PS> Get-ExecutionPolicy

AllSigned

The Get-ExecutionPolicy cmdlet uses the List parameter to display each scope's
execution
policy. The Get-ExecutionPolicy cmdlet is run without a parameter to display
the effective
execution policy, AllSigned.

Example 4: Unblock a script to run it without changing


the execution policy
This example shows how the RemoteSigned execution policy prevents you from running
unsigned
scripts.

A best practice is to read the script's code and verify it's safe before using the
Unblock-
File cmdlet. The Unblock-File cmdlet unblocks scripts so they can run, but doesn't

change the execution policy.

PowerShell

PS> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope LocalMachine

PS> Get-ExecutionPolicy

RemoteSigned

PS> .\Start-ActivityTracker.ps1

.\Start-ActivityTracker.ps1 : File .\Start-ActivityTracker.ps1 cannot be


loaded.

The file .\Start-ActivityTracker.ps1 is not digitally signed.

The script will not execute on the system.

For more information, see about_Execution_Policies at


https://go.microsoft.com/fwlink/?LinkID=135170.

At line:1 char:1

+ .\Start-ActivityTracker.ps1

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : NotSpecified: (:) [], PSSecurityException

+ FullyQualifiedErrorId : UnauthorizedAccess

PS> Unblock-File -Path .\Start-ActivityTracker.ps1

PS> Get-ExecutionPolicy

RemoteSigned

PS> .\Start-ActivityTracker.ps1

Task 1:
The Set-ExecutionPolicy uses the ExecutionPolicy parameter to specify the
RemoteSigned
policy. The policy is set for the default scope, LocalMachine.

The Get-ExecutionPolicy cmdlet shows that RemoteSigned is the effective execution


policy for
the current PowerShell session.

The Start-ActivityTracker.ps1 script is executed from the current directory. The script is
blocked by RemoteSigned because the script isn't digitally signed.

For this example, the script's code was reviewed and verified as safe to run. The
Unblock-File
cmdlet uses the Path parameter to unblock the script.

To verify that Unblock-File didn't change the execution policy, Get-ExecutionPolicy


displays the
effective execution policy, RemoteSigned.

The script, Start-ActivityTracker.ps1 is executed from the current directory. The script
begins
to run because it was unblocked by the Unblock-File cmdlet.

Parameters
-List

Gets all execution policy values for the session listed in precedence order. By default,
Get-ExecutionPolicy gets only the effective execution policy.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Scope

Specifies the scope that is affected by an execution policy.

The effective execution policy is determined by the order of precedence as follows:

MachinePolicy. Set by a Group Policy for all users of the computer.


UserPolicy. Set by a Group Policy for the current user of the computer.
Process. Affects only the current PowerShell session.
CurrentUser. Affects only the current user.
LocalMachine. Default scope that affects all users of the computer.

Type: ExecutionPolicyScope

Accepted values: CurrentUser, LocalMachine, MachinePolicy, Process, UserPolicy

Position: 0

Default value: Effective execution policy

Accept pipeline input: True

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
ExecutionPolicy

This cmdlet returns the current execution policy.

Notes
An execution policy is part of the PowerShell security strategy. Execution policies
determine
whether you can load configuration files, such as your PowerShell profile, or
run scripts. And,
whether scripts must be digitally signed before they are run.

Related Links
about_Execution_Policies
about_Group_Policy_Settings
Get-AuthenticodeSignature
Set-AuthenticodeSignature
Set-ExecutionPolicy
Get-PfxCertificate
Reference
Module: Microsoft.PowerShell.Security

Gets information about PFX certificate files on the computer.

Syntax
PowerShell

Get-PfxCertificate

[-FilePath] <String[]>

[<CommonParameters>]

PowerShell

Get-PfxCertificate

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

Examples

Example 1: Get a PFX certificate


PowerShell

Get-PfxCertificate -FilePath "C:\windows\system32\Test.pfx"

Password: ******

Signer Certificate: David Chew (Self Certificate)

Time Certificate:

Time Stamp:

Path: C:\windows\system32\zap.pfx

This command gets information about the Test.pfx certificate file on the system.
Example 2: Get a PFX certificate from a remote computer
PowerShell

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

Parameters
-FilePath

Specifies the full path to the PFX file of the secured file. If you specify a value for this
parameter, it is not necessary to type -FilePath at the command line.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-LiteralPath

The full path to the PFX file of the secured file. Unlike FilePath, 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 PowerShell not to interpret any characters as escape
sequences.

Type: String[]

Aliases: PSPath

Position: Named

Default value: None


Accept pipeline input: True

Accept wildcard characters: False

Inputs
String

You can pipe a string that contains a file path to Get-PfxCertificate .

Outputs
X509Certificate2

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.

Related Links
Get-AuthenticodeSignature
Set-AuthenticodeSignature
New-FileCatalog
Reference
Module: Microsoft.PowerShell.Security

New-FileCatalog creates a catalog file of file hashes that can be used to validate the

authenticity of a file.

Syntax
PowerShell

New-FileCatalog

[-CatalogVersion <Int32>]

[-CatalogFilePath] <String>

[[-Path] <String[]>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
New-FileCatalog creates a Windows catalog file
for a set of folders and files. This

catalog file contains hashes for all files in the provided


paths. Users can then distribute
the catalog with their files so that users can validate whether any
changes have been
made to the folders since catalog creation time.

Catalog versions 1 and 2 are supported. Version 1 uses the (deprecated) SHA1 hashing
algorithm to
create file hashes, and version 2 uses SHA256. Catalog version 2 is not
supported on Windows Server
2008 R2 or Windows 7. You should use catalog version 2
on Windows 8, Windows Server 2012, and later
operating systems.

Examples

Example 1: Create a file catalog for


`Microsoft.PowerShell.Utility`
PowerShell

New-FileCatalog -Path $PSHOME\Modules\Microsoft.PowerShell.Utility -


CatalogFilePath \temp\Microsoft.PowerShell.Utility.cat -CatalogVersion 2.0

Mode LastWriteTime Length Name

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

-a---- 11/2/2018 11:58 AM 950


Microsoft.PowerShell.Utility.cat

Parameters
-CatalogFilePath

A path to a file or folder where the catalog file (.cat) should be placed. If a folder
path is
specified, the default filename catalog.cat will be used.

Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-CatalogVersion

Accepts 1.0 or 2.0 as possible values for specifying the catalog version. 1.0 should
be used
avoided whenever possible, as it uses the insecure SHA-1 hash algorithm,
while 2.0 uses the secure
SHA-256 algorithm However, 1.0 is the only supported
algorithm on Windows 7 and Server 2008R2.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter
Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Path

Accepts a path or array of paths to files or folders that should be included in the
catalog file. If
a folder is specified, all the files in the folder will be included as well.

Type: String[]

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a string that is used as the catalog filename to this cmdlet.
Outputs
FileInfo

This cmdlet returns a FileInfo object representing the created catalog.

Notes
This cmdlet is only available on Windows platforms.

Related Links
Test-FileCatalog
PowerShellGet
Protect-CmsMessage
Reference
Module: Microsoft.PowerShell.Security

Encrypts content by using the Cryptographic Message Syntax format.

Syntax
PowerShell

Protect-CmsMessage

[-To] <CmsMessageRecipient[]>

[-Content] <PSObject>

[[-OutFile] <String>]

[<CommonParameters>]

PowerShell

Protect-CmsMessage

[-To] <CmsMessageRecipient[]>

[-Path] <String>

[[-OutFile] <String>]

[<CommonParameters>]

PowerShell

Protect-CmsMessage

[-To] <CmsMessageRecipient[]>

[-LiteralPath] <String>

[[-OutFile] <String>]

[<CommonParameters>]

Description
The Protect-CmsMessage cmdlet encrypts content by using the Cryptographic Message
Syntax (CMS)
format.

The CMS cmdlets support encryption and decryption of content using the IETF format as
documented by
RFC5652 .

The CMS encryption standard uses public key cryptography, where the keys used to
encrypt content
(the public key) and the keys used to decrypt content (the private key)
are separate. Your public
key can be shared widely, and is not sensitive data. If any
content is encrypted with this public
key, only your private key can decrypt it. For more
information, see
Public-key cryptography .

Before you can run the Protect-CmsMessage cmdlet, you must have an encryption
certificate set up.
To be recognized in PowerShell, encryption certificates require a
unique extended key usage
(EKU) ID to identify them as data encryption certificates
(such as
the IDs for Code Signing and Encrypted Mail). For an example of a certificate
that would work for
document encryption, see Example 1 in this topic.

Examples

Example 1: Create a certificate for encrypting content


Before you can run the Protect-CmsMessage cmdlet, you must create an encryption
certificate. Using
the following text, change the name in the Subject line to your name,
email, or other identifier,
and save the certificate in a file (such as
DocumentEncryption.inf , as shown in this example).

PowerShell

# Create .INF file for certreq

{[Version]

Signature = "$Windows NT$"

[Strings]

szOID_ENHANCED_KEY_USAGE = "2.5.29.37"

szOID_DOCUMENT_ENCRYPTION = "1.3.6.1.4.1.311.80.1"

[NewRequest]

Subject = "cn=youralias@emailaddress.com"

MachineKeySet = false

KeyLength = 2048

KeySpec = AT_KEYEXCHANGE

HashAlgorithm = Sha1

Exportable = true

RequestType = Cert

KeyUsage = "CERT_KEY_ENCIPHERMENT_KEY_USAGE |
CERT_DATA_ENCIPHERMENT_KEY_USAGE"
ValidityPeriod = "Years"

ValidityPeriodUnits = "1000"

[Extensions]

%szOID_ENHANCED_KEY_USAGE% = "{text}%szOID_DOCUMENT_ENCRYPTION%"

} | Out-File -FilePath DocumentEncryption.inf

# After you have created your certificate file, run the following command to
add

# the certificate file to the certificate store. Now you are ready to
encrypt and

# decrypt content with the next two examples.

certreq.exe -new DocumentEncryption.inf DocumentEncryption.cer

Example 2: Encrypt a message sent by email


PowerShell

$Protected = "Hello World" | Protect-CmsMessage -To


"*youralias@emailaddress.com*"

In the following example, you encrypt a message, "Hello World", by piping it to the
Protect-CmsMessage cmdlet, and then save the encrypted message in a variable. The To

parameter
uses the value of the Subject line in the certificate.

Example 3: View document encryption certificates


PowerShell

PS C:\> cd Cert:\CurrentUser\My

PS Cert:\CurrentUser\My> Get-ChildItem -DocumentEncryptionCert

To view document encryption certificates in the certificate provider, you can add the
DocumentEncryptionCert dynamic parameter of
Get-ChildItem, available only when the
certificate provider is loaded.

Parameters
-Content

Specifies a PSObject that contains content that you want to encrypt. For example,
you can
encrypt the content of an event message, and then use the variable
containing the message ( $Event ,
in this example) as the value of the Content
parameter:
$event = Get-WinEvent -ProviderName "PowerShell" -MaxEvents 1 . You
can also use the Get-Content
cmdlet to get the contents of a file, such as a Microsoft
Word document, and save the content in a
variable that you use as the value of the
Content parameter.

Type: PSObject
Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-LiteralPath

Specifies the path to content that you want to encrypt. 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
PowerShell not to interpret any characters as escape sequences.

Type: String

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-OutFile

Specifies the path and file name of a file to which you want to send the encrypted
content.

Type: String

Position: 2

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Path

Specifies the path to content that you want to encrypt.

Type: String

Position: 1
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-To

Specifies one or more CMS message recipients, identified in any of the following
formats:

An actual certificate (as retrieved from the certificate provider).


Path to the file containing the certificate.
Path to a directory containing the certificate.
Thumbprint of the certificate (used to look in the certificate store).
Subject name of the certificate (used to look in the certificate store).

Type: CmsMessageRecipient[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Related Links
about_Providers
Get-CmsMessage
Unprotect-CmsMessage
Set-Acl
Reference
Module: Microsoft.PowerShell.Security

Changes the security descriptor of a specified item, such as a file or a registry key.

Syntax
PowerShell

Set-Acl

[-Path] <String[]>

[-AclObject] <Object>

[[-CentralAccessPolicy] <String>]

[-ClearCentralAccessPolicy]

[-Passthru]

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

PowerShell

Set-Acl

[-InputObject] <PSObject>

[-AclObject] <Object>

[-Passthru]

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

PowerShell

Set-Acl

-LiteralPath <String[]>

[-AclObject] <Object>

[[-CentralAccessPolicy] <String>]

[-ClearCentralAccessPolicy]

[-Passthru]

[-Filter <String>]

[-Include <String[]>]

[-Exclude <String[]>]

[-WhatIf]

[-Confirm]

[-UseTransaction]

[<CommonParameters>]

Description
The Set-Acl cmdlet changes the security descriptor of a specified item, 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 or InputObject parameter to identify the item whose
security
descriptor you want to change. Then, use the AclObject or SecurityDescriptor
parameters to
supply a security descriptor that has the values you want to apply. Set-
Acl applies the security
descriptor that is supplied. It uses the value of the AclObject

parameter as a model and changes


the values in the item's security descriptor to match
the values in the AclObject parameter.

Examples

Example 1: Copy a security descriptor from one file to


another
PowerShell

$DogACL = Get-Acl -Path "C:\Dog.txt"

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: Use the pipeline operator to pass a descriptor


PowerShell

Get-Acl -Path "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 from 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 cmdlet.

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: Apply a security descriptor to multiple files


PowerShell

$NewAcl = Get-Acl File0.txt

Get-ChildItem -Path "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 the Set-
Acl
cmdlet, 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 item. 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.

Example 4: Disable inheritance and preserve inherited


access rules
PowerShell

$NewAcl = Get-Acl -Path "C:\Pets\Dog.txt"

$isProtected = $true

$preserveInheritance = $true

$NewAcl.SetAccessRuleProtection($isProtected, $preserveInheritance)

Set-Acl -Path "C:\Pets\Dog.txt" -AclObject $NewAcl

These commands disable access inheritance from parent folders, while still preserving
the existing
inherited access rules.

The first command uses the Get-Acl cmdlet to get the security descriptor of the Dog.txt
file.

Next, variables are created to convert the inherited access rules to explicit access rules.
To
protect the access rules associated with this from inheritance, set the $isProtected
variable to
$true . To allow inheritance, set $isProtected to $false . For more
information, see
set access rule protection.

Set the $preserveInheritance variable to $true to preserve inherited access rules or


$false to
remove inherited access rules. Then the access rule protection is updated
using the
SetAccessRuleProtection() method.

The last command uses Set-Acl to apply the security descriptor of to Dog.txt. When the
command
completes, the ACLs of the Dog.txt that were inherited from the Pets folder
will be applied directly
to Dog.txt, and new access policies added to Pets will not change
the access to Dog.txt.

Example 5: Grant Administrators Full Control of the file


PowerShell

$NewAcl = Get-Acl -Path "C:\Pets\Dog.txt"

# Set properties

$identity = "BUILTIN\Administrators"

$fileSystemRights = "FullControl"

$type = "Allow"

# Create new rule

$fileSystemAccessRuleArgumentList = $identity, $fileSystemRights, $type

$fileSystemAccessRule = New-Object -TypeName


System.Security.AccessControl.FileSystemAccessRule -ArgumentList
$fileSystemAccessRuleArgumentList
# Apply new rule

$NewAcl.SetAccessRule($fileSystemAccessRule)

Set-Acl -Path "C:\Pets\Dog.txt" -AclObject $NewAcl

This command will grant the BUILTIN\Administrators group Full control of the Dog.txt
file.

The first command uses the Get-Acl cmdlet to get the security descriptor of the Dog.txt
file.

Next variables are created to grant the BUILTIN\Administrators group full control of the
Dog.txt
file. The $identity variable set to the name of a
user account. The
$fileSystemRights variable set to FullControl, and can be any one of the

FileSystemRights values that specifies


the type of operation associated with the access
rule. The $type variable set to "Allow" to
specifies whether to allow or deny the
operation. The $fileSystemAccessRuleArgumentList variable
is an argument list is to be
passed when making the new FileSystemAccessRule object. Then a new
FileSystemAccessRule object is created, and the FileSystemAccessRule object is passed
to the
SetAccessRule() method, adds the new access rule.

The last command uses Set-Acl to apply the security descriptor of to Dog.txt. When the
command
completes, the BUILTIN\Administrators group will have full control of the
Dog.txt.

Parameters
-AclObject

Specifies an ACL with the desired property values. Set-Acl changes the ACL of item
specified by
the Path or InputObject 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.

Type: Object

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-CentralAccessPolicy

Establishes or changes the central access policy of the item.


Enter the CAP ID or
friendly name of a central access policy on the computer.

Beginning in Windows Server 2012, administrators can use Active Directory and
Group Policy to set central access policies for users and groups.
For more
information, see Dynamic Access Control: Scenario Overview.

This parameter was introduced in Windows PowerShell 3.0.

Type: String

Position: 2

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-ClearCentralAccessPolicy

Removes the central access policy from the specified item.

Beginning in Windows Server 2012, administrators can use Active Directory and
Group Policy to set
central access policies for users and groups. For more
information, see
Dynamic Access Control: Scenario Overview.

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named
Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Exclude

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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Filter

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 PowerShell
filter the objects after they are retrieved.

Type: String

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Include

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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-InputObject

Changes the security descriptor of the specified object. Enter a variable that contains
the object
or a command that gets the object.

You cannot pipe the object to be changed to Set-Acl . Instead, use the InputObject
parameter
explicitly in the command.

This parameter was introduced in Windows PowerShell 3.0.

Type: PSObject

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-LiteralPath

Changes the security descriptor of the specified item. 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 PowerShell not to interpret any characters as escape
sequences.

This parameter was introduced in Windows PowerShell 3.0.

Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Passthru

Returns an object that represents the security descriptor that was changed. By
default, this cmdlet
does not generate any output.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Path

Changes the security descriptor of the specified item. Enter the path to an item, 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 or


SecurityDescriptor parameters or by passing a security 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.

Type: String[]

Position: 0

Default value: None


Accept pipeline input: True

Accept wildcard characters: True

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

Type: SwitchParameter

Aliases: usetx

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
ObjectSecurity

You can pipe an ACL object to this cmdlet.

CommonSecurityDescriptor

You can pipe a security descriptor to this cmdlet.


Outputs
None

By default, this cmdlet returns no output.

FileSecurity

When you use the PassThru parameter, this cmdlet returns a security object. The type of
the
security object depends on the type of the item.

Notes
The Set-Acl cmdlet is supported by the PowerShell file system and registry providers.
As such, you
can use it to change the security descriptors of files, directories, and
registry keys.

Related Links
Get-Acl
FileSystemAccessRule
ObjectSecurity.SetAccessRuleProtection
FileSystemRights
Set-AuthenticodeSignature
Reference
Module: Microsoft.PowerShell.Security

Adds an Authenticode signature to a PowerShell


script or other file.

Syntax
PowerShell

Set-AuthenticodeSignature

[-Certificate] <X509Certificate2>

[-IncludeChain <String>]

[-TimestampServer <String>]

[-HashAlgorithm <String>]

[-Force]

[-FilePath] <String[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Set-AuthenticodeSignature

[-Certificate] <X509Certificate2>

[-IncludeChain <String>]

[-TimestampServer <String>]

[-HashAlgorithm <String>]

[-Force]

-LiteralPath <String[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Set-AuthenticodeSignature

[-Certificate] <X509Certificate2>

[-IncludeChain <String>]

[-TimestampServer <String>]

[-HashAlgorithm <String>]

[-Force]

-SourcePathOrExtension <String[]>

-Content <Byte[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Set-AuthenticodeSignature cmdlet adds an Authenticode signature to any file that
supports
Subject Interface Package (SIP).

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

Examples

Example 1 - Sign a script using a certificate from the local


certificate store
These commands retrieve a code-signing certificate from the PowerShell certificate
provider and use
it to sign a PowerShell script.

PowerShell

$cert=Get-ChildItem -Path Cert:\CurrentUser\My -CodeSigningCert

$signingParameters = @{

FilePath = 'PsTestInternet2.ps1'

Certificate = $cert

HashAlgorithm = 'SHA256'

Set-AuthenticodeSignature @signingParameters

The first command uses the Get-ChildItem cmdlet and the 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 defines the $signingParameters variable as a HashTable with the
parameters
for the Set-AuthenticodeSignature cmdlet to sign the PSTestInternet2.ps1
script. It uses the
FilePath parameter to specify the name of the script, the Certificate
parameter to specify
that the certificate is stored in the $cert variable, and the
HashAlgorithm parameter to set
the hashing algorithm to SHA256.

The third command signs the script by splatting the parameters defined in
$signingParameters .

7 Note

Using the CodeSigningCert parameter with Get-ChildItem only returns certificates


that have
code-signing authority and contain a private key. If there is no private
key, the certificates
cannot be used for signing.

Example 2 - Sign a script using a certificate from a PFX


file
These commands use the Get-PfxCertificate cmdlet to load a code signing certificate.
Then, use it
to sign a PowerShell script.

PowerShell

$cert = Get-PfxCertificate -FilePath C:\Test\Mysign.pfx

$signingParameters = @{

FilePath = 'ServerProps.ps1'

Certificate = $cert

HashAlgorithm = 'SHA256'

Set-AuthenticodeSignature @signingParameters

The first command uses the Get-PfxCertificate cmdlet to load the C:\Test\MySign.pfx
certificate
into the $cert variable.

The second command defines the $signingParameters variable as a HashTable with the
parameters
for the Set-AuthenticodeSignature cmdlet to sign the ServerProps.ps1
script. It uses the
FilePath parameter to specify the name of the script, the Certificate
parameter to specify
that the certificate is stored in the $cert variable, and the
HashAlgorithm parameter to set
the hashing algorithm to SHA256.

The third command signs the script by splatting the parameters defined in
$signingParameters .

If the certificate file is password protected, PowerShell prompts you for the password.
Example 3 - Add a signature that includes the root
authority
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.

PowerShell

$signingParameters = @{

FilePath = 'C:\scripts\Remodel.ps1'

Certificate = $cert

HashAlgorithm = 'SHA256'

IncludeChain = 'All'

TimestampServer = 'http://timestamp.fabrikam.com/scripts/timstamper.dll'

Set-AuthenticodeSignature @signingParameters

The first command defines the $signingParameters variable as a HashTable with the
parameters
for the Set-AuthenticodeSignature cmdlet to sign the script. It uses the
FilePath parameter to
specify the path to the script, the Certificate parameter to specify
that the certificate is
stored in the $cert variable, and the HashAlgorithm parameter to
set the hashing algorithm to
SHA256. 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.

The second command signs the script by splatting the parameters defined in
$signingParameters .

Parameters
-Certificate

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.

Type: X509Certificate2

Position: 1
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Content

This parameter appears in the syntax listing because it is defined in the base class
that
Set-AuthenticodeSignature is derived from. However, support for this parameter
is not implemented
in Set-AuthenticodeSignature .

Type: Byte[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-FilePath

Specifies the path to a file that is being signed.

Type: String[]

Position: 1

Default value: None

Accept pipeline input: True


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.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-HashAlgorithm

Specifies the hashing algorithm that Windows uses to compute the digital signature
for the file.

The default is SHA1. Files that are signed with a different hashing algorithm might
not be
recognized on other systems. Which algorithms are supported depends on
the version of the operating
system.

For a list of possible values, see HashAlgorithmName Struct.

Type: String

Position: Named

Default value: Null

Accept pipeline input: False

Accept wildcard characters: False

-IncludeChain

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.

Type: String

Position: Named

Default value: NotRoot

Accept pipeline input: False

Accept wildcard characters: False

-LiteralPath

Specifies the path to a file that is being signed. Unlike FilePath, 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 PowerShell not to interpret any characters as escape
sequences.

Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-SourcePathOrExtension

This parameter appears in the syntax listing because it is defined in the base class
that
Set-AuthenticodeSignature is derived from. However, support for this parameter
is not implemented
in Set-AuthenticodeSignature .

Type: String[]

Position: Named

Default value: None

Accept pipeline input: True


Accept wildcard characters: False

-TimestampServer

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.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a string that contains the file path to this cmdlet.

Outputs
Signature
This cmdlet returns a Signature object representing the value it set.

Related Links
Get-AuthenticodeSignature
Get-ExecutionPolicy
Get-PfxCertificate
Set-ExecutionPolicy
about_Execution_Policies
about_Signing
Set-ExecutionPolicy
Reference
Module: Microsoft.PowerShell.Security

Sets the PowerShell execution policies for Windows computers.

Syntax
PowerShell

Set-ExecutionPolicy

[-ExecutionPolicy] <ExecutionPolicy>

[[-Scope] <ExecutionPolicyScope>]

[-Force]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Set-ExecutionPolicy cmdlet changes PowerShell execution policies for Windows
computers. For
more information, see about_Execution_Policies.

An execution policy is part of the PowerShell security strategy. Execution policies


determine
whether you can load configuration files, such as your PowerShell profile, or
run scripts. And,
whether scripts must be digitally signed before they are run.

The Set-ExecutionPolicy cmdlet's default scope is LocalMachine, which affects


everyone who
uses the computer. To change the execution policy for LocalMachine,
start PowerShell with Run
as Administrator.

To display the execution policies for each scope in the order of precedence, use
Get-
ExecutionPolicy -List . To see the effective execution policy for your PowerShell session

use
Get-ExecutionPolicy with no parameters.

Examples

Example 1: Set an execution policy


This example shows how to set the execution policy for the local computer.
PowerShell

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope LocalMachine

Get-ExecutionPolicy -List

Scope ExecutionPolicy

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

MachinePolicy Undefined

UserPolicy Undefined

Process Undefined

CurrentUser RemoteSigned

LocalMachine RemoteSigned

The Set-ExecutionPolicy cmdlet uses the ExecutionPolicy parameter to specify the


RemoteSigned policy. The Scope parameter specifies the default scope value,
LocalMachine. To view the execution policy settings, use the Get-ExecutionPolicy
cmdlet with
the List parameter.

Example 2: Set an execution policy that conflicts with a


Group Policy
This command attempts to set the LocalMachine scope's execution policy to Restricted.
LocalMachine is more restrictive, but isn't the effective policy because it conflicts with a
Group Policy. The Restricted policy is written to the registry hive
HKEY_LOCAL_MACHINE.

PowerShell

PS> Set-ExecutionPolicy -ExecutionPolicy Restricted -Scope LocalMachine

Set-ExecutionPolicy : 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

PS> Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds

Hive: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds

Name Property

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

Microsoft.PowerShell Path :
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

ExecutionPolicy : Restricted

ScriptedDiagnostics ExecutionPolicy : Unrestricted


The Set-ExecutionPolicy cmdlet uses the ExecutionPolicy parameter to specify the
Restricted policy. The Scope parameter specifies the default scope value, LocalMachine.
The Get-ChildItem cmdlet uses the Path parameter with the HKLM provider to specify
registry location.

Example 3: Apply the execution policy from a remote


computer to a local computer
This command gets the execution policy object from a remote computer and sets the
policy on the
local computer. Get-ExecutionPolicy sends a
Microsoft.PowerShell.ExecutionPolicy object down
the pipeline. Set-ExecutionPolicy
accepts pipeline input and doesn't require the
ExecutionPolicy parameter.

PowerShell

PS> Invoke-Command -ComputerName Server01 -ScriptBlock { Get-ExecutionPolicy


} | Set-ExecutionPolicy

The Invoke-Command cmdlet is executed at the local computer and sends the ScriptBlock
to the
remote computer. The ComputerName parameter specifies the remote
computer, Server01. The
ScriptBlock parameter runs Get-ExecutionPolicy on the
remote computer. The
Get-ExecutionPolicy object is sent down the pipeline to the Set-
ExecutionPolicy .
Set-ExecutionPolicy applies the execution policy to the local
computer's default scope,
LocalMachine.

Example 4: Set the scope for an execution policy


This example shows how to set an execution policy for a specified scope, CurrentUser.
The
CurrentUser scope only affects the user who sets this scope.

PowerShell

Set-ExecutionPolicy -ExecutionPolicy AllSigned -Scope CurrentUser

Get-ExecutionPolicy -List

Scope ExecutionPolicy

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

MachinePolicy Undefined

UserPolicy Undefined

Process Undefined

CurrentUser AllSigned

LocalMachine RemoteSigned
Set-ExecutionPolicy uses the ExecutionPolicy parameter to specify the AllSigned

policy.
The Scope parameter specifies the CurrentUser. To view the execution policy
settings, use
the Get-ExecutionPolicy cmdlet with the List parameter.

The effective execution policy for the user becomes AllSigned.

Example 5: Remove the execution policy for the current


user
This example shows how use the Undefined execution policy to remove an execution
policy for a
specified scope.

PowerShell

Set-ExecutionPolicy -ExecutionPolicy Undefined -Scope CurrentUser

Get-ExecutionPolicy -List

Scope ExecutionPolicy

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

MachinePolicy Undefined

UserPolicy Undefined

Process Undefined

CurrentUser Undefined

LocalMachine RemoteSigned

Set-ExecutionPolicy uses the ExecutionPolicy parameter to specify the Undefined

policy.
The Scope parameter specifies the CurrentUser. To view the execution policy
settings, use
the Get-ExecutionPolicy cmdlet with the List parameter.

Example 6: Set the execution policy for the current


PowerShell session
The Process scope only affects the current PowerShell session. The execution policy is
saved in
the environment variable $env:PSExecutionPolicyPreference and is deleted
when the session is
closed.

PowerShell

Set-ExecutionPolicy -ExecutionPolicy AllSigned -Scope Process

Scope ExecutionPolicy

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

MachinePolicy Undefined

UserPolicy Undefined

Process AllSigned

CurrentUser RemoteSigned

LocalMachine RemoteSigned

The Set-ExecutionPolicy uses the ExecutionPolicy parameter to specify the AllSigned


policy. The Scope parameter specifies the value Process. To view the execution policy
settings, use the Get-ExecutionPolicy cmdlet with the List parameter.

Example 7: Unblock a script to run it without changing


the execution policy
This example shows how the RemoteSigned execution policy prevents you from running
unsigned
scripts.

A best practice is to read the script's code and verify it's safe before using the
Unblock-
File cmdlet. The Unblock-File cmdlet unblocks scripts so they can run, but doesn't

change the execution policy.

PowerShell

PS> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope LocalMachine

PS> Get-ExecutionPolicy

RemoteSigned

PS> .\Start-ActivityTracker.ps1

.\Start-ActivityTracker.ps1 : File .\Start-ActivityTracker.ps1 cannot be


loaded.

The file .\Start-ActivityTracker.ps1 is not digitally signed.

The script will not execute on the system.

For more information, see about_Execution_Policies at


https://go.microsoft.com/fwlink/?LinkID=135170.

At line:1 char:1

+ .\Start-ActivityTracker.ps1

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : NotSpecified: (:) [], PSSecurityException

+ FullyQualifiedErrorId : UnauthorizedAccess

PS> Unblock-File -Path .\Start-ActivityTracker.ps1

PS> Get-ExecutionPolicy

RemoteSigned

PS> .\Start-ActivityTracker.ps1

Task 1:
The Set-ExecutionPolicy uses the ExecutionPolicy parameter to specify the
RemoteSigned
policy. The policy is set for the default scope, LocalMachine.

The Get-ExecutionPolicy cmdlet shows that RemoteSigned is the effective execution


policy for
the current PowerShell session.

The Start-ActivityTracker.ps1 script is executed from the current directory. The script is
blocked by RemoteSigned because the script isn't digitally signed.

For this example, the script's code was reviewed and verified as safe to run. The
Unblock-File
cmdlet uses the Path parameter to unblock the script.

To verify that Unblock-File didn't change the execution policy, Get-ExecutionPolicy


displays the
effective execution policy, RemoteSigned.

The script, Start-ActivityTracker.ps1 is executed from the current directory. The script
begins
to run because it was unblocked by the Unblock-File cmdlet.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-ExecutionPolicy

Specifies the execution policy. If there are no Group Policies and each scope's
execution policy is
set to Undefined, then Restricted becomes the effective policy for
all users.

The acceptable execution policy values are as follows:


AllSigned. Requires that all scripts and configuration files are signed by a
trusted
publisher, including scripts written on the local computer.
Bypass. Nothing is blocked and there are no warnings or prompts.
Default. Sets the default execution policy. Restricted for Windows clients or
RemoteSigned for Windows servers.
RemoteSigned. Requires that all scripts and configuration files downloaded
from the Internet
are signed by a trusted publisher. The default execution
policy for Windows server computers.
Restricted. Doesn't load configuration files or run scripts. The default execution
policy for
Windows client computers.
Undefined. No execution policy is set for the scope. Removes an assigned
execution policy from
a scope that is not set by a Group Policy. If the execution
policy in all scopes is Undefined,
the effective execution policy is Restricted.
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.

Type: ExecutionPolicy

Accepted values: AllSigned, Bypass, Default, RemoteSigned, Restricted,


Undefined, Unrestricted

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Force

Suppresses all the confirmation prompts. Use caution with this parameter to avoid
unexpected
results.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-Scope

Specifies the scope that is affected by an execution policy. The default scope is
LocalMachine.

The effective execution policy is determined by the order of precedence as follows:

MachinePolicy. Set by a Group Policy for all users of the computer.


UserPolicy. Set by a Group Policy for the current user of the computer.
Process. Affects only the current PowerShell session.
CurrentUser. Affects only the current user.
LocalMachine. Default scope that affects all users of the computer.

The Process scope only affects the current PowerShell session. The execution policy
is saved in
the environment variable $env:PSExecutionPolicyPreference , rather than
the registry. When the
PowerShell session is closed, the variable and value are
deleted.

Execution policies for the CurrentUser scope are written to the registry hive
HKEY_LOCAL_USER.

Execution policies for the LocalMachine scope are written to the registry hive
HKEY_LOCAL_MACHINE.

Type: ExecutionPolicyScope

Accepted values: CurrentUser, LocalMachine, MachinePolicy, Process, UserPolicy

Position: 1

Default value: LocalMachine

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False


Accept pipeline input: False

Accept wildcard characters: False

Inputs
ExecutionPolicy

You can pipe an execution policy object to this cmdlet.

String

You can pipe a string that contains the name of an execution policy to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
Set-ExecutionPolicy doesn't change the MachinePolicy and UserPolicy scopes because
they
are set by Group Policies.

Set-ExecutionPolicy doesn't override a Group Policy, even if the user preference is


more
restrictive than the policy.

If the Group Policy Turn on Script Execution is enabled for the computer or user, the
user
preference is saved, but it is not effective. PowerShell displays a message that
explains the
conflict.

Related Links
about_Execution_Policies
about_Group_Policy_Settings
about_Providers
Get-AuthenticodeSignature
Get-ChildItem
Get-ExecutionPolicy
Invoke-Command
Set-AuthenticodeSignature
Unblock-File
Test-FileCatalog
Reference
Module: Microsoft.PowerShell.Security

Test-FileCatalog validates whether the hashes contained in a catalog file (.cat) matches

the
hashes of the actual files in order to validate their authenticity.

This cmdlet is only supported on Windows.

Syntax
PowerShell

Test-FileCatalog

[-Detailed]

[-FilesToSkip <String[]>]

[-CatalogFilePath] <String>

[[-Path] <String[]>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
Test-FileCatalog validates the authenticity of files by comparing the file hashes of a

catalog
file (.cat) with the hashes of actual files on disk. If it detects any mismatches, it
returns the
status as ValidationFailed. Users can retrieve all this information by using the
-Detailed
parameter. It also displays signing status of catalog in Signature property
which is equivalent to
calling Get-AuthenticodeSignature cmdlet on the catalog file.
Users can also skip any file during
validation by using the -FilesToSkip parameter.

This cmdlet is only supported on Windows.

Examples

Example 1: Create and validate a file catalog


PowerShell
New-FileCatalog -Path $PSHOME\Modules\Microsoft.PowerShell.Utility -
CatalogFilePath \temp\Microsoft.PowerShell.Utility.cat -CatalogVersion 2.0

Test-FileCatalog -CatalogFilePath \temp\Microsoft.PowerShell.Utility.cat -


Path "$PSHome\Modules\Microsoft.PowerShell.Utility\"

Valid

Example 2: Validate a file catalog with detailed output


PowerShell

Test-FileCatalog -Detailed -CatalogFilePath


\temp\Microsoft.PowerShell.Utility.cat -Path
"$PSHome\Modules\Microsoft.PowerShell.Utility\"

Status : Valid

HashAlgorithm : SHA256

CatalogItems : {[Microsoft.PowerShell.Utility.psd1,

A7028BD54018AE519381CDF5BF91F3B0417BD9345478086089ACBFAD05C899FC],
[Microsoft.PowerShell.Utility.psm1,

1127E8151FB86BCB683F932E8F6538552F7195816ED351A28AE07A753B8F20DE]}
PathItems : {[Microsoft.PowerShell.Utility.psd1,

A7028BD54018AE519381CDF5BF91F3B0417BD9345478086089ACBFAD05C899FC],
[Microsoft.PowerShell.Utility.psm1,

1127E8151FB86BCB683F932E8F6538552F7195816ED351A28AE07A753B8F20DE]}
Signature : System.Management.Automation.Signature

Parameters
-CatalogFilePath

A path to a catalog file (.cat) that contains the hashes to be used for validation.

Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False


-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Detailed

Returns more information a more detailed CatalogInformation object that contains


the files tested,
their expected/actual hashes, and an Authenticode signature of the
catalog file if it's signed.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-FilesToSkip

An array of paths that should not be tested as part of the validation.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Path

A folder or array of files that should be validated against the catalog file.
Type: String[]

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
DirectoryInfo

You can pipe a DirectoryInfo object representing the path to the files that need to be
validated.

String

You can pipe a string representing the path to the files that need to be validated.

Outputs
CatalogValidationStatus

By default, this cmdlet returns a CatalogValidationStatus object with a value of either


Valid
or ValidationFailed .

CatalogInformation
When you use the Detailed parameter, the cmdlet returns a CatalogInformation object
for
each file, which can be used to analyze specific files that may or may not have
passed validation,
which hashes were expected vs. found, and the algorithm used in the
catalog.

Related Links
New-FileCatalog
PowerShellGet
Unprotect-CmsMessage
Reference
Module: Microsoft.PowerShell.Security

Decrypts content that has been encrypted by using the Cryptographic Message Syntax
format.

Syntax
PowerShell

Unprotect-CmsMessage

[-EventLogRecord] <PSObject>

[-IncludeContext]

[[-To] <CmsMessageRecipient[]>]

[<CommonParameters>]

PowerShell

Unprotect-CmsMessage

[-Content] <String>

[-IncludeContext]

[[-To] <CmsMessageRecipient[]>]

[<CommonParameters>]

PowerShell

Unprotect-CmsMessage

[-Path] <String>

[-IncludeContext]

[[-To] <CmsMessageRecipient[]>]

[<CommonParameters>]

PowerShell

Unprotect-CmsMessage

[-LiteralPath] <String>

[-IncludeContext]

[[-To] <CmsMessageRecipient[]>]

[<CommonParameters>]

Description
The Unprotect-CmsMessage cmdlet decrypts content that has been encrypted by using
the
Cryptographic Message Syntax (CMS) format.

The CMS cmdlets support encryption and decryption of content using the IETF standard
format for
cryptographically protecting messages, as documented by
RFC5652 .

The CMS encryption standard uses public key cryptography, where the keys used to
encrypt content
(the public key) and the keys used to decrypt content (the private key)
are separate. Your public
key can be shared widely, and is not sensitive data. If any
content is encrypted with this public
key, only your private key can decrypt it. For more
information, see
Public-key cryptography .

Unprotect-CmsMessage decrypts content that has been encrypted in CMS format. You can

run this
cmdlet to decrypt content that you have encrypted by running the Protect-
CmsMessage cmdlet. You
can specify content that you want to decrypt as a string, by the
encryption event log record ID
number, or by path to the encrypted content. The
Unprotect-CmsMessage cmdlet returns the decrypted
content.

Examples

Example 1: Decrypt a message


In the following example, you decrypt content that is located at the literal path
C:\Users\Test\Documents\PowerShell . For the value of the required To parameter, this

example
uses the thumbprint of the certificate that was used to perform the encryption.
The decrypted
message, "Try the new Break All command," is the result.

PowerShell

$parameters = @{

LiteralPath = "C:\Users\Test\Documents\PowerShell\Future_Plans.txt"

To = '0f 8j b1 ab e0 ce 35 1d 67 d2 f2 6f a2 d2 00 cl 22 z9 m9 85'

Unprotect-CmsMessage -LiteralPath @parameters

Try the new Break All command

Parameters
-Content

Specifies an encrypted string, or a variable containing an encrypted string.


Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-EventLogRecord

Specifies an event log record ID that represents a CMS encryption operation.

Type: PSObject

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-IncludeContext

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-LiteralPath

Specifies the path to encrypted content that you want to decrypt. Unlike Path, the
value of
LiteralPath is used exactly as it is typed. No characters are interpreted as
wildcard
characters. If the path includes escape characters, enclose it in single
quotation marks. Single
quotation marks tell PowerShell not to interpret any
characters as escape sequences.

Type: String

Position: 0
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Path

Specifies the path to encrypted content that you want to decrypt.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-To

Specifies one or more CMS message recipients, identified in any of the following
formats:

An actual certificate (as retrieved from the certificate provider).


Path to the a file containing the certificate.
Path to a directory containing the certificate.
Thumbprint of the certificate (used to look in the certificate store).
Subject name of the certificate (used to look in the certificate store).

Type: CmsMessageRecipient[]

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
EventLogRecord

String
You can pipe an object containing encrypted content to this cmdlet.

Outputs
String

This cmdlet returns the unencrypted message.

Related Links
about_Providers
Get-CmsMessage
Protect-CmsMessage
Microsoft.PowerShell.Utility
Reference

This section contains the help topics for the cmdlets that are installed with the
Microsoft.PowerShell.Utility module. This module contains cmdlets that manage the
basic features of
PowerShell.

Microsoft.PowerShell.Utility
Add-Member Adds custom properties and methods to an instance of a
PowerShell object.

Add-Type Adds a Microsoft .NET class to a PowerShell session.

Clear-Variable Deletes the value of a variable.

Compare-Object Compares two sets of objects.

Convert-String Formats a string to match examples.

ConvertFrom-Csv Converts object properties in character-separated value (CSV)


format into CSV versions of the
original objects.

ConvertFrom-Json Converts a JSON-formatted string to a custom object.

ConvertFrom-SddlString Converts a SDDL string to a custom object.

ConvertFrom-String Extracts and parses structured properties from string content.

ConvertFrom-StringData Converts a string containing one or more key and value pairs to
a hash table.

ConvertTo-Csv Converts .NET objects into a series of character-separated value


(CSV) strings.

ConvertTo-Html Converts .NET objects into HTML that can be displayed in a Web
browser.

ConvertTo-Json Converts an object to a JSON-formatted string.

ConvertTo-Xml Creates an XML-based representation of an object.

Debug-Runspace Starts an interactive debugging session with a runspace.

Disable-PSBreakpoint Disables the breakpoints in the current console.

Disable-RunspaceDebug Disables debugging on one or more runspaces, and releases any


pending debugger stop.
Enable-PSBreakpoint Enables the breakpoints in the current console.

Enable-RunspaceDebug Enables debugging on runspaces where any breakpoint is


preserved until a debugger is attached.

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-Csv Converts objects into a series of character-separated value (CSV)


strings and saves the strings to a
file.

Export-FormatData Saves formatting data from the current session in a formatting


file.

Export-PSSession Exports commands from another session and saves them in a


PowerShell module.

Format-Custom Uses a customized view to format the output.

Format-Hex Displays a file or other input as hexadecimal.

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-Alias Gets the aliases for the current session.

Get-Culture Gets the current culture set in the operating system.

Get-Date Gets the current date and time.

Get-Event Gets the events in the event queue.

Get-EventSubscriber Gets the event subscribers in the current session.

Get-FileHash Computes the hash value for a file by using a specified hash
algorithm.

Get-FormatData Gets the formatting data in the current session.

Get-Host Gets an object that represents the current host program.

Get-Member Gets the properties and methods of objects.

Get-PSBreakpoint Gets the breakpoints that are set in the current session.

Get-PSCallStack Displays the current call stack.


Get-Random Gets a random number, or selects objects randomly from a
collection.

Get-Runspace Gets active runspaces within a PowerShell host process.

Get-RunspaceDebug Shows runspace debugging options.

Get-TraceSource Gets PowerShell components that are instrumented for tracing.

Get-TypeData Gets the extended type data in the current session.

Get-UICulture Gets the current UI culture settings in the operating system.

Get-Unique Returns unique items from a sorted list.

Get-Variable Gets the variables in the current console.

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 in


PowerShell.

Import-Csv Creates table-like custom objects from the items in a character-


separated value (CSV) file.

Import-LocalizedData Imports language-specific data into scripts and functions based


on the UI culture that's selected
for the operating system.

Import-PowerShellDataFile Imports values from a .PSD1 file without invoking its contents.

Import-PSSession Imports commands from another session into the current


session.

Invoke-Expression Runs commands or expressions on the local computer.

Invoke-RestMethod Sends an HTTP or HTTPS request to a RESTful web service.

Invoke-WebRequest Gets content from a web page on the internet.

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 files of text.

New-Alias Creates a new alias.

New-Event Creates a new event.

New-Guid Creates a GUID.

New-Object Creates an instance of a Microsoft .NET Framework or COM


object.

New-TemporaryFile Creates a temporary file.

New-TimeSpan Creates a TimeSpan object.

New-Variable Creates a new variable.

Out-File Sends output to a file.

Out-GridView Sends output to an interactive table in a separate window.

Out-Printer Sends output to a printer.

Out-String Outputs input objects as a string.

Read-Host Reads a line of input from the console.

Register-EngineEvent Subscribes to events that are generated by the PowerShell


engine and by the New-Event cmdlet.

Register-ObjectEvent Subscribes to the events that are generated by a Microsoft .NET


Framework object.

Remove-Event Deletes events from the event queue.

Remove-PSBreakpoint Deletes breakpoints from the current console.

Remove-TypeData Deletes extended types from the current session.

Remove-Variable Deletes a variable and its value.

Select-Object Selects objects or object properties.

Select-String Finds text in strings and files.

Select-Xml Finds text in an XML string or document.

Send-MailMessage Sends an email message.

Set-Alias Creates or changes an alias for a cmdlet or other command in


the current PowerShell session.

Set-Date Changes the system time on the computer to a time that you
specify.

Set-PSBreakpoint Sets a breakpoint on a line, command, or variable.

Set-TraceSource Configures, starts, and stops a trace of PowerShell components.

Set-Variable Sets the value of a variable. Creates the variable if one with the
requested name does not exist.

Show-Command Displays PowerShell command information in a graphical


window.

Sort-Object Sorts objects by property values.

Start-Sleep Suspends the activity in a script or session for the specified


period of time.

Tee-Object Saves command output in a file or variable and also sends it


down the pipeline.

Trace-Command Configures and starts a trace of the specified expression or


command.

Unblock-File Unblocks files that were downloaded from the internet.

Unregister-Event Cancels an event subscription.

Update-FormatData Updates the formatting data in the current session.

Update-List Adds items to and removes items from a property value that
contains a collection of objects.

Update-TypeData Updates the extended type data in the session.

Wait-Debugger Stops a script in the debugger before running the next statement
in the script.

Wait-Event Waits until a particular event is raised before continuing to run.

Write-Debug Writes a debug message to the console.

Write-Error Writes an object to the error stream.

Write-Host Writes customized output to a host.

Write-Information Specifies how PowerShell handles information stream data for a


command.

Write-Output Writes the specified objects to the pipeline. If Write-Output is


the last command in the pipeline,
the objects are displayed in
the console.

Write-Progress Displays a progress bar within a PowerShell command window.

Write-Verbose Writes text to the verbose message stream.

Write-Warning Writes a warning message.


Add-Member
Reference
Module: Microsoft.PowerShell.Utility

Adds custom properties and methods to an instance of a PowerShell object.

Syntax
PowerShell

Add-Member

-InputObject <PSObject>

-TypeName <String>

[-PassThru]

[<CommonParameters>]

PowerShell

Add-Member

-InputObject <PSObject>

[-TypeName <String>]

[-Force]

[-PassThru]

[-NotePropertyMembers] <IDictionary>

[<CommonParameters>]

PowerShell

Add-Member

-InputObject <PSObject>

[-TypeName <String>]

[-Force]

[-PassThru]

[-NotePropertyName] <String>

[-NotePropertyValue] <Object>

[<CommonParameters>]

PowerShell

Add-Member

-InputObject <PSObject>

[-MemberType] <PSMemberTypes>

[-Name] <String>

[[-Value] <Object>]

[[-SecondValue] <Object>]

[-TypeName <String>]

[-Force]

[-PassThru]

[<CommonParameters>]

Description
The Add-Member cmdlet lets you add members (properties and methods) to an instance
of a PowerShell
object. For instance, you can add a NoteProperty member that contains
a description of the
object or a ScriptMethod member that runs a script to change the
object.

To use Add-Member , pipe the object to Add-Member , or use the InputObject parameter to
specify the object.

The MemberType parameter indicates the type of member that you want to add. The
Name
parameter assigns a name to the new member, and the Value parameter sets the
value of the
member.

The properties and methods that you add are added only to the particular instance of
the object that
you specify. Add-Member doesn't change the object type. To create a new
object type, use the
Add-Type cmdlet.

You can also use the Export-Clixml cmdlet to save the instance of the object, including
the
additional members, in a file. Then you can use the Import-Clixml cmdlet to re-
create the instance
of the object from the information that's stored in the exported file.

Beginning in Windows PowerShell 3.0, Add-Member has new features that make it easier
to add note
properties to objects. You can use the NotePropertyName and
NotePropertyValue parameters to
define a note property or use the
NotePropertyMembers parameter, which takes a hash table of
note property names
and values.

Also, beginning in Windows PowerShell 3.0, the PassThru parameter, which generates an
output
object, is needed less frequently. Add-Member now adds the new members
directly to the input
object of more types. For more information, see the PassThru
parameter description.

Examples

Example 1: Add a note property to a PSObject


The following example adds a Status note property with a value of "Done" to the
FileInfo
object that represents the Test.txt file.

The first command uses the Get-ChildItem cmdlet to get a FileInfo object representing
the Test.txt file. It saves it in the $a variable.

The second command adds the note property to the object in $a .

The third command uses dot notation to get the value of the Status property of the
object in
$a . As the output shows, the value is Done .

PowerShell

$A = Get-ChildItem c:\ps-test\test.txt

$A | Add-Member -NotePropertyName Status -NotePropertyValue Done

$A.Status

Done

Example 2: Add an alias property to a PSObject


The following example adds a Size alias property to the object that represents the
Test.txt
file. The new property is an alias for the Length property.

The first command uses the Get-ChildItem cmdlet to get the Test.txt FileInfo object.

The second command adds the Size alias property. The third command uses dot
notation to get the
value of the new Size property.

PowerShell

$A = Get-ChildItem C:\Temp\test.txt

$A | Add-Member -MemberType AliasProperty -Name Size -Value Length

$A.Size

2394

Example 3: Add a StringUse note property to a string


This example adds the StringUse note property to a string. Because Add-Member can't
add types
to String input objects, you can specify the PassThru parameter to generate
an output
object. The last command in the example displays the new property.
This example uses the NotePropertyMembers parameter. The value of the
NotePropertyMembers
parameter is a hash table. The key is the note property name,
StringUse, and the value is the
note property value, Display.

PowerShell

$A = "A string"

$A = $A | Add-Member -NotePropertyMembers @{StringUse="Display"} -PassThru

$A.StringUse

Display

Example 4: Add a script method to a FileInfo object


This example adds the SizeInMB script method to a FileInfo object that calculates the
file
size to the nearest MegaByte. The second command creates a ScriptBlock that uses
the Round
static method from the [math] type to round the file size to the second
decimal place.

The Value parameter also uses the $This automatic variable, which represents the
current
object. The $This variable is valid only in script blocks that define new
properties and methods.

The last command uses dot notation to call the new SizeInMB script method on the
object in the
$A variable.

PowerShell

$A = Get-ChildItem C:\Temp\test.txt

$S = {[math]::Round(($this.Length / 1MB), 2)}

$A | Add-Member -MemberType ScriptMethod -Name "SizeInMB" -Value $S

$A.SizeInMB()

0.43

Example 5: Create a custom object


This example creates an Asset custom object.

The New-Object cmdlet creates a PSObject. The example saves the PSObject in the
$Asset
variable.

The second command uses the [ordered] type accelerator to create an ordered
dictionary of names
and values. The command saves the result in the $D variable.
The third command uses the NotePropertyMembers parameter of the Add-Member
cmdlet to add the
dictionary in the $D variable to the PSObject. The TypeName
property assigns a new name,
Asset, to the PSObject.

The last command pipes the new Asset object to the Get-Member cmdlet. The output
shows that
the object has a type name of Asset and the note properties that we defined
in the ordered
dictionary.

PowerShell

$Asset = New-Object -TypeName PSObject

$d = [ordered]@{Name="Server30";System="Server Core";PSVersion="4.0"}

$Asset | Add-Member -NotePropertyMembers $d -TypeName Asset

$Asset.PSObject.Properties | Select-Object Name, Value

Name Value

---- -----

Name Server30

System Server Core

PSVersion 4.0

Example 6: Add an AliasProperty to an object


In this example we create a custom object that contains two NoteProperty members.
The type for a
NoteProperty reflects the type of the value stored in the property. In this
case, the Age
property is a string.

PowerShell

$obj = [pscustomobject]@{

Name = 'Doris'

Age = '20'

$obj | Add-Member -MemberType AliasProperty -Name 'intAge' -Value age -


SecondValue uint32

$obj | Get-Member

$obj

TypeName: System.Management.Automation.PSCustomObject

Name MemberType Definition

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

intAge AliasProperty intAge = (System.UInt32)age

Equals Method bool Equals(System.Object obj)

GetHashCode Method int GetHashCode()

GetType Method type GetType()

ToString Method string ToString()

Age NoteProperty string Age=20

Name NoteProperty string Name=Doris

Name : Doris

Age : 20

intAge : 20

$obj.Age + 1

$obj.intAge + 1

201

21

The intAge property is an AliasProperty for the Age property, but the type is
guaranteed
to be uint32.

Example 7: Add get and set methods to a custom object


This examples shows how to define Get and Set methods that access a deeply nested
property.

PowerShell

$user = [pscustomobject]@{

Name = 'User1'

Age = 29

StartDate = [datetime]'2019-05-05'

Position = [pscustomobject]@{

DepartmentName = 'IT'

Role = 'Manager'

$addMemberSplat = @{

MemberType = 'ScriptProperty'
Name = 'Title'

Value = { $this.Position.Role } # getter

SecondValue = { $this.Position.Role = $args[0] } # setter

$user | Add-Member @addMemberSplat

$user | 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()

Age NoteProperty int Age=29

Name NoteProperty string Name=User1

Position NoteProperty System.Management.Automation.PSCustomObject


Position=@{DepartmentName=IT; Role=Manager}

StartDate NoteProperty datetime StartDate=5/5/2019 12:00:00 AM

Title ScriptProperty System.Object Title {get= $this.Position.Role


;set= $this.Position.Role = $args[0] ;}

$user.Title = 'Dev Manager'

Name : User1

Age : 29

StartDate : 5/5/2019 12:00:00 AM

Position : @{DepartmentName=IT; Role=Dev Manager}

Title : Dev Manager

Notice that the Title property is a ScriptProperty that has a Get and Set method.
When
we assign a new value to the Title property, the Set method is called and changes the
value of the Role property in the Position property.

Parameters
-Force

Indicates that this cmdlet adds a new member even the object has a custom member
with the same name.
You can't use the Force parameter to replace a standard
member of a type.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

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.

Type: PSObject

Position: Named

Default value: None

Accept pipeline input: True


Accept wildcard characters: False

-MemberType

Specifies the type of the member to add. This parameter is required. The acceptable
values for this
parameter are:

AliasProperty
CodeMethod
CodeProperty
NoteProperty
ScriptMethod
ScriptProperty

For information about these values, see


PSMemberTypes Enumeration in the
PowerShell SDK.

Not all objects have every type of member. If you specify a member type that the
object doesn't
have, PowerShell returns an error.

Type: PSMemberTypes

Aliases: Type

Accepted values: AliasProperty, CodeMethod, CodeProperty, NoteProperty,


ScriptMethod, ScriptProperty

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Name

Specifies the name of the member that this cmdlet adds.

Type: String

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-NotePropertyMembers

Specifies a hashtable or ordered dictionary that contains key-value pair representing


NoteProperty names and their values. For more information about hash tables and
ordered
dictionaries in PowerShell, see
about_Hash_Tables.

This parameter was introduced in Windows PowerShell 3.0.

Type: IDictionary

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-NotePropertyName

Specifies the note property name.

Use this parameter with the NotePropertyValue parameter. This parameter is


optional.

This parameter was introduced in Windows PowerShell 3.0.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-NotePropertyValue

Specifies the note property value.

Use this parameter with the NotePropertyName parameter. This parameter is


optional.

This parameter was introduced in Windows PowerShell 3.0.

Type: Object
Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-PassThru

Returns an object representing the item with which you are working. By default, this
cmdlet doesn't
generate any output.

For most objects, Add-Member adds the new members to the input object. However,
when the input
object is a string, Add-Member can't add the member to the input
object. For these objects, use
the PassThru parameter to create an output object.

In Windows PowerShell 2.0, Add-Member added members only to the PSObject


wrapper of objects,
not to the object. Use the PassThru parameter to create an
output object for any object that has
a PSObject wrapper.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SecondValue

Specifies optional additional information about AliasProperty, ScriptProperty, or


CodeProperty members.

If used when adding an AliasProperty, this parameter must be a data type. A


conversion 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 using the corresponding AliasProperty.

For a CodeProperty, the value must be a reference to a method that implements a


Set
accessor. Use the GetMethod() method of a type reference to get a reference to a
method. The
method must take a single parameter that's a PSObject. The Get
accessor is assigned using
the Value parameter.

For a ScriptProperty, the value must be a script block that implements a Set
accessor. The
Get accessor is assigned using the Value parameter.

Type: Object

Position: 3

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-TypeName

Specifies a name for the type.

When the type is a class in the System namespace or a type that has a type
accelerator, you can
enter the short name of the type. Otherwise, the full type name
is required. This parameter is
effective only when the InputObject is a PSObject.

This parameter was introduced in Windows PowerShell 3.0.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Value

Specifies the initial value of the added member. If you add an AliasProperty,
CodeProperty,
or ScriptProperty member, you can supply additional information
using the SecondValue
parameter.

For an AliasProperty, the value must be the name of the property being
aliased.
For a CodeMethod, the value must be a reference to a method. Use the
GetMethod() method of
a type reference to get a reference to a method.
For a CodeProperty, the value must be a reference to a method that
implements a Get
accessor. Use the GetMethod() method of a type reference to
get a reference to a method.
reference. The method must take a single
parameter that's a PSObject. The Set accessor is
assigned using the
SecondValue parameter.
For a ScriptMethod, the value must be a script block.
For a ScriptProperty, the value must be a script block that implements a Get
accessor. The
Set accessor is assigned using the SecondValue parameter.

Type: Object

Position: 2

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSObject

You can pipe any object to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

Object

When you use the PassThru parameter, this cmdlet returns the newly extended object.

Notes
You can add members only to PSObject type objects. To determine whether an object is
a
PSObject object, use the -is operator. For instance, to test an object stored in the
$obj
variable, type $obj -is [psobject] .

PSObject type objects maintain their list of members in the order that the members
were added to
the object.
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, and SecondValue.

If you include the parameter names, the parameters can appear in any order.

You can use the $this automatic variable in script blocks that define the values of new
properties
and methods. The $this variable refers to the instance of the object to which
the properties and
methods are being added. For more information about the $this
variable, see
about_Automatic_Variables.

Related Links
Export-Clixml
Get-Member
Import-Clixml
New-Object
about_Automatic_Variables
System.Type.GetMethod()
Add-Type
Reference
Module: Microsoft.PowerShell.Utility

Adds a Microsoft .NET class to a PowerShell session.

Syntax
PowerShell

Add-Type

[-CodeDomProvider <CodeDomProvider>]

[-CompilerParameters <CompilerParameters>]

[-TypeDefinition] <String>

[-Language <Language>]

[-ReferencedAssemblies <String[]>]

[-OutputAssembly <String>]

[-OutputType <OutputAssemblyType>]

[-PassThru]

[-IgnoreWarnings]

[<CommonParameters>]

PowerShell

Add-Type

[-CodeDomProvider <CodeDomProvider>]

[-CompilerParameters <CompilerParameters>]

[-Name] <String>

[-MemberDefinition] <String[]>
[-Namespace <String>]

[-UsingNamespace <String[]>]

[-Language <Language>]

[-ReferencedAssemblies <String[]>]

[-OutputAssembly <String>]

[-OutputType <OutputAssemblyType>]

[-PassThru]

[-IgnoreWarnings]

[<CommonParameters>]

PowerShell

Add-Type

[-CompilerParameters <CompilerParameters>]

[-Path] <String[]>

[-ReferencedAssemblies <String[]>]

[-OutputAssembly <String>]

[-OutputType <OutputAssemblyType>]

[-PassThru]

[-IgnoreWarnings]

[<CommonParameters>]

PowerShell

Add-Type

[-CompilerParameters <CompilerParameters>]

-LiteralPath <String[]>

[-ReferencedAssemblies <String[]>]

[-OutputAssembly <String>]

[-OutputType <OutputAssemblyType>]

[-PassThru]

[-IgnoreWarnings]

[<CommonParameters>]

PowerShell

Add-Type

-AssemblyName <String[]>

[-PassThru]

[-IgnoreWarnings]

[<CommonParameters>]

Description
The Add-Type cmdlet lets you define a Microsoft .NET Framework class in your
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 PowerShell profile,
the class is available in all 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. On Windows, you can use this
feature to make Platform Invoke
(P/Invoke) calls to unmanaged functions in 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,
C# is the
default, compiler options, assembly dependencies, the class namespace, the
names of the type, and
the resulting assembly.
Examples

Example 1: Add a .NET type to a session


This example adds the BasicTest class to the session by specifying source code that is
stored in
a variable. The BasicTest class is used to add integers, create an object, and
multiply
integers.

PowerShell

$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);

"@

Add-Type -TypeDefinition $Source

[BasicTest]::Add(4, 3)

$BasicTestObject = New-Object BasicTest

$BasicTestObject.Multiply(5, 2)

The $Source variable stores the source code for the class. The type has a static method
called
Add and a non-static method called Multiply .

The Add-Type cmdlet adds the class to the session. Because it's using inline source code,
the
command uses the TypeDefinition parameter to specify the code in the $Source
variable.

The Add static method of the BasicTest class uses the double-colon characters ( :: ) to
specify a static member of the class. The integers are added and the sum is displayed.

The New-Object cmdlet instantiates an instance of the BasicTest class. It saves the new
object
in the $BasicTestObject variable.

$BasicTestObject uses the Multiply method. The integers are multiplied and the

product is
displayed.
Example 2: Examine an added type
This example uses the Get-Member cmdlet to examine the objects that the Add-Type and
New-Object cmdlets created in Example 1.

PowerShell

[BasicTest] | Get-Member

TypeName: System.RuntimeType

Name MemberType Definition

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

AsType Method type AsType()

Clone Method System.Object Clone(), System.Object


ICloneable.Clone()

Equals Method bool Equals(System.Object obj), bool


Equals(type o)

FindInterfaces Method type[]


FindInterfaces(System.Reflection.TypeFilter filter...

...

[BasicTest] | Get-Member -Static

TypeName: BasicTest

Name MemberType Definition

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

Add Method static int Add(int a, int b)

Equals Method static bool Equals(System.Object objA,


System.Object objB)

new Method BasicTest new()

ReferenceEquals Method static bool ReferenceEquals(System.Object objA,


System.Object objB)

$BasicTestObject | Get-Member

TypeName: BasicTest

Name MemberType Definition


---- ---------- ----------
Equals Method bool Equals(System.Object obj)

GetHashCode Method int GetHashCode()

GetType Method type GetType()

Multiply Method int Multiply(int a, int b)

ToString Method string ToString()

The Get-Member cmdlet gets the type and members of the BasicTest class that Add-Type
added
to the session. The Get-Member command reveals that it's a System.RuntimeType
object, which is
derived from the System.Object class.
The Get-Member Static parameter gets the static properties and methods of the BasicTest
class. The output shows that the Add method is included.

The Get-Member cmdlet gets the members of the object stored in the $BasicTestObject
variable.
$BasicTestObject was created by using the New-Object cmdlet with the
BasicTest 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: Add types from an assembly


This example adds the classes from the Accessibility.dll assembly to the current
session.

PowerShell

$AccType = Add-Type -AssemblyName "accessib*" -PassThru

The $AccType variable stores an object created with the Add-Type cmdlet. Add-Type uses
the
AssemblyName parameter to specify the name of the assembly. The asterisk ( * )
wildcard
character allows you to get the correct assembly even when you aren't sure of
the name or its
spelling. The PassThru parameter generates objects that represent the
classes that are added to
the session.

Example 4: Call native Windows APIs


This example demonstrates how to call native Windows APIs in PowerShell. Add-Type
uses the
Platform Invoke (P/Invoke) mechanism to call a function in User32.dll from
PowerShell. This
example only works on computers running the Windows operating
system.

PowerShell

$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 PowerShell console

$ShowWindowAsync::ShowWindowAsync((Get-Process -Id $pid).MainWindowHandle,


2)

# Restore the PowerShell console

$ShowWindowAsync::ShowWindowAsync((Get-Process -Id $Pid).MainWindowHandle,


4)

The $Signature variable stores the C# signature of the ShowWindowAsync function. To


ensure that
the resulting method will be visible in a PowerShell session, the public
keyword was added to the
standard signature. For more information, see
ShowWindowAsync function.

The $ShowWindowAsync variable stores the object created by the Add-Type PassThru
parameter.
The Add-Type cmdlet adds the ShowWindowAsync function to the PowerShell
session as a static
method. 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. The
PassThru parameter generates an object that represents
the types.

The new ShowWindowAsync static method is used in the commands to minimize and
restore the
PowerShell console. The method takes two parameters: the window handle,
and an integer that
specifies how the window is displayed.

To minimize the PowerShell console, ShowWindowAsync uses the Get-Process cmdlet with
the $PID
automatic variable to get the process that is hosting the current 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, ShowWindowAsync uses a value of 4 for the window position,
which
represents the SW_RESTORE value.

To maximize the window, use the value of 3 that represents SW_MAXIMIZE .

Example 5: Add a type from a Visual Basic file


This example uses the Add-Type cmdlet to add the VBFromFile class that's defined in the
Hello.vb file to the current session. The text of the Hello.vb file is shown in the

command
output.

PowerShell

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

Hello, World

Add-Type uses the Path parameter to specify the source file, Hello.vb , and adds the
type
defined in the file. The SayHello function is called as a static method of the
VBFromFile
class.

Example 6: Add a class with JScript.NET


This example uses JScript.NET to create a new class, FRectangle, in your PowerShell
session.

PowerShell

Add-Type @'

class FRectangle {

var Length : double;

var Height : double;

function Perimeter() : double {

return (Length + Height) * 2; }

function Area() : double {

return Length * Height; } }

'@ -Language JScript

$rect = [FRectangle]::new()

$rect

Length Height

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

0 0

Example 7: Add an F# compiler


This example shows how to use the Add-Type cmdlet to add an F# code compiler to
your PowerShell
session. To run this example in PowerShell, you must have the
FSharp.Compiler.CodeDom.dll that is
installed with the F# language.

PowerShell
Add-Type -Path "FSharp.Compiler.CodeDom.dll"

$Provider = New-Object Microsoft.FSharp.Compiler.CodeDom.FSharpCodeProvider

$FSharpCode = @"

let rec loop n =if n <= 0 then () else beginprint_endline (string_of_int


n);loop (n-1)end

"@

$FSharpType = Add-Type -TypeDefinition $FSharpCode -CodeDomProvider


$Provider -PassThru |

Where-Object { $_.IsPublic }

$FSharpType::loop(4)

Add-Type uses the Path parameter to specify an assembly and gets the types in the
assembly.
New-Object creates an instance of the F# code provider and saves the result in
the $Provider
variable. The $FSharpCode variable saves the F# code that defines the
Loop method.

The the $FSharpType variable stores the results of the Add-Type cmdlet that saves the
public
types defined in $FSharpCode . 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.
The objects are sent down the pipeline to the Where-Object
cmdlet, which returns only the public
types. The Where-Object cmdlet is used because
the F# provider generates non-public types to
support the resulting public type.

The Loop method is called as a static method of the type stored in the $FSharpType
variable.

Parameters
-AssemblyName

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're 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 doesn't accept a path or a file name. To enter the path to the
assembly dynamic-link
library (DLL) file, use the Path parameter.

Type: String[]

Aliases: AN

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-CodeDomProvider

Specifies a code generator or compiler. Add-Type uses the specified compiler to


compile the source
code. The default is the C# compiler. Use this parameter if you're
using a language that can't be
specified by using the Language parameter. The
CodeDomProvider that you specify must be able
to generate assemblies from
source code.

Type: CodeDomProvider

Aliases: Provider

Position: Named

Default value: C# compiler

Accept pipeline input: False

Accept wildcard characters: False

-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.
You can't use the CompilerParameters and ReferencedAssemblies parameters in the
same
command.

Type: CompilerParameters

Aliases: CP

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.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Language

Specifies the language that is used in the source code. The Add-Type cmdlet uses the
value of this
parameter to select the appropriate CodeDomProvider. CSharp is the
default value. The acceptable
values for this parameter are as follows:

CSharp
CSharpVersion2

CSharpVersion3

JScript
VisualBasic

Type: Language

Accepted values: CSharp, CSharpVersion2, CSharpVersion3, JScript, VisualBasic

Position: Named
Default value: CSharp

Accept pipeline input: False

Accept wildcard characters: False

-LiteralPath

Specifies the path to source code files or assembly DLL files that contain the types.
Unlike
Path, the value of the LiteralPath parameter is used exactly as it's typed. No
characters
are interpreted as wildcards. If the path includes escape characters,
enclose it in single quotation
marks. Single quotation marks tell PowerShell not to
interpret any characters as escape sequences.

Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-MemberDefinition

Specifies new properties or methods for the class. Add-Type generates the template
code that is
required to support the properties or methods.

On Windows, you can use this feature to make Platform Invoke (P/Invoke) calls to
unmanaged functions
in PowerShell.

Type: String[]

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Name
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 can't unload a
type or change it.
To change the code for a type, you must change the name or start
a new PowerShell session.
Otherwise, the command fails.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Namespace

Specifies a namespace for the type.

If this parameter isn't 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.

Type: String

Aliases: NS

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-OutputAssembly

Generates a DLL file for the assembly with the specified name in the location. Enter
an optional
path and filename. Wildcard characters are permitted. By default, Add-
Type generates the assembly
only in memory.

Type: String

Aliases: OA
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-OutputType

Specifies the output type of the output assembly. By default, no output type is
specified. This
parameter is valid only when an output assembly is specified in the
command. For more information
about the values, see OutputAssemblyType
Enumeration.

The acceptable values for this parameter are as follows:

ConsoleApplication

Library
WindowsApplication

Type: OutputAssemblyType

Aliases: OT

Accepted values: ConsoleApplication, Library, WindowsApplication

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 doesn't generate any output.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False


Accept wildcard characters: False

-Path

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

Type: String[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ReferencedAssemblies

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.

You can't use the CompilerParameters and ReferencedAssemblies parameters in the


same
command.

Type: String[]

Aliases: RA

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-TypeDefinition

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.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-UsingNamespace

Specifies other namespaces that are required for the class. This is much like the C#
keyword,
Using .

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.

Type: String[]

Aliases: Using

Position: Named

Default value: System namespace

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

Type

When you use the PassThru parameter, this cmdlet returns a System.Type object
representing
the new type.

Notes
The types that you add exist only in the current session. To use the types in all sessions,
add them
to your PowerShell profile. For more information about the profile, see
about_Profiles.

Type names and namespaces must be unique within a session. You can't 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 PowerShell session.
Otherwise, the command fails.

The CodeDomProvider class for some languages, such as IronPython and J#, doesn't
generate
output. As a result, types written in these languages can't be used with Add-
Type .

This cmdlet is based on the Microsoft .NET Framework CodeDomProvider Class.

Related Links
about_Profiles
about_Quoting_Rules
Add-Member
New-Object
OutputAssemblyType
Platform Invoke (P/Invoke)
Where-Object
Clear-Variable
Reference
Module: Microsoft.PowerShell.Utility

Deletes the value of a variable.

Syntax
PowerShell

Clear-Variable

[-Name] <String[]>

[-Include <String[]>]

[-Exclude <String[]>]

[-Force]

[-PassThru]

[-Scope <String>]

[-WhatIf]

[-Confirm]

[<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, this cmdlet preserves the type of the object stored in the
variable.

Examples

Example 1: Remove the value of global variables that


begin with a search string
PowerShell

Clear-Variable my* -Scope Global

This command removes the value of global variables that have names that begin with
my.
Example 2: Clear a variable in a child scope but not the
parent scope
PowerShell

$a=3

&{ Clear-Variable a }

$a

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 the 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: Delete the value of the specified variable


PowerShell

Clear-Variable -Name "Processes"

This command deletes the value of the variable named Processes. After the cmdlet
completes the
operation, the variable named Processes still exists, but the value is null.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


-Exclude

Specifies an array of items that this cmdlet omits in the operation. The value of this
parameter
qualifies the Name parameter. Enter a name element or pattern, such as
"s*". Wildcards are
permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Force

Allows the cmdlet to clear a variable even if it is read-only. Even using the Force
parameter, the
cmdlet cannot clear constants.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Include

Specifies an array of items that this cmdlet includes in the operation. The value of
this parameter
qualifies the Name parameter. Enter a name element or pattern, such
as "s*". Wildcards are
permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True


-Name

Specifies the name of the variable to be cleared. Wildcards are permitted. This
parameter is
required, but the parameter name Name is optional.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-PassThru

Returns an object representing the item with which you are working. By default, this
cmdlet does not
generate any output.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Scope

Specifies the scope in which this alias is valid.

The acceptable values for this parameter are:

Global

Local
Script

You can also use 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.

Type: String

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

PSVariable

When you use the PassThru parameter, this cmdlet returns a PSVariable object
representing
the cleared variable.

Notes
Windows PowerShell includes the following aliases for Clear-Variable :

clv
To delete a variable, along with its value, use Remove-Variable or Remove-Item .

This cmdlet does 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.

Related Links
Get-Variable
New-Variable
Remove-Variable
Set-Variable
Compare-Object
Reference
Module: Microsoft.PowerShell.Utility

Compares two sets of objects.

Syntax
PowerShell

Compare-Object

[-ReferenceObject] <PSObject[]>

[-DifferenceObject] <PSObject[]>

[-SyncWindow <Int32>]

[-Property <Object[]>]

[-ExcludeDifferent]

[-IncludeEqual]

[-PassThru]

[-Culture <String>]

[-CaseSensitive]

[<CommonParameters>]

Description
The Compare-Object cmdlet compares two sets of objects. One set of objects is the
reference,
and the other set of objects is the difference.

Compare-Object checks for available methods of comparing a whole object. If it can't


find a
suitable method, it calls the ToString() methods of the input objects and
compares the string
results. You can provide one or more properties to be used for
comparison. When properties are
provided, the cmdlet compares the values of those
properties only.

The result of the comparison indicates whether a property value appeared only in the
reference
object ( <= ) or only in the difference object ( => ). If the IncludeEqual
parameter is
used, ( == ) indicates the value is in both objects.

If the reference or the difference objects are null ( $null ), Compare-Object generates a
terminating error.

Some examples use splatting to reduce the line length of the code samples. For more
information, see
about_Splatting.
Examples

Example 1 - Compare the content of two text files


This example compares the contents of two text files. The example uses the following
two text files,
with each value on a separate line.

Testfile1.txt contains the values: dog, squirrel, and bird.


Testfile2.txt contains the values: cat, bird, and racoon.

The output displays only the lines that are different between the files. Testfile1.txt is
the
reference object ( <= ) and Testfile2.txt is the difference object ( => ). Lines with
content that appear in both files aren't displayed.

PowerShell

Compare-Object -ReferenceObject (Get-Content -Path C:\Test\Testfile1.txt) -


DifferenceObject (Get-Content -Path C:\Test\Testfile2.txt)

InputObject SideIndicator

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

cat =>

racoon =>

dog <=

squirrel <=

Example 2 - Compare each line of content and exclude


the differences
This example uses the IncludeEqual and ExcludeDifferent parameters to compare each
line of
content in two text files.

Because the command uses the ExcludeDifferent parameter, the output only contains
lines
contained in both files, as shown by the SideIndicator ( == ).

PowerShell

$objects = @{

ReferenceObject = (Get-Content -Path C:\Test\Testfile1.txt)

DifferenceObject = (Get-Content -Path C:\Test\Testfile2.txt)

Compare-Object @objects -IncludeEqual -ExcludeDifferent

InputObject SideIndicator

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

bird ==

Example 3 - Show the difference when using the PassThru


parameter
Normally, Compare-Object returns a PSCustomObject type with the following properties:

The InputObject being compared


The SideIndicator property showing which input object the output belongs to

When you use the PassThru parameter, the Type of the object is not changed but the
instance
of the object returned has an added NoteProperty named SideIndicator.
SideIndicator
shows which input object the output belongs to.

The following examples shows the different output types.

PowerShell

$a = $True

Compare-Object -IncludeEqual $a $a

(Compare-Object -IncludeEqual $a $a) | Get-Member

InputObject SideIndicator

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

True ==

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()

InputObject NoteProperty System.Boolean InputObject=True

SideIndicator NoteProperty string SideIndicator===

Compare-Object -IncludeEqual $a $a -PassThru

(Compare-Object -IncludeEqual $a $a -PassThru) | Get-Member

True

TypeName: System.Boolean

Name MemberType Definition

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

CompareTo Method int CompareTo(System.Object obj), int


CompareTo(bool value), int IComparable.CompareTo(Syst

Equals Method bool Equals(System.Object obj), bool Equals(bool


obj), bool IEquatable[bool].Equals(bool ot

GetHashCode Method int GetHashCode()

GetType Method type GetType()

GetTypeCode Method System.TypeCode GetTypeCode(), System.TypeCode


IConvertible.GetTypeCode()

ToBoolean Method bool


IConvertible.ToBoolean(System.IFormatProvider provider)

ToByte Method byte IConvertible.ToByte(System.IFormatProvider


provider)

ToChar Method char IConvertible.ToChar(System.IFormatProvider


provider)

ToDateTime Method datetime


IConvertible.ToDateTime(System.IFormatProvider provider)

ToDecimal Method decimal


IConvertible.ToDecimal(System.IFormatProvider provider)

ToDouble Method double


IConvertible.ToDouble(System.IFormatProvider provider)

ToInt16 Method short IConvertible.ToInt16(System.IFormatProvider


provider)

ToInt32 Method int IConvertible.ToInt32(System.IFormatProvider


provider)

ToInt64 Method long IConvertible.ToInt64(System.IFormatProvider


provider)

ToSByte Method sbyte IConvertible.ToSByte(System.IFormatProvider


provider)

ToSingle Method float


IConvertible.ToSingle(System.IFormatProvider provider)

ToString Method string ToString(), string


ToString(System.IFormatProvider provider), string IConvertible.To

ToType Method System.Object IConvertible.ToType(type


conversionType, System.IFormatProvider provider)

ToUInt16 Method ushort


IConvertible.ToUInt16(System.IFormatProvider provider)

ToUInt32 Method uint IConvertible.ToUInt32(System.IFormatProvider


provider)

ToUInt64 Method ulong


IConvertible.ToUInt64(System.IFormatProvider provider)

TryFormat Method bool TryFormat(System.Span[char] destination,


[ref] int charsWritten)

SideIndicator NoteProperty string SideIndicator===

When using PassThru, the original object type (System.Boolean) is returned. Note how
the
output displayed by the default format for System.Boolean objects didn't display
the
SideIndicator property. However, the returned System.Boolean object has the
added
NoteProperty.

Example 4 - Compare two simple objects using properties


In this example, we compare two different string that have the same length.

PowerShell
Compare-Object -ReferenceObject 'abc' -DifferenceObject 'xyz' -Property
Length -IncludeEqual

Length SideIndicator

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

3 ==

Example 5 - Comparing complex objects using properties


This example shows the behavior when comparing complex objects. In this example we
store two
different process objects for different instances of PowerShell. Both variables
contain process
objects with the same name. When the objects are compared without
specifying the Property
parameter, the cmdlet considers the objects to be equal. Notice
that the value of the
InputObject is the same as the result of the ToString() method.
Since the
System.Diagnostics.Process class does not have the IComparable interface,
the cmdlet
converts the objects to strings then compares the results.

PowerShell

PS> Get-Process pwsh

NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName

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

101 123.32 139.10 35.81 11168 1 pwsh

89 107.55 66.97 11.44 17600 1 pwsh

PS> $a = Get-Process -Id 11168

PS> $b = Get-Process -Id 17600

PS> $a.ToString()

System.Diagnostics.Process (pwsh)
PS> $b.ToString()

System.Diagnostics.Process (pwsh)
PS> Compare-Object $a $b -IncludeEqual

InputObject SideIndicator

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

System.Diagnostics.Process (pwsh) ==

PS> Compare-Object $a $b -Property ProcessName, Id, CPU

ProcessName Id CPU SideIndicator

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

pwsh 17600 11.4375 =>

pwsh 11168 36.203125 <=

When you specify properties to be compared, the cmdlet shows the differences.
Example 6 - Comparing complex objects that implement
IComparable
If the object implements IComparable, the cmdlet searches for ways to compare the
objects.If the
objects are different types, the Difference object is converted to the type
of the
ReferenceObject then compared.

In this example, we are comparing a string to a TimeSpan object. In the first case, the
string
is converted to a TimeSpan so the objects are equal.

PowerShell

Compare-Object ([TimeSpan]"0:0:1") "0:0:1" -IncludeEqual

InputObject SideIndicator

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

00:00:01 ==

Compare-Object "0:0:1" ([TimeSpan]"0:0:1")

InputObject SideIndicator

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

00:00:01 =>

0:0:1 <=

In the second case, the TimeSpan is converted to a string so the object are different.

Parameters
-CaseSensitive

Indicates that comparisons should be case-sensitive.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Culture

Specifies the culture to use for comparisons.


Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-DifferenceObject

Specifies the objects that are compared to the reference objects.

Type: PSObject[]

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-ExcludeDifferent

Indicates that this cmdlet displays only the characteristics of compared objects that
are equal. The
differences between the objects are discarded.

Use ExcludeDifferent with IncludeEqual to display only the lines that match between
the
reference and difference objects.

If ExcludeDifferent is specified without IncludeEqual, there's no output.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-IncludeEqual

IncludeEqual displays the matches between the reference and difference objects.
By default, the output also includes the differences between the reference and
difference
objects.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-PassThru

When you use the PassThru parameter, Compare-Object omits the PSCustomObject
wrapper
around the compared objects and returns the differing objects, unchanged.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Property

Specifies an array of properties of the reference and difference objects to compare.

The value of the Property parameter can be a new calculated property. The
calculated property
can be a script block or a hash table. Valid key-value pairs are:

Expression - <string> or <script block>

For more information, see


about_Calculated_Properties.

Type: Object[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-ReferenceObject

Specifies an array of objects used as a reference for comparison.

Type: PSObject[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SyncWindow

Specifies the number of adjacent objects that Compare-Object inspects while looking
for a match in
a collection of objects. Compare-Object examines adjacent objects
when it doesn't find the object
in the same position in a collection. The default value
is [Int32]::MaxValue , which means that
Compare-Object examines the entire object
collection.

When working with large collections, the default value might not be efficient but is
accurate.
Specifying a smaller value for SyncWindow can increase performance but
could have lower
accuracy.

Type: Int32

Position: Named

Default value: [Int32]::MaxValue

Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSObject

You can send an object down the pipeline to the DifferenceObject parameter.

Outputs
None
By default, this cmdlet returns no output when the ReferenceObject and the
DifferenceObject
are the same.

PSCustomObject

When the objects are different, this cmdlet wraps the differing objects in a
PSCustomObject
wrapper with a SideIndicator property to reference the differences.

When you use the PassThru parameter, the Type of the object is not changed but the
instance
of the object returned has an added NoteProperty named SideIndicator.
SideIndicator
shows which input object the output belongs to.

Notes
Windows PowerShell includes the following aliases for Compare-Object :

compare
diff

When using the PassThru parameter, the output displayed in the console may not
include the
SideIndicator property. The default format view for the object type output
by Compare-Object
does not include the SideIndicator property. For more information
see Example 3 in this
article.

Related Links
about_Calculated_Properties
ForEach-Object
Group-Object
Measure-Object
New-Object
Select-Object
Sort-Object
Tee-Object
Where-Object
Get-Process
ConvertFrom-Csv
Reference
Module: Microsoft.PowerShell.Utility

Converts object properties in character-separated value (CSV) format into CSV versions
of the
original objects.

Syntax
PowerShell

ConvertFrom-Csv

[-InputObject] <psobject[]>

[[-Delimiter] <char>]

[-Header <string[]>]

[<CommonParameters>]

PowerShell

ConvertFrom-Csv

[-InputObject] <psobject[]>

-UseCulture

[-Header <string[]>]

[<CommonParameters>]

Description
The ConvertFrom-Csv cmdlet converts character-separated value (CSV) data to PSObject
type
objects for each line of CSV data. The new objects are written to the pipeline in the
order they are
read from the CSV data. The values in column header row of the CSV
become the names of the
properties added to each new PSObject.

The objects that ConvertFrom-Csv creates are PSObject type object for each row in the
CSV
file. The property values of the CSV objects are string versions of the property
values of the
original objects. The CSV versions of the objects don't 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.
The PSObject type maintains the order of the properties in column header order. This
means that
you get the same column order when you convert the objects back into CSV
format.

Examples

Example 1: Convert processes on the local computer to


CSV format
This example shows how to convert the processes on the local computer into CSV
format and then
restore them to object form.

PowerShell

$P = Get-Process | ConvertTo-Csv

$P | ConvertFrom-Csv

The Get-Process cmdlet sends the processes down the pipeline to ConvertTo-Csv . The
ConvertTo-Csv cmdlet converts the process objects to a series of CSV strings. The
ConvertFrom-Csv cmdlet converts the CSV strings into CSV versions of the original

process objects.
The CSV strings are saved in the $P variable.

Example 2: Convert a data object to CSV format and then


to CSV object format
This example shows how to convert a data object to CSV format and then to CSV object
format.

PowerShell

$Date = Get-Date | ConvertTo-Csv -Delimiter ';'

ConvertFrom-Csv -InputObject $Date -Delimiter ';'

The first command uses Get-Date to send the current date and time down the pipeline
to
ConvertTo-Csv . The ConvertTo-Csv cmdlet converts the date object to a series of CSV
strings. The
Delimiter parameter is used to specify a semicolon delimiter. The strings are
saved in the
$Date variable.
Example 3: Use the header parameter to change the
names of properties
This example shows how to use the Header parameter of ConvertFrom-Csv to change
the names of
properties in the resulting imported object.

PowerShell

$J = Start-Job -ScriptBlock { Get-Process } | ConvertTo-Csv -


NoTypeInformation

$Header = 'State', 'MoreData', 'StatusMessage', 'Location', 'Command',

'StateInfo', 'Finished', 'InstanceId', 'Id', 'Name', 'ChildJobs',

'BeginTime', 'EndTime', 'JobType', 'Output', 'Error', 'Progress',

'Verbose', 'Debug', 'Warning', 'Information'

# Delete the default header from $J

$J = $J[1..($J.count - 1)]

$J | ConvertFrom-Csv -Header $Header

State : Running

MoreData : True

StatusMessage :

Location : localhost

Command : Get-Process

StateInfo : Running

Finished : System.Threading.ManualResetEvent

InstanceId : a259eb63-6824-4b97-a033-305108ae1c2e

Id : 1

Name : Job1

ChildJobs :
System.Collections.Generic.List`1[System.Management.Automation.Job]

BeginTime : 12/20/2018 18:59:57

EndTime :

JobType : BackgroundJob

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.Management.Automation
.VerboseRecord]

Debug :
System.Management.Automation.PSDataCollection`1[System.Management.Automation
.DebugRecord]

Warning :
System.Management.Automation.PSDataCollection`1[System.Management.Automation
.WarningRecord]

Information :
System.Management.Automation.PSDataCollection`1[System.Management.Automation
.InformationRecord]

The Start-Job cmdlet starts a background job that runs Get-Process . A job object is
sent down
the pipeline to ConvertTo-Csv and converted to a CSV string. The
NoTypeInformation parameter
removes the type information header from CSV output
and is optional in PowerShell v6 and higher. The
$Header variable contains a custom
header that replaces the following default values:
HasMoreData, JobStateInfo,
PSBeginTime, PSEndTime, and PSJobTypeName. The $J
variable contains the CSV
string and is used to remove the default header. The ConvertFrom-Csv
cmdlet converts
the CSV string into a PSCustomObject and uses the Header parameter to apply
the
$Header variable.

Example 4: Convert CSV strings of service objects


This example shows how to use the ConvertFrom-Csv cmdlet with the UseCulture
parameter.

PowerShell

(Get-Culture).TextInfo.ListSeparator

$Services = (Get-Service | ConvertTo-Csv)

ConvertFrom-Csv -InputObject $Services -UseCulture

The Get-Culture cmdlet uses the nested properties TextInfo and ListSeparator to get
the
current culture's default list separator. The Get-Service cmdlet sends service objects
down the
pipeline to ConvertTo-Csv . The ConvertTo-Csv converts the service objects to
a series of CSV
strings. The CSV strings are stored in the $Services variable. The
ConvertFrom-Csv cmdlet uses
the InputObject parameter and converts the CSV strings
from the $Services variable. The
UseCulture parameter uses the current culture's
default list separator.

When the UseCulture parameter is used, be sure that the current culture's default list
separator matches the delimiter used in the CSV strings. Otherwise, ConvertFrom-Csv
can't
generate objects from the CSV strings.

Parameters
-Delimiter
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
single quotation marks.

If you specify a character other than the actual string delimiter in the file,
ConvertFrom-Csv
can't create the objects from the CSV strings and returns the CSV

strings.

Type: Char

Position: 1

Default value: comma (,)

Accept pipeline input: False

Accept wildcard characters: False

-Header

Specifies an alternate column header row for the imported string. The column
header determines the
property names of the objects created by ConvertFrom-Csv .

Enter column headers as a character-separated list. don't enclose the header string in
quotation
marks. Enclose each column header in single quotation marks.

If you enter fewer column headers than there are data columns, the remaining data
columns are
discarded. If you enter more column headers than there are data
columns, the additional column
headers are created with empty data columns.

When using the Header parameter, omit the column header string from the CSV
strings. Otherwise,
this cmdlet creates an extra object from the items in the header
row.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

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

Type: PSObject[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-UseCulture

Uses the list separator for the current culture as the item delimiter. To find the list
separator
for a culture, use the following command: (Get-
Culture).TextInfo.ListSeparator .

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe CSV strings to this cmdlet.

Outputs
PSObject

This cmdlet returns the objects described by the properties in the CSV strings.

Notes
In CSV format, each object is represented by a character-separated list of the property
values of
the object. The property values are converted to strings, using the ToString()
method of the
object. There is no way to export the methods of the object.

Related Links
ConvertTo-Csv
Export-Csv
Import-Csv
ConvertFrom-Json
Reference
Module: Microsoft.PowerShell.Utility

Converts a JSON-formatted string to a custom object.

Syntax
PowerShell

ConvertFrom-Json

[-InputObject] <String>

[<CommonParameters>]

Description
The ConvertFrom-Json cmdlet converts a JavaScript Object Notation (JSON) formatted
string to a
custom PSObject or Hashtable object that has a property for each field in the
JSON string.
JSON is commonly used by web sites to provide a textual representation of
objects. The cmdlet adds
the properties to the new object as it processes each line of
the JSON string.

The JSON standard allows duplicate key names, which are prohibited in PSObject end
Hashtable
types. For example, if the JSON string contains duplicate keys, only the last
key is used by this
cmdlet. See other examples below.

To generate a JSON string from any object, use the ConvertTo-Json cmdlet.

This cmdlet was introduced in PowerShell 3.0.

7 Note

Beginning with PowerShell 6, the cmdlet supports JSON with comments. JSON
comments start with two
forward slashes ( // ) characters. JSON comments aren't
captured in the objects output by the
cmdlet. Prior to PowerShell 6, ConvertFrom-
Json would return an error when it encountered a JSON
comment.

Examples
Example 1: Convert a DateTime object to a JSON object
This command uses the ConvertTo-Json and ConvertFrom-Json cmdlets to convert a
DateTime
object from the Get-Date cmdlet to a JSON object then to a
PSCustomObject.

PowerShell

Get-Date | Select-Object -Property * | ConvertTo-Json | ConvertFrom-Json

DisplayHint : 2

DateTime : Friday, January 13, 2012 8:06:31 PM

Date : 1/13/2012 8:00:00 AM

Day : 13

DayOfWeek : 5

DayOfYear : 13

Hour : 20

Kind : 2

Millisecond : 400

Minute : 6

Month : 1

Second : 31

Ticks : 634620819914009002

TimeOfDay : @{Ticks=723914009002; Days=0; Hours=20; Milliseconds=400;


Minutes=6; Seconds=31; TotalDays=0.83786343634490734;
TotalHours=20.108722472277776; TotalMilliseconds=72391400.900200009;
TotalMinutes=1206.5233483366667;TotalSeconds=72391.4009002}

Year : 2012

The example uses the Select-Object cmdlet to get all of the properties of the DateTime
object. It uses the ConvertTo-Json cmdlet to convert the DateTime object to a string
formatted as a JSON object and the ConvertFrom-Json cmdlet to convert the JSON-
formatted string
to a PSCustomObject object.

Example 2: Get JSON strings from a web service and


convert them to PowerShell objects
This command uses the Invoke-WebRequest cmdlet to get JSON strings from a web
service
and then it uses the ConvertFrom-Json cmdlet to convert JSON content to
objects
that can be managed in PowerShell.

PowerShell

# Ensures that Invoke-WebRequest uses TLS 1.2

[Net.ServicePointManager]::SecurityProtocol =
[Net.SecurityProtocolType]::Tls12
$j = Invoke-WebRequest
'https://api.github.com/repos/PowerShell/PowerShell/issues' | ConvertFrom-
Json

You can also use the Invoke-RestMethod cmdlet, which automatically converts JSON
content to
objects.

Example 3: Convert a JSON string to a custom object


This example shows how to use the ConvertFrom-Json cmdlet to convert a JSON file to a
PowerShell
custom object.

PowerShell

Get-Content -Raw JsonFile.JSON | ConvertFrom-Json

The command uses Get-Content cmdlet to get the strings in a JSON file. The Raw
parameter
returns the whole file as a single JSON object. Then it uses the pipeline
operator to send the
delimited string to the ConvertFrom-Json cmdlet, which converts it
to a custom object.

Parameters
-InputObject

Specifies the JSON strings to convert to JSON objects. Enter a variable that contains
the string,
or type a command or expression that gets the string. You can also pipe a
string to
ConvertFrom-Json .

The InputObject parameter is required, but its value can be an empty string. When
the input
object is an empty string, ConvertFrom-Json doesn't generate any output.
The InputObject
value can't be $null .

Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False


Inputs
String

You can pipe a JSON string to ConvertFrom-Json .

Outputs
PSCustomObject

Notes
The ConvertFrom-Json cmdlet is implemented using the
JavaScriptSerializer class.

The PSObject type maintains the order of the properties as presented in the JSON
string. While
the key-value pairs are added to the Hashtable in the order presented in
the JSON string,
Hashtable objects don't maintain that order.

Related Links
An Introduction to JavaScript Object Notation (JSON) in JavaScript and .NET
ConvertTo-Json
Invoke-WebRequest
Invoke-RestMethod
ConvertFrom-SddlString
Reference
Module: Microsoft.PowerShell.Utility

Converts a SDDL string to a custom object.

Syntax
PowerShell

ConvertFrom-SddlString

[-Sddl] <String>

[-Type <Object>]

[<CommonParameters>]

Description
The ConvertFrom-SddlString cmdlet converts a Security Descriptor Definition Language
string to a
custom PSCustomObject object with the following properties: Owner, Group,
DiscretionaryAcl,
SystemAcl and RawDescriptor.

Owner, Group, DiscretionaryAcl and SystemAcl properties contain a readable text


representation of
the access rights specified in a SDDL string.

This cmdlet was introduced in PowerShell 5.0.

Examples

Example 1: Convert file system access rights SDDL to a


PSCustomObject
PowerShell

$acl = Get-Acl -Path C:\Windows

ConvertFrom-SddlString -Sddl $acl.Sddl

The first command uses the Get-Acl cmdlet to get the security descriptor for the
C:\Windows folder
and saves it in the variable.
The second command uses the ConvertFrom-SddlString cmdlet to get the text
representation of the
SDDL string, contained in the Sddl property of the object
representing the security descriptor.

Example 2: Convert registry access rights SDDL to a


PSCustomObject
PowerShell

$acl = Get-Acl HKLM:\SOFTWARE\Microsoft\

ConvertFrom-SddlString -Sddl $acl.Sddl -Type RegistryRights

The first command uses the Get-Acl cmdlet to get the security descriptor for the
HKLM:\SOFTWARE\Microsoft\ key and saves it in the variable.

The second command uses the ConvertFrom-SddlString cmdlet to get the text
representation of the
SDDL string, contained in the Sddl property of the object
representing the security descriptor.

It uses the -Type parameter to specify that SDDL string represents a registry security
descriptor.

Example 3: Convert registry access rights SDDL to a


PSCustomObject by using ConvertFrom-SddlString with
and without the `-Type` parameter
PowerShell

$acl = Get-Acl -Path HKLM:\SOFTWARE\Microsoft\

ConvertFrom-SddlString -Sddl $acl.Sddl | Foreach-Object


{$_.DiscretionaryAcl[0]}

BUILTIN\Administrators: AccessAllowed (ChangePermissions, CreateDirectories,


Delete, ExecuteKey, FullControl, GenericExecute, GenericWrite,
ListDirectory, ReadExtendedAttributes, ReadPermissions, TakeOwnership,
Traverse, WriteData, WriteExtendedAttributes, WriteKey)

ConvertFrom-SddlString -Sddl $acl.Sddl -Type RegistryRights | Foreach-Object


{$_.DiscretionaryAcl[0]}

BUILTIN\Administrators: AccessAllowed (ChangePermissions, CreateLink,


CreateSubKey, Delete, EnumerateSubKeys, ExecuteKey, FullControl,
GenericExecute, GenericWrite, Notify, QueryValues, ReadPermissions,
SetValue, TakeOwnership, WriteKey)
The first command uses the Get-Acl cmdlet to get the security descriptor for the
HKLM:\SOFTWARE\Microsoft\ key and saves it in the variable.

The second command uses the ConvertFrom-SddlString cmdlet to get the text
representation of the
SDDL string, contained in the Sddl property of the object
representing the security descriptor.

It doesn't use the -Type parameter, so the access rights shown are for file system.

The third command uses the ConvertFrom-SddlString cmdlet with the -Type parameter,
so the access
rights returned are for registry.

Example 4: Convert Active Directory access rights SDDL


to a PSCustomObject
PowerShell

$user = [ADSI]"LDAP://CN=username,CN=Users,DC=domain,DC=com"

ConvertFrom-SddlString $user.psbase.ObjectSecurity.Sddl -Type


ActiveDirectoryRights

The first command uses Active Directory Service Interfaces (ADSI) to get the user object
and saves it in the variable.

The second command uses the ConvertFrom-SddlString cmdlet to get text


representation of the SDDL string, contained in the Sddl property of the object
representing the security descriptor.

It uses the -Type parameter to specify that SDDL string represents an Active Directory
security descriptor.

Parameters
-Sddl

Specifies the string representing the security descriptor in SDDL syntax.

Type: String

Position: 0

Default value: None


Accept pipeline input: True

Accept wildcard characters: False

-Type

Specifies the type of rights that SDDL string represents.

The acceptable values for this parameter are:

FileSystemRights
RegistryRights
ActiveDirectoryRights
MutexRights
SemaphoreRights
CryptoKeyRights
EventWaitHandleRights

By default cmdlet uses file system rights.

CryptoKeyRights and ActiveDirectoryRights are not supported in PowerShell v6 and


higher.

Type: Object

Accepted values: FileSystemRights, RegistryRights, ActiveDirectoryRights,


MutexRights, SemaphoreRights, CryptoKeyRights,
EventWaitHandleRights

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a SDDL string to this cmdlet.

Related Links
Security Descriptor Definition Language
ConvertFrom-String
Reference
Module: Microsoft.PowerShell.Utility

Extracts and parses structured properties from string content.

Syntax
PowerShell

ConvertFrom-String

[-Delimiter <String>]

[-PropertyNames <String[]>]

[-InputObject] <String>

[<CommonParameters>]

PowerShell

ConvertFrom-String

[-TemplateFile <String[]>]

[-TemplateContent <String[]>]

[-IncludeExtent]

[-UpdateTemplate]
[-InputObject] <String>

[<CommonParameters>]

Description
The ConvertFrom-String cmdlet extracts and parses structured properties from string
content. This
cmdlet generates an object by parsing text from a traditional text stream.
For each string in the
pipeline, the cmdlet splits the input by either a delimiter or a parse
expression, and then assigns
property names to each of the resulting split elements. You
can provide these property names; if you
do not, they are automatically generated for
you.

The cmdlet's default parameter set, ByDelimiter, splits exactly on the regular expression
delimiter. It does not perform quote matching or delimiter escaping as the Import-Csv
cmdlet does.

The cmdlet's alternate parameter set, TemplateParsing, generates elements from the
groups that
are captured by a regular expression. For more information on regular
expressions, see about_Regular_Expressions.

This cmdlet supports two modes: basic delimited parsing, and automatically-generated,
example-driven
parsing.

Delimited parsing, by default, splits the input at white space, and assigns property
names to the
resulting groups.

You can customize the delimiter by piping the ConvertFrom-String results into one of
the
Format-* cmdlets, or you can use the Delimiter parameter.

The cmdlet also supports automatically-generated, example-driven parsing based on


the FlashExtract, research work by Microsoft Research .

Examples

Example 1: Generate an object with default property


names
PowerShell

"Hello World" | ConvertFrom-String

P1 P2

-- --

Hello World

This command generates an object with default property names, P1 and P2.

Example 1A: Get to know the generated object


This command generates one object with properties P1, P2; both properties are of
String
type, by default.

PowerShell

"Hello World" | ConvertFrom-String | 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()

P1 NoteProperty string P1=Hello

P2 NoteProperty string P2=World

Example 2: Generate an object with default property


names using a delimiter
This command generates an object with a domain and username using the backslash
( \ ) as the
delimiter. The backslash character must be escaped with another backslash
when using regular
expressions.

PowerShell

"Contoso\Administrator" | ConvertFrom-String -Delimiter "\\"

P1 P2

-- --

Contoso Administrator

Example 3: Generate an object that contains two named


properties
The following example creates objects from Windows hosts file entries.

PowerShell

$content = Get-Content C:\Windows\System32\drivers\etc\hosts

$content = $content -match "^[^#]"

$content | ConvertFrom-String -PropertyNames IP, Server

IP Server

-- ------

192.168.7.10 W2012R2

192.168.7.20 W2016

192.168.7.101 WIN8

192.168.7.102 WIN10

The Get-Content cmdlet stores the content of a Windows hosts file in $content . The
second
command removes any comments at the beginning of the hosts file using a
regular expression that
matches any line that does not start with ( # ). The last command
converts the remaining text into
objects with Server and IP properties.
Example 4: Use an expression as the value of the
TemplateContent parameter, save the results in a variable.
This command uses an expression as the value of the TemplateContent parameter. The
expression is
saved in a variable for simplicity. Windows PowerShell understands now
that the string that is used
on the pipeline to ConvertFrom-String has three properties:

Name
phone
age

PowerShell

$template = @'

{Name*:Phoebe Cat}, {phone:425-123-6789}, {age:6}

{Name*:Lucky Shot}, {phone:(206) 987-4321}, {age:12}

'@

$testText = @'

Phoebe Cat, 425-123-6789, 6

Lucky Shot, (206) 987-4321, 12

Elephant Wise, 425-888-7766, 87

Wild Shrimp, (111) 222-3333, 1

'@

$PersonalData = $testText | ConvertFrom-String -TemplateContent $template

Write-output ("Pet items found: " + ($PersonalData.Count))

$PersonalData

Pet items found: 4

Name phone age


---- ----- ---
Phoebe Cat 425-123-6789 6

Lucky Shot (206) 987-4321 12

Elephant Wise 425-888-7766 87

Wild Shrimp (111) 222-3333 1

Each line in the input is evaluated by the sample matches. If the line matches the
examples given in
the pattern, values are extracted and passed to the output variable.

The sample data, $template , provides two different phone formats:

425-123-6789
(206) 987-4321

The sample data also provides two different age formats:


6

12

This implies that phones like (206) 987 4321 will not be recognized, because there's no
sample
data that matches that pattern because there are no hyphens.

Example 5: Specifying data types to the generated


properties
This is the same example as Example 4, above. The difference is that the pattern string
includes a
data type for each desired property.

PowerShell

$template = @'

{[string]Name*:Phoebe Cat}, {[string]phone:425-123-6789}, {[int]age:6}

{[string]Name*:Lucky Shot}, {[string]phone:(206) 987-4321}, {[int]age:12}

'@

$testText = @'

Phoebe Cat, 425-123-6789, 6

Lucky Shot, (206) 987-4321, 12

Elephant Wise, 425-888-7766, 87

Wild Shrimp, (111) 222-3333, 1

'@

$PersonalData = $testText | ConvertFrom-String -TemplateContent $template

Write-output ("Pet items found: " + ($PersonalData.Count))

$PersonalData

Pet items found: 4

Name phone age


---- ----- ---
Phoebe Cat 425-123-6789 6

Lucky Shot (206) 987-4321 12

Elephant Wise 425-888-7766 87

Wild Shrimp (111) 222-3333 1

$PersonalData | 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()

age NoteProperty int age=6

Name NoteProperty string Name=Phoebe Cat

phone NoteProperty string phone=425-123-6789

The Get-Member cmdlet is used to show that the age property is an integer.

Parameters
-Delimiter

Specifies a regular expression that identifies the boundary between elements.


Elements that are
created by the split become properties in the resulting object. The
delimiter is ultimately used in
a call to the Split method of the type
[System.Text.RegularExpressions.RegularExpression] .

Type: String

Aliases: DEL

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-IncludeExtent

Indicates that this cmdlet includes an extent text property that is removed by default.

Type: SwitchParameter

Aliases: IE

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies strings received from the pipeline, or a variable that contains a string
object.
Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-PropertyNames

Specifies an array of property names to which to assign split values in the resulting
object. Every
line of text that you split or parse generates elements that represent
property values. If the
element is the result of a capture group, and that capture
group is named (for example, (?<name>)
or (?'name') ), then the name of that
capture group is assigned to the property.

If you provide any elements in the PropertyName array, those names are assigned to
properties
that have not yet been named.

If you provide more property names than there are fields, PowerShell ignores the
extra property
names. If you do not specify enough property names to name all
fields, PowerShell automatically
assigns numerical property names to any properties
that are not named: P1, P2, etc.

Type: String[]

Aliases: PN

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-TemplateContent

Specifies an expression, or an expression saved as a variable, that describes the


properties to
which this cmdlet assigns strings. The syntax of a template field
specification is the following: {[optional-typecast]<name>:<example-value>} .

Type: String[]

Aliases: TC
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-TemplateFile

Specifies a file, as an array, that contains a template for the desired parsing of the
string. In
the template file, properties and their values are enclosed in brackets, as
shown below. If a
property, such as the Name property and its associated other
properties, appears multiple times,
you can add an asterisk ( * ) to indicate that this
results in multiple records. This avoids
extracting multiple properties into a single
record.

{Name*:David Chew}
{City:Redmond}, {State:WA}
{Name*:Evan Narvaez}
{Name*:Antonio Moreno}
{City:Issaquah}, {State:WA}

Type: String[]

Aliases: TF

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-UpdateTemplate

Indicates that this cmdlet saves the results of a learning algorithm into a comment in
the template
file. This makes the algorithm learning process faster. To use this
parameter, you must also specify
a template file with the TemplateFile parameter.

Type: SwitchParameter

Aliases: UT

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

Inputs
String

Related Links
ConvertFrom-String: Example-based text parsing
ConvertFrom-StringData
ConvertFrom-Csv
ConvertTo-Xml
ConvertFrom-StringData
Reference
Module: Microsoft.PowerShell.Utility

Converts a string containing one or more key and value pairs to a hash table.

Syntax
PowerShell

ConvertFrom-StringData

[-StringData] <String>

[<CommonParameters>]

Description
The ConvertFrom-StringData cmdlet converts a string that contains one or more key and
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. By default, the key must be separated
from the value by an equals
sign ( = ) character.

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.

ConvertFrom-StringData supports escape character sequences that are allowed by


conventional
machine translation tools. That is, the cmdlet can interpret backslashes ( \ )
as escape characters
in the string data by using the
Regex.Unescape Method, instead of
the
PowerShell backtick character ( ` ) that would normally signal the end of a line in a
script.
Inside the here-string, the backtick character does not work. You can also
preserve a literal
backslash in your results by escaping it with a preceding backslash, like
this: \\ . Unescaped
backslash characters, such as those that are commonly used in file
paths, can render as illegal
escape sequences in your results.

Examples
Example 1: Convert a single-quoted here-string to a hash
table
This example converts 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 ConvertFrom-StringData cmdlet converts the value in the $Here variable
to a hash table.

PowerShell

$Here = @'

Msg1 = The string parameter is required.

Msg2 = Credentials are required for this command.

Msg3 = The specified variable does not exist.

'@

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.

Example 2: Convert a here-string containing a comment


This example converts a here-string that contains a comment and multiple key-value
pairs into a hash
table.

PowerShell

ConvertFrom-StringData -StringData @'

Name = Disks.ps1

# Category is optional.

Category = Storage

Cost = Free

'@

Name Value

---- -----

Cost Free

Category Storage

Name Disks.ps1

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.
ConvertFrom-StringData ignores single-line comments, but the #
character must be the first
non-whitespace character on the line. All characters on the
line after the # are ignored.

Example 3: Convert a string to a hash table


This example converts a regular double-quoted string (not a here-string) into a hash
table and saves
it in the $A variable.

PowerShell

$A = ConvertFrom-StringData -StringData "Top = Red `n Bottom = Blue"

$A

Name Value

---- -----

Bottom Blue

Top Red

To satisfy the condition that each key-value pair must be on a separate line, the string
uses the
PowerShell newline character ( `n ) to separate the pairs.

Example 4: Use ConvertFrom-StringData in the DATA


section of a script
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.

PowerShell

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

'@

$TextMsgs

Name Value

---- -----

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.
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 5: Use the pipeline operator to pass a string


This example shows that you can use a pipeline operator ( | ) to send a string to
ConvertFrom-StringData . The the value of the $Here variable is piped to ConvertFrom-

StringData
and the result in the $Hash variable.

PowerShell

$Here = @'

Msg1 = The string parameter is required.

Msg2 = Credentials are required for this command.

Msg3 = The specified variable does not exist.

'@

$Hash = $Here | ConvertFrom-StringData

$Hash

Name Value

---- -----

Msg3 The specified variable does not exist.

Msg2 Credentials are required for this command.

Msg1 The string parameter is required.

Example 6: Use escape characters to add new lines and


return characters
This example shows the use of escape characters to create new lines and return
characters in source
data. The escape sequence \n is used to create new lines within a
block of text that is associated
with a name or item in the resulting hash table.

PowerShell

ConvertFrom-StringData @"

Vincentio = Heaven doth with us as we with torches do,\nNot light them for
themselves; for if our virtues\nDid not go forth of us, 'twere all alike\nAs
if we had them not.

Angelo = Let there be some more test made of my metal,\nBefore so noble and
so great a figure\nBe stamp'd upon it.

"@ | Format-List

Name : Angelo

Value : Let there be some more test made of my metal,

Before so noble and so great a figure

Be stamp'd upon it.

Name : Vincentio

Value : Heaven doth with us as we with torches do,

Not light them for themselves; for if our virtues

Did not go forth of us, 'twere all alike

As if we had them not.

Example 7: Use backslash escape character to correctly


render a file path
This example shows how to use of the backslash escape character in the string data to
allow a file
path to render correctly in the resulting ConvertFrom-StringData hash table.
The double backslash
ensures that the literal backslash characters render correctly in the
hash table output.

PowerShell

ConvertFrom-StringData "Message=Look in c:\\Windows\\System32"

Name Value

---- -----

Message Look in c:\Windows\System32

Parameters
-StringData

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 contains 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. ConvertFrom-StringData ignores single-line comments. The
# character must be the first
non-whitespace character on the line. All characters on

the line after the # are ignored. The


comments are not included in the hash table.

A here-string is a string consisting of one or more lines. Quotation marks within the
here-string
are interpreted literally as part of the string data. For more information,
see
about_Quoting_Rules.
Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

Inputs
String

You can pipe a string containing a key-value pair to this cmdlet.

Outputs
Hashtable

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

This cmdlet 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.
Convert-String
Reference
Module: Microsoft.PowerShell.Utility

Formats a string to match examples.

Syntax
PowerShell

Convert-String

[-Example
<System.Collections.Generic.List`1[System.Management.Automation.PSObject]>]

-InputObject <String>

[<CommonParameters>]

Description
The cmdlet formats a string to match the format of examples.

Examples

Example 1: Convert format of a string


PowerShell

"Mu Han", "Jim Hance", "David Ahs", "Kim Akers" | Convert-String -Example
"Ed Wilson=Wilson, E."

Han, M.

Hance, J.

Ahs, D.

Akers, K.

The first command creates an array that contains first and last names.

The second command formats the names according to the example. It puts the surname
first in the
output, followed by an initial.

Example 2: Simplify format of a string


PowerShell

$composers = @("Johann Sebastian Bach", "Wolfgang Amadeus Mozart", "Frederic


Francois Chopin", "Johannes Brahms")

$composers | Convert-String -Example "first middle last=last, first"

Bach, Johann

Mozart, Wolfgang

Chopin, Frederic

Brahms, Johannes

The first command creates an array that contains first, middle and last names. Note that
the last
entry has no middle name.

The second command formats the names according to the example. It puts the last
name first in the
output, followed by the first name. All middle names removed; entry
without middle name is handled
correctly.

Example 3: Output management when strings don't


match example
PowerShell

$composers = @("Johann Sebastian Bach", "Wolfgang Amadeus Mozart", "Frederic


Francois Chopin", "Johannes Brahms")

$composers | Convert-String -Example "first middle last=middle, first"

Sebastian, Johann

Amadeus, Wolfgang

Francois, Frederic

The first command creates an array that contains first, middle and last names. Note that
the last
entry has no middle name.

The second command formats the names according to the example. It puts the middle
name first in
the output, followed by the first name. The last entry in $Composers is
skipped, because it
doesn't match the sample pattern: it has no middle name.

Example 4: Caution with beauty spaces


PowerShell

$composers = @("Antonio Vivaldi", "Richard Wagner ", "Franz Schubert",


"Johannes Brahms ")

$composers | Convert-String -Example "Patti Fuller = Fuller, P."

Wagner, R.

Brahms, J.

The first command creates an array of first and last names. Note that second and fourth
items have
an extra trailing space, after the last name.

The second command converts all strings that match the sample pattern:
word, space,
word, and final trailing space, all of this before the equal sign( = ). Also, note
the leading
space in the output.

Example 5: Format process information with multiple


patterns
PowerShell

$ExamplePatterns = @(

@{before='"Hello","World"'; after='World: Hello'},

@{before='"Hello","1"'; after='1: Hello'},

@{before='"Hello-World","22"'; after='22: Hello-World'},

@{before='"hello world","333"'; after='333: hello world'}

$Processes = Get-Process | Select-Object -Property ProcessName, Id |


ConvertTo-Csv -NoTypeInformation

$Processes | Convert-String -Example $ExamplePatterns

Id: ProcessName

4368: AGSService

8896: Amazon Music Helper

4420: AppleMobileDeviceService

...

11140: git-bash

0: Idle

...

56: Secure System

...

13028: WmiPrvSE

2724: WUDFHost

2980: WUDFHost

3348: WUDFHost

$ExamplePatterns defines different expected patterns in the data, through examples.

The first pattern, @{before='"Hello","World"'; after='World: Hello'} ,


reads as follows:

expect strings where a word comes enclosed in double quotes, then a comma,
and then the second, and last, word enclosed in quotes;
with no spaces in the string. On the output: place second word first,
without quotes, then a single space, and then the first word, without quotes.

The second pattern, @{before='"Hello","1"'; after='1: Hello'} ,


reads as follows:

expect strings where a word comes enclosed in double quotes, then a comma,
and then a number enclosed in quotes;
with no spaces in the string. On the output: place the number first,
without quotes, then a single space, and then the word, without quotes.

The third pattern, @{before='"Hello-World","22"'; after='22: Hello-World'} ,


reads as
follows:

expect strings where two words with a hyphen in between come enclosed in
double quotes, then a comma, and then a number enclosed in quotes;
with no spaces between the comma and the third double quote.
On the output: place the number first, without quotes, then a single space,
and then the hyphenated words, without quotes.

The fourth, and final, pattern,


@{before='"hello world","333"'; after='333: hello
world'} ,
reads as follows:

expect strings where two words with a space in between come enclosed in
double quotes, then a comma, and then a number enclosed in quotes;
with no spaces between the comma and the third double quote.
On the output: place the number first, without quotes, then a single space,
and then the words with the space in between, without quotes.

The first command gets all processes by using the Get-Process cmdlet. The command
passes them to the
Select-Object cmdlet, which selects the process name and process
ID. At the end of the pipeline, the
command converts the output to comma separated
values, without type information, by using the
ConvertTo-Csv cmdlet. The command
stores the results in the $Processes variable. $Processes
now contains process names
and PID.

The second command specifies an example variable that changes the order of the input
items. The
command coverts each string in $Processes .

7 Note

The fourth pattern implicitly says that two or more words separated by spaces are
matched. Without
the fourth pattern, only the first word of the string enclosed in
double quotes is matched.
Parameters
-Example

Specifies a list of examples of the target format. Specify pairs separated by the equal
sign ( = ),
with the source pattern on the left and the target pattern on the right, as in
the following
examples:

-Example "Hello World=World, Hello"

-Example "Hello World=World: Hello",'"Hello","1"=1: Hello'

7 Note

The second example uses a list of patterns

Alternatively, specify a list of hash tables that contain Before and


After properties.

-Example @{before='"Hello","World"'; after='World: Hello'},

@{before='"Hello","1"'; after='1: Hello'}

U Caution

Avoid using spaces around the equal sign( = ), as they are treated as part of the
pattern.

Type: List<T>[PSObject]

Aliases: E

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies a string to format.

Type: String

Position: Named
Default value: None

Accept pipeline input: True

Accept wildcard characters: False

Inputs
String

You can pipe strings to this cmdlet.

Outputs
String

This cmdlet returns a string.

Related Links
ConvertFrom-String
ConvertTo-Csv
Get-Process
Out-String
Select-Object
ConvertTo-Csv
Reference
Module: Microsoft.PowerShell.Utility

Converts .NET objects into a series of character-separated value (CSV) strings.

Syntax
PowerShell

ConvertTo-Csv

[-InputObject] <psobject>

[[-Delimiter] <char>]

[-NoTypeInformation]

[<CommonParameters>]

PowerShell

ConvertTo-Csv

[-InputObject] <psobject>

[-UseCulture]

[-NoTypeInformation]

[<CommonParameters>]

Description
The ConvertTo-CSV cmdlet returns a series of character-separated value (CSV) strings
that
represent the objects that you submit. You can then use the ConvertFrom-Csv
cmdlet to recreate
objects from the CSV strings. The objects converted from CSV are
string values of the original
objects that contain property values and no methods.

You can use the Export-Csv cmdlet to convert objects to CSV strings. Export-CSV is
similar to
ConvertTo-CSV , except that it saves the CSV strings to a file.

The ConvertTo-CSV cmdlet has parameters to specify a delimiter other than a comma or
use the
current culture as the delimiter.

Examples

Example 1: Convert an object to CSV


This example converts a Process object to a CSV string.

PowerShell

Get-Process -Name 'PowerShell' | ConvertTo-Csv -NoTypeInformation

"Name","SI","Handles","VM","WS","PM","NPM","Path","Company","CPU","FileVersi
on", ...

"powershell","11","691","2204036739072","175943680","132665344","33312", ...

The Get-Process cmdlet gets the Process object and uses the Name parameter to
specify the
PowerShell process. The process object is sent down the pipeline to the
ConvertTo-CSV cmdlet. The
ConvertTo-CSV cmdlet converts the object to CSV strings.
The NoTypeInformation parameter
removes the #TYPE information header from the
CSV output.

Example 2: Convert a DateTime object to CSV


This example converts a DateTime object to a CSV string.

PowerShell

$Date = Get-Date

ConvertTo-Csv -InputObject $Date -Delimiter ';' -NoTypeInformation

"DisplayHint";"DateTime";"Date";"Day";"DayOfWeek";"DayOfYear";"Hour";"Kind";
"Millisecond";"Minute";"Month";"Second";"Ticks";"TimeOfDay";"Year"

"DateTime";"Friday, January 4, 2019 14:40:51";"1/4/2019


00:00:00";"4";"Friday";"4";"14";"Local";"711";"40";"1";"51";"636822096517114
991";"14:40:51.7114991";"2019"

The Get-Date cmdlet gets the DateTime object and saves it in the $Date variable. The
ConvertTo-Csv cmdlet converts the DateTime object to strings. The InputObject

parameter
uses the DateTime object stored in the $Date variable. The Delimiter
parameter specifies
a semicolon to separate the string values. The NoTypeInformation
parameter removes the
#TYPE information header from the CSV output.

Example 3: Convert the PowerShell event log to CSV


This example converts the Windows event log for PowerShell to a series of CSV strings.

PowerShell

(Get-Culture).TextInfo.ListSeparator

Get-WinEvent -LogName 'Windows PowerShell' | ConvertTo-Csv -UseCulture -


NoTypeInformation

"Message","Id","Version","Qualifiers","Level","Task","Opcode","Keywords","Re
cordId", ...

"Error Message = System


error","403",,"0","4","4",,"36028797018963968","46891","PowerShell", ...

The Get-Culture cmdlet uses the nested properties TextInfo and ListSeparator and
displays
the current culture's default list separator. The Get-WinEvent cmdlet gets the
event log objects
and uses the LogName parameter to specify the log file name. The
event log objects are sent down
the pipeline to the ConvertTo-Csv cmdlet. The
ConvertTo-Csv cmdlet converts the event log
objects to a series of CSV strings. The

UseCulture parameter uses the current culture's default


list separator as the delimiter.
The NoTypeInformation parameter removes the #TYPE
information header from the
CSV output.

Parameters
-Delimiter

Specifies the delimiter to separate the property values in CSV strings. The default is a
comma
( , ). Enter a character, such as a colon ( : ). To specify a semicolon ( ; ) enclose
it in single
quotation marks.

Type: Char

Position: 1

Default value: comma (,)

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies the objects that are converted to 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 .

Type: PSObject

Position: 0
Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-NoTypeInformation

Removes the #TYPE information header from the output. This parameter became the
default in
PowerShell 6.0 and is included for backwards compatibility.

Type: SwitchParameter

Aliases: NTI

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-UseCulture

Uses the list separator for the current culture as the item delimiter. To find the list
separator
for a culture, use the following command: (Get-
Culture).TextInfo.ListSeparator .

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSObject

You can pipe any object that has an Extended Type System (ETS) adapter to this cmdlet.

Outputs
String

This cmdlet returns one or more strings representing each converted object.

Notes
In CSV format, each object is represented by a character-separated list of its property
value. The
property values are converted to strings using the object's ToString() method.
The strings are
represented by the property value name. ConvertTo-CSV does not export
the object's methods.

The CSV strings are output as follows:

By default the first string contains the #TYPE information header followed by the
object
type's fully qualified name. For example, #TYPE System.Diagnostics.Process.
If NoTypeInformation is used the first string includes the column headers. The
headers
contain the first object's property names as a comma-separated list.
The remaining strings contain comma-separated lists of each object's property
values.

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.

Related Links
ConvertFrom-Csv
Export-Csv
Import-Csv
ConvertTo-Html
Reference
Module: Microsoft.PowerShell.Utility

Converts .NET objects into HTML that can be displayed in a Web browser.

Syntax
PowerShell

ConvertTo-Html

[-InputObject <PSObject>]

[[-Property] <Object[]>]

[[-Body] <String[]>]

[[-Head] <String[]>]

[[-Title] <String>]
[-As <String>]

[-CssUri <Uri>]

[-PostContent <String[]>]

[-PreContent <String[]>]

[<CommonParameters>]

PowerShell

ConvertTo-Html

[-InputObject <PSObject>]

[[-Property] <Object[]>]

[-As <String>]

[-Fragment]

[-PostContent <String[]>]

[-PreContent <String[]>]

[<CommonParameters>]

Description
The ConvertTo-Html cmdlet converts .NET 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 , 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.

Examples

Example 1: Create a web page to display the date


PowerShell

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: Create a web page to display PowerShell


aliases
PowerShell

Get-Alias | ConvertTo-Html | Out-File aliases.htm

Invoke-Item aliases.htm

This command creates an HTML page that lists the 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. The command also uses
the Out-File cmdlet to send the HTML code to the
aliases.htm file.

Example 3: Create a web page to display PowerShell


events
PowerShell
Get-EventLog -LogName "Windows PowerShell" | ConvertTo-Html | Out-File
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
Out-File cmdlet to send the HTML code to the pslog.htm
file.

The command also uses the Out-File cmdlet to send the HTML code to the pslog.htm
file.

Example 4: Create a web page to display processes


PowerShell

Get-Process |

ConvertTo-Html -Property Name, Path, Company -Title "Process Information"


|

Out-File proc.htm

Invoke-Item 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 Out-File cmdlet to send the
resulting HTML to a file named
Proc.htm .

The second command uses the Invoke-Item cmdlet to open the Proc.htm in the default
browser.

Example 5: Create a web page to display service objects


PowerShell
Get-Service | ConvertTo-Html -CssUri "test.css"

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"


"https://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html>

<head>

<title>HTML TABLE</title>

<link rel="stylesheet" type="text/css" href="test.css" />

...

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"
href="test.css"> tag to the resulting HTML. The HREF
attribute in the tag contains the

name of the style sheet.

Example 6: Create a web page to display service objects


PowerShell

Get-Service | ConvertTo-Html -As LIST | Out-File 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 cmdlet Out-
File sends the
resulting HTML to the Services.htm file.

Example 7: Create a web table for the current date


PowerShell

Get-Date | ConvertTo-Html -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>

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.

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: Create a web page to display PowerShell


events
PowerShell

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: Create a web page to display specified


services
PowerShell

$htmlParams = @{

Title = "Windows Services: Server01"

Body = Get-Date

PreContent = "<P>Generated by Corporate IT</P>"

PostContent = "For details, contact Corporate IT."

Get-Service A* |

ConvertTo-Html @htmlParams |

Out-File Services.htm

Invoke-Item 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 also uses the Out-File cmdlet 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 to open the Services.htm file in the default browser.

Parameters
-As

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 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 PowerShell
list format. The first column displays the property name. The second
column displays the property
value.

Type: String

Accepted values: Table, List

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Body

Specifies the text to add after the opening <BODY> tag. By default, there is no text in
that
position.
Type: String[]

Position: 3

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-CssUri

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.

Type: Uri

Aliases: cu, uri

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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Head

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.

Type: String[]
Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

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. To create a table of the individual objects, use the pipeline
operator to pipe the objects
to ConvertTo-Html .

Type: PSObject

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-PostContent

Specifies text to add after the closing </TABLE> tag. By default, there is no text in that
position.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-PreContent

Specifies text to add before the opening <TABLE> tag. By default, there is no text in
that
position.
Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Property

Includes the specified properties of the objects in the HTML. The value of the
Property
parameter can be a new calculated property. The calculated property can
be a script block or a hash
table. Valid key-value pairs are:

Expression - <string> or <script block>

FormatString - <string>
Width - <int32> - must be greater than 0

Alignment - value can be Left , Center , or Right

For more information, see


about_Calculated_Properties.

Type: Object[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Title

Specifies a title for the HTML file, that is, the text that appears between the <TITLE>
tags.

Type: String

Position: 2

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


Inputs
PSObject

You can pipe any object to this cmdlet.

Outputs
String

This cmdlet returns an array of strings of HTML representing the converted object.

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, 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 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"


"https://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"\>

Related Links
about_Calculated_Properties
ConvertTo-Csv
ConvertTo-Json
ConvertTo-Xml
Export-Clixml
Import-Clixml
ConvertTo-Json
Reference
Module: Microsoft.PowerShell.Utility

Converts an object to a JSON-formatted string.

Syntax
PowerShell

ConvertTo-Json

[-InputObject] <Object>

[-Depth <Int32>]

[-Compress]

[<CommonParameters>]

Description
The ConvertTo-Json cmdlet converts any .NET object to a string in JavaScript Object
Notation
(JSON) format. The properties are converted to field names, the field values are
converted to
property values, and the methods are removed.

You can then use the ConvertFrom-Json cmdlet to convert a JSON-formatted string to a
JSON
object, which is easily managed in PowerShell.

Many web sites use JSON instead of XML to serialize data for communication between
servers and
web-based apps.

This cmdlet was introduced in Windows PowerShell 3.0.

Examples

Example 1
PowerShell

(Get-UICulture).Calendar | ConvertTo-Json

"MinSupportedDateTime": "\/Date(-62135596800000)\/",

"MaxSupportedDateTime": "\/Date(253402300799999)\/",

"AlgorithmType": 1,

"CalendarType": 1,

"Eras": [

],

"TwoDigitYearMax": 2029,

"IsReadOnly": false

This command uses the ConvertTo-Json cmdlet to convert a GregorianCalendar object


to a
JSON-formatted string.

Example 2
PowerShell

@{Account="User01";Domain="Domain01";Admin="True"} | ConvertTo-Json -
Compress

{"Domain":"Domain01","Account":"User01","Admin":"True"}

This command shows the effect of using the Compress parameter of ConvertTo-Json .
The
compression affects only the appearance of the string, not its validity.

Example 3
PowerShell

Get-Date | Select-Object -Property * | ConvertTo-Json

"DisplayHint": 2,

"DateTime": "Friday, January 13, 2012 8:06:16 PM",

"Date": "\/Date(1326441600000)\/",

"Day": 13,

"DayOfWeek": 5,

"DayOfYear": 13,

"Hour": 20,

"Kind": 2,

"Millisecond": 221,

"Minute": 6,

"Month": 1,

"Second": 16,

"Ticks": 634620819762218083,

"TimeOfDay": {

"Ticks": 723762218083,

"Days": 0,

"Hours": 20,

"Milliseconds": 221,

"Minutes": 6,

"Seconds": 16,

"TotalDays": 0.83768775241087956,

"TotalHours": 20.104506057861109,
"TotalMilliseconds": 72376221.8083,

"TotalMinutes": 1206.2703634716668,

"TotalSeconds": 72376.22180829999
},

"Year": 2012

This example uses the ConvertTo-Json cmdlet to convert a System.DateTime object


from the
Get-Date cmdlet to a JSON-formatted string. The command uses the Select-
Object cmdlet to get all
( * ) of the properties of the DateTime object. The output shows

the JSON string that


ConvertTo-Json returned.

Example 4
PowerShell

Get-Date | Select-Object -Property * | ConvertTo-Json | ConvertFrom-Json

DisplayHint : 2

DateTime : October 12, 2018 10:55:52 PM

Date : 2018-10-12 12:00:00 AM


Day : 12

DayOfWeek : 5

DayOfYear : 285

Hour : 22

Kind : 2

Millisecond : 768

Minute : 55

Month : 10

Second : 52

Ticks : 636749817527683372

TimeOfDay : @{Ticks=825527683372; Days=0; Hours=22; Milliseconds=768;


Minutes=55; Seconds=52;

TotalDays=0.95547185575463; TotalHours=22.9313245381111;
TotalMilliseconds=82552768.3372;

TotalMinutes=1375.87947228667; TotalSeconds=82552.7683372}

Year : 2018

This example shows how to use the ConvertTo-Json and ConvertFrom-Json cmdlets to
convert an
object to a JSON string and a JSON object.

Parameters
-Compress

Omits white space and indented formatting in the output string.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Depth

Specifies how many levels of contained objects are included in the JSON
representation. The value
can be any number from 1 to 100 . The default value is 2 .
ConvertTo-Json emits a
warning if the number of levels in an input object exceeds

this number.

Type: Int32

Position: Named

Default value: 2

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies the objects to convert to JSON format. Enter a variable that contains the
objects, or type
a command or expression that gets the objects. You can also pipe an
object to ConvertTo-Json .

The InputObject parameter is required, but its value can be null ( $null ) or an empty
string.
When the input object is $null , ConvertTo-Json does not generate any
output. When the input
object is an empty string, ConvertTo-Json returns an empty
string.

Type: Object

Position: 0

Default value: None


Accept pipeline input: True

Accept wildcard characters: False

Inputs
Object

You can pipe any object to this cmdlet.

Outputs
String

This cmdlet returns a string representing the input object converted to a JSON string.

Notes
The ConvertTo-Json cmdlet is implemented using the
JavaScriptSerializer class.

Related Links
An Introduction to JavaScript Object Notation (JSON) in JavaScript and .NET
ConvertFrom-Json
Get-Content
Get-UICulture
Invoke-WebRequest
Invoke-RestMethod
ConvertTo-Xml
Reference
Module: Microsoft.PowerShell.Utility

Creates an XML-based representation of an object.

Syntax
PowerShell

ConvertTo-Xml

[-Depth <Int32>]

[-InputObject] <PSObject>

[-NoTypeInformation]

[-As <String>]

[<CommonParameters>]

Description
The ConvertTo-Xml cmdlet creates an XML-based representation
of one or more .NET
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, in-memory XML document that
includes
representations of all the objects.

This cmdlet is similar to Export-Clixml except that Export-Clixml stores the


resulting
XML in a
Common Language Infrastructure (CLI)
file that can be reimported as objects
with Import-Clixml. ConvertTo-Xml
returns an in-memory representation of an XML
document, so you can continue to process it in
PowerShell. ConvertTo-Xml doesn't have
an option to convert objects to CLI XML.

Examples

Example 1: Convert a date to XML


PowerShell
Get-Date | ConvertTo-Xml

This command converts the current date (a DateTime object) to XML.

Example 2: Convert processes to XML


PowerShell

ConvertTo-Xml -As "Document" -InputObject (Get-Process) -Depth 3

This command converts the process objects that represent all the processes on the
computer into an
XML document. The objects are expanded to a depth of three levels.

Parameters
-As

Determines the output format. The acceptable values for this parameter are:

String - Returns a single string.


Stream - Returns an array of strings.

Document - Returns an XmlDocument object.

The default value is Document .

Type: String

Accepted values: Stream, String, Document

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Depth

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.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

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 .

Type: PSObject

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-NoTypeInformation

Omits the Type attribute from the object nodes.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


Inputs
PSObject

You can pipe any object to this cmdlet

Outputs
String

When you use the As parameter and set the value to string , this cmdlet returns the
XML as a
string. When the value is stream , this cmdlet returns an array of strings.

XmlDocument

By default, this cmdlet returns an XML document.

Related Links
ConvertTo-Csv
ConvertTo-Html
Export-Clixml
Get-Date
Import-Clixml
Debug-Runspace
Reference
Module: Microsoft.PowerShell.Utility

Starts an interactive debugging session with a runspace.

Syntax
PowerShell

Debug-Runspace

[-Runspace] <Runspace>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Debug-Runspace

[-Name] <String>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Debug-Runspace

[-Id] <Int32>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Debug-Runspace

[-InstanceId] <Guid>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Debug-Runspace cmdlet starts an interactive debugging session with a local or
remote active
runspace. You can find a runspace that you want to debug by first running
Get-Process to find
processes associated with PowerShell, then Enter-PSHostProcess

with the process ID specified in


the Id parameter to attach to the process, and then Get-
Runspace to list runspaces within the
PowerShell host process.

After you have selected a runspace to debug, if the runspace is currently running a
command or
script, or if the script has stopped at a breakpoint, PowerShell opens a
remote debugger session for
the runspace. You can debug the runspace script in the
same way remote session scripts are debugged.

You can only attach to a PowerShell host process if you are an administrator on the
computer that is
running the process, or you are running the script that you want to
debug. Also, you cannot enter
the host process that is running the current PowerShell
session. You can only enter a host process
that is running a different PowerShell session.

Examples

Example 1: Debug a remote runspace


In this example, you debug a runspace that is open on a remote computer,
WS10TestServer. In the
first line of the command, you run Get-Process on the remote
computer, and filter for Windows
PowerShell host processes. In this example, you want
to debug process ID 1152, the Windows
PowerShell ISE host process.

PowerShell

PS C:\> Get-Process -ComputerName "WS10TestServer" -Name "*powershell*"

Handles WS(K) VM(M) CPU(s) Id ProcessName

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

377 69912 63 2.09 2420 powershell

399 123396 829 4.48 1152 powershell_ise

PS C:\> Enter-PSSession -ComputerName "WS10TestServer"

[WS10TestServer]:PS C:\> Enter-PSHostProcess -Id 1152

[WS10TestServer:][Process:1152]: PS C:\Users\Test\Documents> Get-Runspace

Id Name ComputerName Type State Availability

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

1 Runspace1 WS10TestServer Remote Opened Available

2 RemoteHost WS10TestServer Remote Opened Busy

[WS10TestServer][Process:1152]: PS C:\Users\Test\Documents> Debug-Runspace -


Id 2

Hit Line breakpoint on 'C:\TestWFVar1.ps1:83'

At C:\TestWFVar1.ps1:83 char:1

+ $scriptVar = "Script Variable"

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

[Process:1152]: [RSDBG: 2]: PS C:\> >

In the second command, you run Enter-PSSession to open a remote session on


WS10TestServer. In the
third command, you attach to the Windows PowerShell ISE host
process running on the remote server by
running Enter-PSHostProcess , and specifying
the ID of the host process that you obtained in the
first command, 1152.

In the fourth command, you list available runspaces for process ID 1152 by running Get-
Runspace .
You note the ID number of the Busy runspace; it is running a script that you
want to debug.

In the last command, you start debugging an opened runspace that is running a script,
TestWFVar1.ps1 , by running Debug-Runspace , and identifying the runspace by its ID, 2, by
adding
the Id parameter. Because there's a breakpoint in the script, the debugger
opens.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: True

Accept pipeline input: False

Accept wildcard characters: False

-Id

Specifies the ID number of a runspace. You can run Get-Runspace to show runspace
IDs.

Type: Int32
Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InstanceId

Specifies a runspace by its instance ID, a GUID that you can show by running Get-
Runspace .

Type: Guid

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Name

Specifies a runspace by its name. You can run Get-Runspace to show the names of
runspaces.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Runspace

Specifies a runspace object. The simplest way to provide a value for this parameter is
to specify a
variable that contains the results of a filtered Get-Runspace command.

Type: Runspace

Position: 0

Default value: None


Accept pipeline input: True

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: True

Accept pipeline input: False

Accept wildcard characters: False

Inputs
Runspace

You can pipe the results of a Get-Runspace command to this cmdlet.

Notes
Debug-Runspace works on runspaces that are in the Opened state. If a runspace state
changes from
Opened to another state, that runspace is automatically removed from
the running list. A runspace is
added to the running list only if it meets the following
criteria.

If it is coming from Invoke-Command; that is, it has an Invoke-Command GUID ID.


If it is coming from Debug-Runspace ; that is, it has a Debug-Runspace GUID ID.
If it is coming from a PowerShell workflow, and its workflow job ID is the same as
the current
active debugger workflow job ID.

Related Links
about_Debuggers
Debug-Job
Get-Runspace
Get-Process
Enter-PSHostProcess
Enter-PSSession
Disable-PSBreakpoint
Reference
Module: Microsoft.PowerShell.Utility

Disables the breakpoints in the current console.

Syntax
PowerShell

Disable-PSBreakpoint

[-PassThru]

[-Breakpoint] <Breakpoint[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Disable-PSBreakpoint

[-PassThru]

[-Id] <Int32[]>

[-WhatIf]

[-Confirm]

[<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 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
PowerShell scripts. For more information about the PowerShell
debugger, see
about_Debuggers.
Examples

Example 1: Set a breakpoint and disable it


These commands disable a newly-created breakpoint.

PowerShell

$B = Set-PSBreakpoint -Script "sample.ps1" -Variable "name"

$B | Disable-PSBreakpoint

The Set-PSBreakpoint cmdlet creates a breakpoint on the $Name variable in the


Sample.ps1
script and saves the breakpoint object in the $B variable. The Disable-
PSBreakpoint cmdlet
disables 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: Disable a breakpoint


This command disables the breakpoint with breakpoint ID 0.

PowerShell

Disable-PSBreakpoint -Id 0

Example 3: Create a disabled breakpoint


This command creates a new breakpoint that is disabled until you enable it.

PowerShell

Disable-PSBreakpoint -Breakpoint ($B = Set-PSBreakpoint -Script "sample.ps1"


-Line 5)

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.

Example 4: Disable all breakpoints in the current console


This command disables all breakpoints in the current console.

PowerShell

`Get-PSBreakpoint` | Disable-PSBreakpoint

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

Type: Breakpoint[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False


Accept wildcard characters: False

-Id

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 .

Type: Int32[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-PassThru

Returns an object representing the enabled breakpoints. By default, this cmdlet does
not generate
any output.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


Inputs
Breakpoint

You can pipe a breakpoint object to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

Breakpoint

When you use the PassThru parameter, this cmdlet returns a breakpoint object
representing the
disabled breakpoint.

Notes
Windows PowerShell includes the following aliases for Disable-PSBreakpoint :

dbp

Related Links
Enable-PSBreakpoint
Get-PSBreakpoint
Get-PSCallStack
Remove-PSBreakpoint
Set-PSBreakpoint
Disable-RunspaceDebug
Reference
Module: Microsoft.PowerShell.Utility

Disables debugging on one or more runspaces, and releases any pending debugger
stop.

Syntax
PowerShell

Disable-RunspaceDebug

[[-RunspaceName] <String[]>]

[<CommonParameters>]

PowerShell

Disable-RunspaceDebug

[-Runspace] <Runspace[]>

[<CommonParameters>]

PowerShell

Disable-RunspaceDebug

[-RunspaceId] <Int32[]>

[<CommonParameters>]

PowerShell

Disable-RunspaceDebug

[-RunspaceInstanceId] <Guid[]>

[<CommonParameters>]

PowerShell

Disable-RunspaceDebug

[[-ProcessName] <String>]

[[-AppDomainName] <String[]>]

[<CommonParameters>]

Description
The Disable-RunspaceDebug cmdlet disables debugging on one or more runspaces, and
releases any
pending debugger stop.

Examples

1: Disable the default runspace debugger


PowerShell

Disable-RunspaceDebug

Get-RunspaceDebug

Id Name Enabled BreakAll

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

1 Runspace1 False False

Parameters
-AppDomainName

The name of the application domain that hosts the PowerShell runspace.

Type: String[]

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ProcessName

The name of the process that hosts the PowerShell runspace.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-Runspace

One or more Runspace objects to be disabled.

Type: Runspace[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-RunspaceId

One or more Runspace Id numbers to be disabled.

Type: Int32[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RunspaceInstanceId

One or more Runspace GUIDs to be disabled.

Type: Guid[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RunspaceName

One or more Runspace names to be disabled.

Type: String[]

Position: 0
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Related Links
Enable-RunspaceDebug
Get-RunspaceDebug
Enable-PSBreakpoint
Reference
Module: Microsoft.PowerShell.Utility

Enables the breakpoints in the current console.

Syntax
PowerShell

Enable-PSBreakpoint

[-PassThru]

[-Id] <Int32[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Enable-PSBreakpoint

[-PassThru]

[-Breakpoint] <Breakpoint[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Enable-PSBreakpoint cmdlet re-enables disabled breakpoints. You can use it to
enable all
breakpoints, or specific breakpoints by providing breakpoint objects or IDs.

A breakpoint is a point in a script where execution stops temporarily so that you can
examine the
state of the script. Newly created breakpoints are automatically enabled,
but can be disabled using
Disable-PSBreakpoint .

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 PowerShell


scripts. For more
information about the PowerShell debugger, see
about_Debuggers.
Examples

Example 1: Enable all breakpoints


This example enables all breakpoints in the current session.

PowerShell

Get-PSBreakpoint | Enable-PSBreakpoint

Using aliases, this example can be abbreviated as gbp | ebp .

Example 2: Enable breakpoints by ID


This example enables multiple breakpoints using their breakpoint IDs.

PowerShell

Enable-PSBreakpoint -Id 0, 1, 5

Example 3: Enable a disabled breakpoint


This example re-enables a breakpoint that has been disabled.

PowerShell

$B = Set-PSBreakpoint -Script "sample.ps1" -Variable Name -PassThru

$B | Enable-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

AccessMode : Write

Variable : Name

Action :

Enabled : True

HitCount : 0

Id : 0

Script : C:\ps-test\sample.ps1

ScriptName : C:\ps-test\sample.ps1
Set-PSBreakpoint creates a breakpoint on the Name variable in the Sample.ps1 script

saving
the breakpoint object in the $B variable. The PassThru parameter displays the
value of the
Enabled property of the breakpoint is False.

Enable-PSBreakpoint re-enables the breakpoint. Again, using the PassThru parameter

we see that
the value of the Enabled property is True.

Example 4: Enable breakpoints using a variable


This example enables a set of breakpoints using the breakpoint objects.

PowerShell

$B = Get-PSBreakpoint -Id 3, 5

Enable-PSBreakpoint -Breakpoint $B

Get-PSBreakpoint gets the breakpoints and saves them in the $B variable. Using the
Breakpoint parameter, Enable-PSBreakpoint enables the breakpoints.

This example is equivalent to running Enable-PSBreakpoint -Id 3, 5 .

Parameters
-Breakpoint

Specifies the breakpoints to enable. Provide a variable containing breakpoints or a


command that
gets breakpoint objects, such as Get-PSBreakpoint . You can also pipe
breakpoint objects to
Enable-PSBreakpoint .

Type: Breakpoint[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.


Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Id

Specifies the Id numbers of the breakpoints to enable. The default value is all
breakpoints.
Provide the Id by number or in a variable. You can't pipe Id numbers to
Enable-PSBreakpoint . To find the Id of a breakpoint, use the Get-PSBreakpoint
cmdlet.

Type: Int32[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-PassThru

Returns an object representing the breakpoint being enabled. By default, this cmdlet
doesn't
generate any output.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet isn't run.
Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
Breakpoint

You can pipe a breakpoint object to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

Breakpoint

When you use the PassThru parameter, this cmdlet returns a breakpoint object
representing the
enabled breakpoint.

Notes
Windows PowerShell includes the following aliases for Enable-PSBreakpoint :

ebp

The Enable-PSBreakpoint cmdlet doesn't 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 don't
need to enable newly created breakpoints.

Related Links
Disable-PSBreakpoint
Get-PSBreakpoint
Get-PSCallStack
Remove-PSBreakpoint
Set-PSBreakpoint
Enable-RunspaceDebug
Reference
Module: Microsoft.PowerShell.Utility

Enables debugging on runspaces where any breakpoint is preserved until a debugger is


attached.

Syntax
PowerShell

Enable-RunspaceDebug

[-BreakAll]

[[-RunspaceName] <String[]>]

[<CommonParameters>]

PowerShell

Enable-RunspaceDebug

[-BreakAll]

[-Runspace] <Runspace[]>

[<CommonParameters>]

PowerShell

Enable-RunspaceDebug

[-BreakAll]

[-RunspaceId] <Int32[]>

[<CommonParameters>]

PowerShell

Enable-RunspaceDebug

[-RunspaceInstanceId] <Guid[]>

[<CommonParameters>]

PowerShell

Enable-RunspaceDebug

[[-ProcessName] <String>]

[[-AppDomainName] <String[]>]

[<CommonParameters>]
Description
The Enable-RunspaceDebug cmdlet enables debugging on runspaces where any
breakpoint is preserved
until a debugger is attached.

Examples

1: Enable the default runspace debugger


PowerShell

Enable-RunspaceDebug

Get-RunspaceDebug

Id Name Enabled BreakAll

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

1 Runspace1 True False

Parameters
-AppDomainName

The name of the application domain that hosts the PowerShell runspace.

Type: String[]

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-BreakAll

Causes any running command or script in the Runspace to stop in step mode,
regardless of whether a
debugger is currently attached. The script or command will
remain stopped until a debugger is
attached to debug the current stop point.

Type: SwitchParameter

Position: 1
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ProcessName

The name of the process that hosts the PowerShell runspace.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Runspace

One or more Runspace objects to be disabled.

Type: Runspace[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-RunspaceId

One or more Runspace Id numbers to be disabled.

Type: Int32[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-RunspaceInstanceId

One or more Runspace GUIDs to be disabled.

Type: Guid[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RunspaceName

One or more Runspace names to be disabled.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Related Links
Disable-RunspaceDebug
Get-RunspaceDebug
Export-Alias
Reference
Module: Microsoft.PowerShell.Utility

Exports information about currently defined aliases to a file.

Syntax
PowerShell

Export-Alias

[-Path] <String>

[[-Name] <String[]>]

[-PassThru]

[-As <ExportAliasFormat>]

[-Append]

[-Force]

[-NoClobber]

[-Description <String>]

[-Scope <String>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Export-Alias

-LiteralPath <String>

[[-Name] <String[]>]

[-PassThru]

[-As <ExportAliasFormat>]

[-Append]

[-Force]

[-NoClobber]

[-Description <String>]

[-Scope <String>]

[-WhatIf]

[-Confirm]

[<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 PowerShell profile.

Examples

Example 1: Export an alias


PowerShell

Export-Alias -Path "alias.csv"

This command exports current alias information to a file named Alias.csv in the current
directory.

Example 2: Export an alias unless the export file already


exists
PowerShell

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: Append aliases to a file


PowerShell

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: Export aliases as a script
PowerShell

Export-Alias -Path "alias.ps1" -As Script

Add-Content -Path $Profile -Value (Get-Content alias.ps1)

$S = New-PSSession -ComputerName Server01

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.

Parameters
-Append

Indicates that this cmdlet appends the output to the specified file, rather than
overwriting the existing contents of that file.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-As
Specifies the output format.
CSV is the default.
The acceptable values for this
parameter 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.

Type: ExportAliasFormat

Accepted values: Csv, Script

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Description

Specifies the description of the exported file.


The description appears as a comment
at the top of the file, following the header information.

Type: String

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-Force

Forces the command to run without asking for user confirmation.

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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-LiteralPath

Specifies the path to the output file.


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 PowerShell not to interpret any characters as escape sequences.

Type: String

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name
Specifies the names as an array of the aliases to export.
Wildcards are permitted.

By default, Export-Alias exports all aliases in the session or scope.

Type: String[]

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-NoClobber

Indicates that this cmdlet 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.

Type: SwitchParameter

Aliases: NoOverwrite

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-PassThru

Returns an object representing the item with which you are working.
By default, this
cmdlet does not generate any output.

Type: SwitchParameter

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Path

Specifies the path to the output file.


Wildcards are permitted, but the resulting path
value must resolve to a single file name.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Scope

Specifies the scope from which the aliases should be exported.


The acceptable values
for this parameter are:

Global
Local
Script
A number relative to the current scope (0 through the number of scopes where
0 is the current scope and 1 is its parent)

The default value is Local.


For more information, see about_Scopes.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs.


The cmdlet is not run.
Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

AliasInfo

When you use the PassThru parameter, this cmdlet returns an AliasInfo object
representing
the alias.

Notes
Windows PowerShell includes the following aliases for Export-Alias :

epal

You can only Export-Aliases to a file.

Related Links
Get-Alias
Import-Alias
New-Alias
Set-Alias
Export-Clixml
Reference
Module: Microsoft.PowerShell.Utility

Creates an XML-based representation of an object or objects and stores it in a file.

Syntax
PowerShell

Export-Clixml

[-Path] <String>

-InputObject <PSObject>

[-Depth <Int32>]

[-Force]

[-NoClobber]

[-Encoding <String>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Export-Clixml

-LiteralPath <String>

-InputObject <PSObject>

[-Depth <Int32>]

[-Force]

[-NoClobber]

[-Encoding <String>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Export-Clixml cmdlet creates a Common Language Infrastructure (CLI) XML-based
representation
of an object or objects and stores it in a file. You can then use the
Import-Clixml cmdlet to
recreate the saved object based on the contents of that file.
For more information about CLI, see Language independence.

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

A valuable use of Export-Clixml on Windows computers is to export credentials and


secure strings
securely as XML. For an example, see Example 3.

Examples

Example 1: Export a string to an XML file


This example creates an XML file that stores in the current directory, a representation of
the
string This is a test.

PowerShell

"This is a test" | Export-Clixml -Path .\sample.xml

The string This is a test is sent down the pipeline. Export-Clixml uses the Path
parameter
to create an XML file named sample.xml in the current directory.

Example 2: Export an object to an XML file


This example shows how to export an object to an XML file and then create an object by
importing the
XML from the file.

PowerShell

Get-Acl C:\test.txt | Export-Clixml -Path .\FileACL.xml

$fileacl = Import-Clixml -Path .\FileACL.xml

The Get-Acl cmdlet gets the security descriptor of the Test.txt file. It sends the object
down
the pipeline to pass the security descriptor to Export-Clixml . The XML-based
representation of the
object is stored in a file named FileACL.xml .

The Import-Clixml cmdlet creates an object from the XML in the FileACL.xml file. Then,
it saves
the object in the $fileacl variable.

Example 3: Encrypt an exported credential object


In this example, given a credential that you've stored in the $Credential variable by
running the
Get-Credential cmdlet, you can run the Export-Clixml cmdlet to save the
credential to disk.
) Important

Export-Clixml only exports encrypted credentials on Windows. On non-Windows


operating systems
such as macOS and Linux, credentials are exported in plain text.

PowerShell

$Credxmlpath = Join-Path (Split-Path $Profile) TestScript.ps1.credential

$Credential | Export-Clixml $Credxmlpath

$Credxmlpath = Join-Path (Split-Path $Profile) TestScript.ps1.credential

$Credential = Import-Clixml $Credxmlpath

The Export-Clixml cmdlet encrypts credential objects by using the Windows Data
Protection API.
The encryption ensures that only your user account on only that
computer can decrypt the contents of
the credential object. The exported CLIXML file
can't be used on a different computer or by a
different user.

In the example, the file in which the credential is stored is represented by


TestScript.ps1.credential . Replace TestScript with the name of the script with which
you're
loading the credential.

You send the credential object down the pipeline to Export-Clixml , and save it to the
path,
$Credxmlpath , that you specified in the first command.

To import the credential automatically into your script, run the final two commands. Run
Import-Clixml to import the secured credential object into your script. This import
eliminates the
risk of exposing plain-text passwords in your script.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False


Accept wildcard characters: False

-Depth

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.

Type: Int32

Position: Named

Default value: 2

Accept pipeline input: False

Accept wildcard characters: False

-Encoding

Specifies the type of encoding for the target file. The default value is Unicode.

The acceptable values for this parameter are as follows:

ASCII Uses ASCII (7-bit) character set.


BigEndianUnicode Uses UTF-16 with the big-endian byte order.

Default Uses the encoding that corresponds to the system's active code page

(usually ANSI).
OEM Uses the encoding that corresponds to the system's current OEM code

page.
Unicode Uses UTF-16 with the little-endian byte order.

UTF7 Uses UTF-7.

UTF8 Uses UTF-8.


UTF32 Uses UTF-32 with the little-endian byte order.

Type: String

Accepted values: ASCII, BigEndianUnicode, Default, OEM, Unicode, UTF7, UTF8,


UTF32

Position: Named

Default value: Unicode


Accept pipeline input: False

Accept wildcard characters: False

-Force

Forces the command to run without asking for user confirmation.

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.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

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 .

Type: PSObject

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-LiteralPath

Specifies the path to the file where the XML representation of the object will be
stored. Unlike
Path, the value of the LiteralPath parameter is used exactly as it's
typed. No characters
are interpreted as wildcards. If the path includes escape
characters, enclose it in single quotation
marks. Single quotation marks tell
PowerShell not to interpret any characters as escape sequences.

Type: String
Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-NoClobber

Indicates that the cmdlet doesn't overwrite the contents of an existing file. By
default, if a file
exists in the specified path, Export-Clixml overwrites the file without
warning.

Type: SwitchParameter

Aliases: NoOverwrite

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Path

Specifies the path to the file where the XML representation of the object will be
stored.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet isn't run.

Type: SwitchParameter
Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSObject

You can pipeline any object to this cmdlet.

Outputs
FileInfo

This cmdlet returns a FileInfo object representing the created file with the stored data.

Related Links
ConvertTo-Html
ConvertTo-Xml
Export-Csv
Import-Clixml
Join-Path
Securely Store Credentials on Disk
Use PowerShell to Pass Credentials to Legacy Systems
Windows.Security.Cryptography.DataProtection
Export-Csv
Reference
Module: Microsoft.PowerShell.Utility

Converts objects into a series of character-separated value (CSV) strings and saves the
strings to a
file.

Syntax
PowerShell

Export-Csv

[[-Path] <string>]

[[-Delimiter] <char>]

-InputObject <psobject>

[-LiteralPath <string>]

[-Force]

[-NoClobber]

[-Encoding <string>]

[-Append]

[-NoTypeInformation]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Export-Csv

[[-Path] <string>]

-InputObject <psobject>

[-LiteralPath <string>]

[-Force]

[-NoClobber]

[-Encoding <string>]

[-Append]

[-UseCulture]

[-NoTypeInformation]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Export-CSV cmdlet creates a CSV file of the objects that you submit. Each object is a
row that
includes a character-separated list of the object's property values. You can use
the Export-CSV
cmdlet to create spreadsheets and share data with programs that accept
CSV files as input.

Do not format objects before sending them to the Export-CSV cmdlet. If Export-CSV
receives
formatted objects the CSV file contains the format properties rather than the
object properties. To
export only selected properties of an object, use the Select-Object
cmdlet.

Examples

Example 1: Export process properties to a CSV file


This example selects Process objects with specific properties, exports the objects to a
CSV
file.

PowerShell

Get-Process -Name WmiPrvSE |

Select-Object -Property BasePriority,Id,SessionId,WorkingSet |


Export-Csv -Path .\WmiData.csv -NoTypeInformation

Import-Csv -Path .\WmiData.csv

BasePriority Id SessionId WorkingSet

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

8 976 0 20267008

8 2292 0 36786176

8 3816 0 30351360

8 8604 0 15011840

8 10008 0 8830976

8 11764 0 14237696

8 54632 0 9502720

The Get-Process cmdlet gets the Process objects. The Name parameter filters the
output to
include only the WmiPrvSE process objects. The process objects are sent down
the pipeline to the
Select-Object cmdlet. Select-Object uses the Property parameter
to select a subset of
process object properties. The process objects are sent down the
pipeline to the Export-Csv
cmdlet. Export-Csv converts the process objects to a series
of CSV strings. The Path parameter
specifies that the WmiData.csv file is saved in the
current directory. The NoTypeInformation
parameter removes the #TYPE information
header from the CSV output and is not required in
PowerShell 6. The Import-Csv cmdlet
uses the Path parameter to display the file located in the
current directory.
Example 2: Export processes to a comma-delimited file
This example gets Process objects and exports the objects to a CSV file.

PowerShell

Get-Process | Export-Csv -Path .\Processes.csv -NoTypeInformation

Get-Content -Path .\Processes.csv

"Name","SI","Handles","VM","WS","PM","NPM","Path","Parent","Company","CPU","
FileVersion", ...

"ApplicationFrameHost","4","511","2203597099008","35364864","21979136","3004
8", ...

The Get-Process cmdlet gets Process objects. The process objects are sent down the
pipeline to
the Export-Csv cmdlet. Export-Csv converts the process objects to a series
of CSV strings. The
Path parameter specifies that the Processes.csv file is saved in the
current directory. The
NoTypeInformation parameter removes the #TYPE information
header from the CSV output and is
not required in PowerShell 6. The Get-Content
cmdlet uses the Path parameter to display the
file located in the current directory.

Example 3: Export processes to a semicolon delimited file


This example gets Process objects and exports the objects to a file with a semicolon
delimiter.

PowerShell

Get-Process | Export-Csv -Path .\Processes.csv -Delimiter ';' -


NoTypeInformation

Get-Content -Path .\Processes.csv

"Name";"SI";"Handles";"VM";"WS";"PM";"NPM";"Path";"Parent";"Company";"CPU";"
FileVersion"; ...

"ApplicationFrameHost";"4";"509";"2203595321344";"34807808";"21770240";"2950
4"; ...

The Get-Process cmdlet gets Process objects. The process objects are sent down the
pipeline to
the Export-Csv cmdlet. Export-Csv converts the process objects to a series
of CSV strings. The
Path parameter specifies that the Processes.csv file is saved in the
current directory. The
Delimiter parameter specifies a semicolon to separate the string
values. The
NoTypeInformation parameter removes the #TYPE information header from
the CSV output and is
not required in PowerShell 6. The Get-Content cmdlet uses the
Path parameter to display the
file located in the current directory.
Example 4: Export processes using the current culture's
list separator
This example gets Process objects and exports the objects to a file. The delimiter is the
current culture's list separator.

PowerShell

(Get-Culture).TextInfo.ListSeparator

Get-Process | Export-Csv -Path .\Processes.csv -UseCulture -


NoTypeInformation

Get-Content -Path .\Processes.csv

"Name","SI","Handles","VM","WS","PM","NPM","Path","Parent","Company","CPU","
FileVersion", ...

"ApplicationFrameHost","4","511","2203597099008","35364864","21979136","3004
8", ...

The Get-Culture cmdlet uses the nested properties TextInfo and ListSeparator and
displays
the current culture's default list separator. The Get-Process cmdlet gets Process
objects. The
process objects are sent down the pipeline to the Export-Csv cmdlet.
Export-Csv converts the
process objects to a series of CSV strings. The Path parameter
specifies that the Processes.csv
file is saved in the current directory. The UseCulture
parameter uses the current culture's
default list separator as the delimiter. The
NoTypeInformation parameter removes the #TYPE
information header from the CSV
output and is not required in PowerShell 6. The Get-Content cmdlet
uses the Path
parameter to display the file located in the current directory.

Example 5: Export processes with type information


This example explains how to include the #TYPE header information in a CSV file. The
#TYPE
header is the default in versions prior to PowerShell 6.0.

PowerShell

Get-Process | Export-Csv -Path .\Processes.csv

Get-Content -Path .\Processes.csv

#TYPE System.Diagnostics.Process

"Name","SI","Handles","VM","WS","PM","NPM","Path","Company","CPU","FileVersi
on", ...

"ApplicationFrameHost","4","507","2203595001856","35139584","20934656","2950
4", ...
The Get-Process cmdlet gets Process objects. The process objects are sent down the
pipeline
to the Export-Csv cmdlet. Export-Csv converts the process objects to a series
of CSV strings.
The Path parameter specifies that the Processes.csv file is saved in the
current directory.
The Get-Content cmdlet uses the Path parameter to display the file
located in the current
directory.

Example 6: Export and append objects to a CSV file


This example describes how to export objects to a CSV file and use the Append
parameter to add
objects to an existing file.

PowerShell

$AppService = (Get-Service -DisplayName *Application* | Select-Object -


Property DisplayName, Status)

$AppService | Export-Csv -Path .\Services.Csv -NoTypeInformation

Get-Content -Path .\Services.Csv

$WinService = (Get-Service -DisplayName *Windows* | Select-Object -Property


DisplayName, Status)

$WinService | Export-Csv -Path .\Services.csv -NoTypeInformation -Append

Get-Content -Path .\Services.Csv

"DisplayName","Status"

"Application Layer Gateway Service","Stopped"

"Application Identity","Running"

"Windows Audio Endpoint Builder","Running"

"Windows Audio","Running"

"Windows Event Log","Running"

The Get-Service cmdlet gets service objects. The DisplayName parameter returns
services that
contain the word Application. The service objects are sent down the
pipeline to the Select-Object
cmdlet. Select-Object uses the Property parameter to
specify the DisplayName and
Status properties. The $AppService variable stores the
objects.

The $AppService objects are sent down the pipeline to the Export-Csv cmdlet. Export-
Csv
converts the service objects to a series of CSV strings. The Path parameter specifies

that the
Services.csv file is saved in the current directory. The NoTypeInformation
parameter removes
the #TYPE information header from the CSV output and is not
required in PowerShell 6. The
Get-Content cmdlet uses the Path parameter to display
the file located in the current
directory.

The Get-Service and Select-Object cmdlets are repeated for services that contain the
word
Windows. The $WinService variable stores the service objects. The Export-Csv
cmdlet uses the
Append parameter to specify that the $WinService objects are added to
the existing
Services.csv file. The Get-Content cmdlet is repeated to display the
updated file that includes
the appended data.

Example 7: Format cmdlet within a pipeline creates


unexpected results
This example shows why it is important not to use a format cmdlet within a pipeline.
When
unexpected output is received, troubleshoot the pipeline syntax.

PowerShell

Get-Date | Select-Object -Property DateTime, Day, DayOfWeek, DayOfYear |

Export-Csv -Path .\DateTime.csv -NoTypeInformation

Get-Content -Path .\DateTime.csv

"DateTime","Day","DayOfWeek","DayOfYear"

"Wednesday, January 2, 2019 14:59:34","2","Wednesday","2"

Get-Date | Format-Table -Property DateTime, Day, DayOfWeek, DayOfYear |

Export-Csv -Path .\FTDateTime.csv -NoTypeInformation

Get-Content -Path .\FTDateTime.csv

"ClassId2e4f51ef21dd47e99d3c952918aff9cd","pageHeaderEntry","pageFooterEntry
","autosizeInfo", ...

"033ecb2bc07a4d43b5ef94ed5a35d280",,,,"Microsoft.PowerShell.Commands.Interna
l.Format. ...

"9e210fe47d09416682b841769c78b8a3",,,,,

"27c87ef9bbda4f709f6b4002fa4af63c",,,,,

"4ec4f0187cb04f4cb6973460dfe252df",,,,,

"cf522b78d86c486691226b40aa69e95c",,,,,

The Get-Date cmdlet gets the DateTime object. The object is sent down the pipeline to
the
Select-Object cmdlet. Select-Object uses the Property parameter to select a
subset of object
properties. The object is sent down the pipeline to the Export-Csv
cmdlet. Export-Csv converts
the object to a CSV format. The Path parameter specifies
that the DateTime.csv file is saved in
the current directory. The NoTypeInformation
parameter removes the #TYPE information header
from the CSV output and is not
required in PowerShell 6. The Get-Content cmdlet uses the Path
parameter to display
the CSV file located in the current directory.

When the Format-Table cmdlet is used within the pipeline to select properties
unexpected results
are received. Format-Table sends table format objects down the
pipeline to the Export-Csv cmdlet
rather than the DateTime object. Export-Csv
converts the table format objects to a series of
CSV strings. The Get-Content cmdlet
displays the CSV file which contains the table format objects.

Example 8: Using the Force parameter to overwrite read-


only files
This example creates an empty, read-only file and uses the Force parameter to update
the file.

PowerShell

New-Item -Path .\ReadOnly.csv -ItemType File

Set-ItemProperty -Path .\ReadOnly.csv -Name IsReadOnly -Value $true

Get-Process | Export-Csv -Path .\ReadOnly.csv -NoTypeInformation

Export-Csv : Access to the path 'C:\ReadOnly.csv' is denied.

At line:1 char:15

+ Get-Process | Export-Csv -Path .\ReadOnly.csv -NoTypeInformation

+ ~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : OpenError: (:) [Export-Csv],


UnauthorizedAccessException

+ FullyQualifiedErrorId :
FileOpenFailure,Microsoft.PowerShell.Commands.ExportCsvCommand

Get-Process | Export-Csv -Path .\ReadOnly.csv -NoTypeInformation -Force

Get-Content -Path .\ReadOnly.csv

"Name";"SI";"Handles";"VM";"WS";"PM";"NPM";"Path";"Parent";"Company";"CPU";"
FileVersion"; ...

"ApplicationFrameHost";"4";"509";"2203595321344";"34807808";"21770240";"2950
4"; ...

The New-Item cmdlet uses the Path and ItemType parameters to create the
ReadOnly.csv
file in the current directory. The Set-ItemProperty cmdlet uses the Name

and Value
parameters to change the file's IsReadOnly property to true. The Get-Process
cmdlet gets
Process objects. The process objects are sent down the pipeline to the
Export-Csv cmdlet.
Export-Csv converts the process objects to a series of CSV strings.

The Path parameter


specifies that the ReadOnly.csv file is saved in the current directory.
The NoTypeInformation
parameter removes the #TYPE information header from the
CSV output and is not required in
PowerShell 6. The output shows that the file is not
written because access is denied.

The Force parameter is added to the Export-Csv cmdlet to force the export to write to
the
file. The Get-Content cmdlet uses the Path parameter to display the file located in
the
current directory.
Example 9: Using the Force parameter with Append
This example shows how to use the Force and Append parameters. When these
parameters are
combined, mismatched object properties can be written to a CSV file.

PowerShell

$Content = [PSCustomObject]@{Name = 'PowerShell'; Version = '7.0'}

$Content | Export-Csv -Path .\ParmFile.csv -NoTypeInformation

$AdditionalContent = [PSCustomObject]@{Name = 'Windows PowerShell'; Edition


= 'Desktop'}

$AdditionalContent | Export-Csv -Path .\ParmFile.csv -NoTypeInformation -


Append

Export-Csv : Cannot append CSV content to the following file: ParmFile.csv.

The appended object does not have a property that corresponds to the
following column:

Version. To continue with mismatched properties, add the -Force parameter,


and then retry

the command.

At line:1 char:22

+ $AdditionalContent | Export-Csv -Path .\ParmFile.csv -NoTypeInformation -


Append

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : InvalidData: (Version:String) [Export-Csv],


InvalidOperationException

+ FullyQualifiedErrorId :
CannotAppendCsvWithMismatchedPropertyNames,Microsoft.PowerShell. ...

$AdditionalContent | Export-Csv -Path .\ParmFile.csv -NoTypeInformation -


Append -Force

Import-Csv -Path .\ParmFile.csv

Name Version

---- -------

PowerShell 7.0

Windows PowerShell

An expression creates the PSCustomObject with Name and Version properties. The
values
are stored in the $Content variable. The $Content variable is sent down the
pipeline to the
Export-Csv cmdlet. Export-Csv uses the Path parameter and saves the
ParmFile.csv file in
the current directory. The NoTypeInformation parameter removes

the #TYPE information header


from the CSV output and is not required in PowerShell 6.

Another expression creates a PSCustomObject with the Name and Edition properties.
The
values are stored in the $AdditionalContent variable. The $AdditionalContent
variable is sent
down the pipeline to the Export-Csv cmdlet. The Append parameter is
used to add the data to
the file. The append fails because there is a property name
mismatch between Version and
Edition.

The Export-Csv cmdlet Force parameter is used to force the export to write to the file.
The
Edition property is discarded. The Import-Csv cmdlet uses the Path parameter to
display
the file located in the current directory.

Parameters
-Append

Use this parameter so that Export-CSV adds CSV output to the end of the specified
file. Without
this parameter, Export-CSV replaces the file contents without warning.

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Delimiter

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.

Type: Char

Position: 1

Default value: comma (,)

Accept pipeline input: False

Accept wildcard characters: False

-Encoding

Specifies the encoding for the exported CSV file. The default value is ASCII .

The acceptable values for this parameter are as follows:

ASCII Uses ASCII (7-bit) character set.


BigEndianUnicode Uses UTF-16 with the big-endian byte order.

Default Uses the encoding that corresponds to the system's active code page
(usually ANSI).
OEM Uses the encoding that corresponds to the system's current OEM code

page.
Unicode Uses UTF-16 with the little-endian byte order.

UTF7 Uses UTF-7.


UTF8 Uses UTF-8.

UTF32 Uses UTF-32 with the little-endian byte order.

Type: String

Accepted values: ASCII, BigEndianUnicode, Default, OEM, Unicode, UTF7, UTF8,


UTF32

Position: Named

Default value: ASCII

Accept pipeline input: False

Accept wildcard characters: False

-Force

This parameter allows Export-Csv to overwrite files with the Read Only attribute.
When Force and Append parameters are combined, objects that contain
mismatched properties
can be written to a CSV file. Only the properties that match
are written to the file. The mismatched
properties are discarded.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

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 .

Type: PSObject

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-LiteralPath

Specifies the path to the CSV output file. 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, use single quotation marks. Single quotation
marks tell PowerShell not
to interpret any characters as escape sequences.

Type: String

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-NoClobber

Use this parameter so that Export-CSV does not overwrite an existing file. By default,
if the file
exists in the specified path, Export-CSV overwrites the file without warning.

Type: SwitchParameter

Aliases: NoOverwrite

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-NoTypeInformation

Removes the #TYPE information header from the output. This parameter became the
default in
PowerShell 6.0 and is included for backwards compatibility.

Type: SwitchParameter

Aliases: NTI

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Path

A required parameter that specifies the location to save the CSV output file.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-UseCulture
Uses the list separator for the current culture as the item delimiter. To find the list
separator
for a culture, use the following command: (Get-
Culture).TextInfo.ListSeparator .

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Prevents the cmdlet from being processed or making changes. The output shows
what would happen if
the cmdlet were run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSObject

You can pipe any object with an Extended Type System (ETS) adapter to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
Windows PowerShell includes the following aliases for Export-Csv :

epcsv

The Export-CSV cmdlet converts the objects that you submit into a series of CSV 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 CSV file.

In the CSV file, each object is represented by a character-separated list of the property
values of
the object. The property values are converted to strings using the ToString()
method. The
strings are represented by the property value name. `Export-CSV does not
export the methods of the
object.

The CSV strings are output as follows:

By default the first string contains the #TYPE information header followed by the
object
type's fully qualified name. For example, #TYPE System.Diagnostics.Process.
If NoTypeInformation is used the first string includes the column headers. The
headers
contain the first object's property names as a character-separated list.
The remaining strings contain character-separated lists of each object's property
values.

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.

You can use the Import-Csv cmdlet to recreate 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.

The ConvertTo-Csv and ConvertFrom-Csv cmdlets convert objects to CSV strings and
from CSV
strings. Export-CSV is the same as ConvertTo-CSV , except that it saves the CSV
strings in a
file.

Related Links
ConvertFrom-Csv
ConvertTo-Csv
Format-Table
Import-Csv
Select-Object
Export-FormatData
Reference
Module: Microsoft.PowerShell.Utility

Saves formatting data from the current session in a formatting file.

Syntax
PowerShell

Export-FormatData

-InputObject <ExtendedTypeDefinition[]>

-Path <String>

[-Force]

[-NoClobber]

[-IncludeScriptBlock]

[<CommonParameters>]

PowerShell

Export-FormatData

-InputObject <ExtendedTypeDefinition[]>

-LiteralPath <String>

[-Force]

[-NoClobber]

[-IncludeScriptBlock]

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

Example 1: Export session format data


PowerShell

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: Export format data for a type


PowerShell

$F = Get-FormatData -TypeName "helpinfoshort"

Export-FormatData -InputObject $F -Path "c:\test\help.format.ps1xml" -


IncludeScriptBlock

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 cmdlet
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: Export format data without a script block


PowerShell

Get-FormatData -TypeName "System.Diagnostics.Process" | Export-FormatData -


Path process.format.ps1xml

Update-FormatData -PrependPath ".\process.format.ps1xml"

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

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.

Parameters
-Force

Forces the command to run without asking for user confirmation.

Type: SwitchParameter

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-IncludeScriptBlock

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

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

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 .

Type: ExtendedTypeDefinition[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-LiteralPath

Specifies a location for the output file. Unlike the Path parameter, 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.
Type: String

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-NoClobber

Indicates that the cmdlet does not overwrite 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.

Type: SwitchParameter

Aliases: NoOverwrite

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Path

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.

Type: String

Aliases: FilePath
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
ExtendedTypeDefinition

You can pipe ExtendedTypeDefinition objects from Get-FormatData to this cmdlet.

Outputs
None

This cmdlet returns no output. 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.

Related Links
Get-FormatData
Update-FormatData
Export-PSSession
Reference
Module: Microsoft.PowerShell.Utility

Exports commands from another session and saves them in a PowerShell module.

Syntax
PowerShell

Export-PSSession

[-Session] <PSSession>

[-OutputModule] <string>

[[-CommandName] <string[]>]
[[-FormatTypeName] <string[]>]

[-Force]

[-Encoding <string>]

[-AllowClobber]

[-ArgumentList <Object[]>]

[-CommandType <CommandTypes>]

[-Module <string[]>]

[-FullyQualifiedModule <ModuleSpecification[]>]

[-Certificate <X509Certificate2>]

[<CommonParameters>]

Description
The Export-PSSession cmdlet gets cmdlets, functions, aliases, and other command types
from
another PowerShell session (PSSession) on a local or remote computer and saves
them in a 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, 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.

To prevent command name conflicts, the default for Export-PSSession is to export all
commands,
except for commands that exist in the current session. You can use the
CommandName parameter to
specify the commands to export.

The Export-PSSession cmdlet uses the implicit remoting feature of 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.

Examples

Example 1: Export commands from a PSSession


This example creates a new PSSession from the local computer to the Server01
computer. All of the
commands, except those that exist in the current session, are
exported to the module named Server01
on the local computer. The export includes the
formatting data for the commands.

PowerShell

$S = New-PSSession -ComputerName Server01

Export-PSSession -Session $S -OutputModule Server01

The New-PSSession command creates a PSSession on the Server01 computer. The


PSSession is stored
in the $S variable. The Export-PSSession command exports the $S
variable's commands and
formatting data into the Server01 module.

Example 2: Export the Get and Set commands


This example exports all of the Get and Set commands from a server.

PowerShell

$S = New-PSSession -ConnectionUri https://exchange.microsoft.com/mailbox -


Credential exchangeadmin01@hotmail.com -Authentication Negotiate

Export-PSSession -Session $S -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\Modules directory makes it
accessible to all users of the
computer.

Example 3: Export commands from a remote computer


This example exports cmdlets from a PSSession on a remote computer and saves them
in a module on
the local computer. The cmdlets from the module are added to the
current session so that they can
be used.

PowerShell

$S = New-PSSession -ComputerName Server01 -Credential Server01\User01

Export-PSSession -Session $S -OutputModule TestCmdlets -Type Cmdlet -


CommandName *test* -FormatTypeName *

Remove-PSSession $S

Import-Module TestCmdlets

Get-Help Test*

Test-Files

The New-PSSession command creates a PSSession on the Server01 computer and saves
it in the $S
variable. The Export-PSSession command exports the cmdlets whose names
begin with Test from the
PSSession in $S to the TestCmdlets module on the local
computer.

The Remove-PSSession cmdlet deletes 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 the
session. The Import-Module cmdlet adds the cmdlets in the
TestCmdlets module to the current
session. The command can be run in any session at
any time.

The Get-Help cmdlet gets 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. The Test-Files cmdlet

was exported from the Server01 computer


and added to the session. The Test-Files
cmdlet runs in a remote session on the computer from
which the command was
imported. PowerShell creates a session from information that is stored in the
TestCmdlets module.

Example 4: Export and clobber commands in the current


session
This example exports commands that are stored in a variable into the current session.

PowerShell

Export-PSSession -Session $S -AllowClobber -OutputModule AllCommands


This Export-PSSession command exports all commands and all formatting data from the
PSSession in
the $S variable into the current session. The AllowClobber parameter
includes commands with
the same names as commands in the current session.

Example 5: Export commands from a closed PSSession


This example shows how to run the exported commands with special options when the
PSSession that
created the exported commands is closed.

If the original remote session is closed when a module is imported, the module will use
any open
remote session that connects to the originating computer. If there is no
current session to the
originating computer, the module will reestablish a session.

To run exported commands with special options in a remote session, you must create a
remote session
with those options before you import the module. Use the New-
PSSession cmdlet with the
SessionOption parameter

PowerShell

$Options = New-PSSessionOption -NoMachineProfile

$S = New-PSSession -ComputerName Server01 -SessionOption $Options

Export-PSSession -Session $S -OutputModule Server01

Remove-PSSession $S

New-PSSession -ComputerName Server01 -SessionOption $Options

Import-Module Server01

The New-PSSessionOption cmdlet creates a PSSessionOption object, and it saves the


object in
the $Options variable. The New-PSSession command creates a PSSession on
the Server01 computer.
The SessionOption parameter uses the object stored in
$Options . The session is stored in the
$S variable.

The Export-PSSession cmdlet exports commands from the PSSession in $S to the


Server01 module.
The Remove-PSSession cmdlet deletes the PSSession in the $S
variable.

The New-PSSession cmdlet creates a new PSSession that connects to the Server01
computer. The
SessionOption parameter uses the object stored in $Options . The
Import-Module cmdlet
imports the commands from the Server01 module. The
commands in the module are run in the PSSession
on the Server01 computer.

Parameters
-AllowClobber

Exports the specified commands, even if they have the same names as commands in
the current
session.

If you export a command with the same name as a command in the current session,
the exported
command hides or replaces the original commands. For more
information, see
about_Command_Precedence.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ArgumentList

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

Type: Object[]

Aliases: Args

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Certificate

Specifies the client certificate that is used to sign the format files (*.Format.ps1xml)
or script
module files (.psm1) in the module that Export-PSSession creates. Enter a
variable that contains
a certificate or a command or expression that gets the
certificate.
To find a certificate, use the Get-PfxCertificate cmdlet or use the Get-ChildItem
cmdlet in the
Certificate (Cert:) drive. If the certificate is not valid or does not have
sufficient authority,
the command fails.

Type: X509Certificate2

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-CommandName

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 commands from being hidden or
replaced by 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.

Type: String[]

Aliases: Name

Position: 2

Default value: All commands in the session.

Accept pipeline input: False

Accept wildcard characters: True

-CommandType

Exports only the specified types of command objects. Use CommandType or its alias,
Type.
The acceptable values for this parameter are as follows:

Alias : All PowerShell aliases in the current session.


All : All command types. It is the equivalent of Get-Command -Name * .

Application : All files other than 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.

Configuration : A PowerShell configuration. For more information, see


about_Session_Configurations.
ExternalScript : All .ps1 files in the paths listed in the Path environment
variable
( $env:path ).
Filter and Function : All PowerShell functions.

Script Script blocks in the current session.


Workflow A PowerShell workflow. For more information, see about_Workflows.

These values are defined as a flag-based enumeration. You can combine multiple
values together to
set multiple flags using this parameter. The values can be passed
to the CommandType parameter
as an array of values or as a comma-separated
string of those values. The cmdlet will combine the
values using a binary-OR
operation. Passing values as an array is the simplest option and also
allows you to
use tab-completion on the values.

Type: CommandTypes

Aliases: Type

Accepted values: Alias, All, Application, Cmdlet, Configuration, ExternalScript,


Filter, Function, Script, Workflow

Position: Named

Default value: All commands in the session.

Accept pipeline input: False

Accept wildcard characters: False

-Encoding

Specifies the type of encoding for the target file. The default value is UTF8 .

The acceptable values for this parameter are as follows:

ASCII : Uses ASCII (7-bit) character set.


BigEndianUnicode : Uses UTF-16 with the big-endian byte order.

Default ; Uses the encoding that corresponds to the system's active code page.
OEM : Uses the encoding that corresponds to the system's current OEM code

page.
Unicode : Uses UTF-16 with the little-endian byte order.

UTF7 : Uses UTF-7.

UTF8 : Uses UTF-8.


UTF32 : Uses UTF-32 with the little-endian byte order.

Type: String

Accepted values: ASCII, BigEndianUnicode, Default, OEM, Unicode, UTF7, UTF8,


UTF32

Position: Named

Default value: UTF8

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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-FormatTypeName

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.

If you use the CommandName parameter, the formatting files for the commands are
not exported
unless you use the FormatTypeName parameter.

Type: String[]

Position: 3

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-FullyQualifiedModule

The value can be a module name, a full module specification, or a path to a module
file.

When the value is a path, the path can be fully qualified or relative. A relative path is
resolved
relative to the script that contains the using statement.

When the value is a name or module specification, PowerShell searches the


PSModulePath for the
specified module.

A module specification is a hashtable that has the following keys.

ModuleName - Required Specifies the module name.

GUID - Optional Specifies the GUID of the module.


It's also Required to specify at least one of the three below keys.
ModuleVersion - Specifies a minimum acceptable version of the module.
MaximumVersion - Specifies the maximum acceptable version of the module.

RequiredVersion - Specifies an exact, required version of the module. This

can't be used with


the other Version keys.

You can't specify the FullyQualifiedModule parameter in the same command as a


Module
parameter. the two parameters are mutually exclusive.

Type: ModuleSpecification[]
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Module

Exports only the commands in the specified PowerShell snap-ins and modules. Enter
the snap-in and
module names. Wildcards are not permitted.

For more information, see Import-Module and


about_PSSnapins.

Type: String[]

Aliases: PSSnapin

Position: Named

Default value: All commands in the session.

Accept pipeline input: False

Accept wildcard characters: False

-OutputModule

Specifies an optional path and name for the module created by Export-PSSession .
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.

Type: String

Aliases: PSPath, ModuleName

Position: 1

Default value: $HOME\Documents\WindowsPowerShell\Modules

Accept pipeline input: False

Accept wildcard characters: False


-Session

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.

Type: PSSession

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
FileInfo

This cmdlet returns a list of files that comprise the module that it created.

Notes
Windows PowerShell includes the following aliases for Export-PSSession :

epsn

Export-PSSession relies on the 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 PowerShell provider.

Exported commands run implicitly in the PSSession from which they were exported. The
details of
running the commands remotely are handled entirely by PowerShell. You can
run the exported commands
just as you would run local commands.
Export-ModuleMember 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 recreate the PSSession. If attempts to recreate the
PSSession fail, the exported commands will
not run.

The session information that Export-ModuleMember captures and saves in the module
does not
include session options, such as those that you specify in the $PSSessionOption
preference
variable or by using the SessionOption parameter of the New-PSSession ,
Enter-PSSession , or
Invoke-Command cmdlets. 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 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.

Related Links
about_Command_Precedence
about_PSSessions
about_PSSnapins
about_Remote_Requirements
Import-Module
Import-PSSession
Invoke-Command
New-PSSession
New-PSSessionOption
Remove-PSSession
Format-Custom
Reference
Module: Microsoft.PowerShell.Utility

Uses a customized view to format the output.

Syntax
PowerShell

Format-Custom

[[-Property] <Object[]>]

[-Depth <Int32>]

[-GroupBy <Object>]

[-View <String>]

[-ShowError]

[-DisplayError]

[-Force]

[-Expand <String>]

[-InputObject <PSObject>]

[<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 PowerShell, or you can create your own views in a new
format.ps1xml file and use
the Update-FormatData cmdlet to add them to PowerShell.

Examples

Example 1: Format output with a custom view


PowerShell

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

Example 2: Format output with the default view


PowerShell

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.

Example 3: Troubleshooting format errors


The following examples show of the results of adding the DisplayError or ShowError
parameters with an expression.

PowerShell

PC /> Get-Date | Format-Custom DayOfWeek,{ $_ / $null } -DisplayError

class DateTime

DayOfWeek = Friday

$_ / $null = #ERR

PC /> Get-Date | Format-Custom DayOfWeek,{ $_ / $null } -ShowError

class DateTime

DayOfWeek = Friday

$_ / $null =

Failed to evaluate expression " $_ / $null ".

+ CategoryInfo : InvalidArgument: (12/21/2018 8:01:04 AM:PSObject)


[], RuntimeException

+ FullyQualifiedErrorId : PSPropertyExpressionError

Parameters
-Depth
Specifies the number of columns in the display.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-DisplayError

Displays errors at the command line. This parameter is rarely used, but can be used
as a debugging
aid when you are formatting expressions in a Format-Custom
command, and the expressions do not
appear to be working.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Expand

Formats the collection object, as well as the objects in the collection. This parameter
is designed
to format objects that support the System.Collections.ICollection
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 objects in the
collection.

Type: String

Accepted values: CoreOnly, EnumOnly, Both

Position: Named

Default value: EnumOnly


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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-GroupBy

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. The
calculated property can
be a script block or a hash table. Valid key-value pairs are:

Name (or Label) <string>


Expression <string> or <script block>
FormatString <string>

For more information, see


about_Calculated_Properties.

Type: Object

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject
Specifies the objects to be formatted. Enter a variable that contains the objects or
type a command
or expression that gets the objects.

Type: PSObject

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Property

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. The
calculated property
can be a script block or a hash table. Valid key-value pairs are:

Expression - <string> or <script block>


Depth - <int32>

For more information, see


about_Calculated_Properties.

Type: Object[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-ShowError

Sends errors through the pipeline. This parameter is rarely used, but can be used as a
debugging aid
when you are formatting expressions in a Format-Custom command,
and the expressions do not appear
to be working.

Type: SwitchParameter
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-View

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.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSObject

You can pipe any object to this cmdlet.

Outputs
Microsoft.PowerShell.Commands.Internal.Format

This cmdlet returns the format objects that represent the display.

Notes
Windows PowerShell includes the following aliases for Format-Custom :

fc

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 .

The GroupBy parameter assumes that the objects are sorted. Before using Format-
Custom to
group the objects, use Sort-Object to sort them.

Related Links
about_Calculated_Properties
Format-Hex
Format-List
Format-Table
Format-Wide
Get-Process
Format-Hex
Reference
Module: Microsoft.PowerShell.Utility

Displays a file or other input as hexadecimal.

Syntax
PowerShell

Format-Hex

[-Path] <string[]>

[<CommonParameters>]

PowerShell

Format-Hex

-LiteralPath <string[]>

[<CommonParameters>]

PowerShell

Format-Hex

-InputObject <Object>

[-Encoding <string>]

[-Raw]

[<CommonParameters>]

Description
The Format-Hex cmdlet displays a file or other input as hexadecimal values. To
determine the
offset of a character from the output, add the number at the leftmost of
the row to the number at
the top of the column for that character.

The Format-Hex cmdlet can help you determine the file type of a corrupted file or a file
that
might not have a filename extension. You can run this cmdlet, and then read the
hexadecimal output
to get file information.

When using Format-Hex on a file, the cmdlet ignores newline characters and returns the
entire
contents of a file in one string with the newline characters preserved.
Examples

Example 1: Get the hexadecimal representation of a string


This command returns the hexadecimal values of a string.

PowerShell

'Hello World' | Format-Hex

00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F

00000000 48 65 6C 6C 6F 20 57 6F 72 6C 64 Hello World

The string Hello World is sent down the pipeline to the Format-Hex cmdlet. The
hexadecimal
output from Format-Hex shows the values of each character in the string.

Example 2: Find a file type from hexadecimal output


This example uses the hexadecimal output to determine the file type. The cmdlet
displays the file's
full path and the hexadecimal values.

To test the following command, make a copy of an existing PDF file on your local
computer and rename
the copied file to File.t7f.

PowerShell

Format-Hex -Path .\File.t7f

Path: C:\Test\File.t7f

00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F

00000000 25 50 44 46 2D 31 2E 35 0D 0A 25 B5 B5 B5 B5 0D %PDF-1.5..%????.

00000010 0A 31 20 30 20 6F 62 6A 0D 0A 3C 3C 2F 54 79 70 .1 0 obj..<</Typ

00000020 65 2F 43 61 74 61 6C 6F 67 2F 50 61 67 65 73 20 e/Catalog/Pages

The Format-Hex cmdlet uses the Path parameter to specify a filename in the current
directory,
File.t7f . The file extension .t7f is uncommon, but the hexadecimal output
%PDF shows
that it is a PDF file.

Example 3: Display raw hexadecimal output


By default Format-Hex opts for compact output of numeric data types: single-byte or
double-byte
sequences are used if the value is small enough. The Raw parameter
deactivates this behavior.

PowerShell

PS> 1,2,3,1000 | Format-Hex

Path:

00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F

00000000 01 02 03 E8 03 ...è.

PS> 1,2,3,1000 | Format-Hex -Raw

Path:

00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F

00000000 01 00 00 00 02 00 00 00 03 00 00 00 E8 03 00 00 ............è...

Notice the difference in output. The Raw parameter displays the numbers as 4-byte
values, true
to their Int32 types.

Parameters
-Encoding

Specifies the encoding of the output. This only applies to [string] input. The
parameter has no
effect on numeric types. The default value is ASCII .

The acceptable values for this parameter are as follows:

Ascii Uses ASCII (7-bit) character set.


BigEndianUnicode Uses UTF-16 with the big-endian byte order.

Unicode Uses UTF-16 with the little-endian byte order.

UTF7 Uses UTF-7.


UTF8 Uses UTF-8.

UTF32 Uses UTF-32 with the little-endian byte order.

Non-ASCII characters in the input are output as literal ? characters resulting in a loss
of
information.
Type: String

Accepted values: ASCII, BigEndianUnicode, Unicode, UTF7, UTF8, UTF32

Position: Named

Default value: ASCII

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies the objects to be formatted. Enter a variable that contains the objects or
type a command
or expression that gets the objects.

Only certain scalar types and [system.io.fileinfo] are supported.

The supported scalar types are:

[string]
[byte]

[int] , [int32]
[long] , [int64]

Type: Object

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-LiteralPath

Specifies the complete path to a file. The value of LiteralPath is used exactly as it is
typed.
This parameter does not accept wildcard characters. To specify multiple paths
to files, separate the
paths with a comma. If the LiteralPath parameter includes
escape characters, enclose the path in
single quotation marks. PowerShell does not
interpret any characters in a single quoted string as
escape sequences. For more
information, see about_Quoting_Rules.

Type: String[]
Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Path

Specifies the path to files. Use a dot ( . ) to specify the current location. The wildcard
character
( * ) is accepted and can be used to specify all the items in a location. If the
Path parameter
includes escape characters, enclose the path in single quotation
marks. To specify multiple paths to
files, separate the paths with a comma.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Raw

By default Format-Hex opts for compact output of numeric data types: single-byte or
double-byte
sequences are used if the value is small enough. The Raw parameter
deactivates this behavior.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String
You can pipe a string to this cmdlet.

Outputs
ByteCollection

This cmdlet returns a ByteCollection. This object represents a collection of bytes. It


includes
methods that convert the collection of bytes to a string formatted like each line
of output returned
by Format-Hex . If you specify the Path or LiteralPath parameter, the
object also contains
the path of the file that contains each byte.

Notes
Windows PowerShell includes the following aliases for Format-Hex :

fhx

The right-most column of output tries to render the bytes as characters:

Generally, each byte is interpreted as a Unicode code point, which means that:

Printable ASCII characters are always rendered correctly


Multi-byte UTF-8 characters never render correctly
UTF-16 characters render correctly only if their high-order byte happens be NUL .

Related Links
about_Quoting_Rules
Format-Custom
Format-List
Format-Table
Format-Wide
Format-List
Reference
Module: Microsoft.PowerShell.Utility

Formats the output as a list of properties in which each property appears on a new line.

Syntax
PowerShell

Format-List

[[-Property] <Object[]>]

[-GroupBy <Object>]

[-View <string>]

[-ShowError]

[-DisplayError]

[-Force]

[-Expand <string>]

[-InputObject <psobject>]

[<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 -Property * ).

Because more space is available for each item in a list than in a table, PowerShell
displays more
properties of the object in the list, and the property values are less likely
to be truncated.

Examples

Example 1: Format computer services


PowerShell

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: Format PS1XML files


These commands display information about the PS1XML files in the PowerShell directory
as a list.

PowerShell

$A = Get-ChildItem $pshome\*.ps1xml

Format-List -InputObject $A

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: Format process properties by name


This command displays the name, base priority, and priority class of each process on the
computer.

PowerShell

Get-Process | Format-List -Property Name, BasePriority, PriorityClass

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: Format all properties for a process


This command displays all the properties of the Winlogon process.
PowerShell

Get-Process winlogon | Format-List -Property *

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.

Example 5: Troubleshooting format errors


The following examples show of the results of adding the DisplayError or ShowError
parameters with an expression.

PowerShell

PC /> Get-Date | Format-List DayOfWeek,{ $_ / $null } -DisplayError

DayOfWeek : Friday

$_ / $null : #ERR

PC /> Get-Date | Format-List DayOfWeek,{ $_ / $null } -ShowError

DayOfWeek : Friday

$_ / $null :

Failed to evaluate expression " $_ / $null ".

+ CategoryInfo : InvalidArgument: (12/21/2018 7:59:23 AM:PSObject)


[], RuntimeException

+ FullyQualifiedErrorId : PSPropertyExpressionError

Parameters
-DisplayError

Indicates that this cmdlet displays errors at the command line. This parameter is
rarely used, but
can be used as a debugging aid when you are formatting
expressions in a Format-List command, and
the expressions do not appear to be
working.

Type: SwitchParameter
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Expand

Specifies the formatted collection object, as well as the objects in the collection. This
parameter
is designed to format objects that support the
System.Collections.ICollection interface. The
default value is EnumOnly . The
acceptable values for this parameter 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.

Type: String

Accepted values: CoreOnly, EnumOnly, Both

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Force

Indicates that this cmdlet displays all the error information. Use with the DisplayError
or
ShowError parameter. By default, when an error object is written to the error or
display
streams, only some error information is displayed.

Also required when formatting certain .NET types. For more information, see the
Notes
section.

Type: SwitchParameter

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-GroupBy

Specifies 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. The
calculated property can
be a script block or a hash table. Valid key-value pairs are:

Name (or Label ) - <string>

Expression - <string> or <script block>


FormatString - <string>

For more information, see


about_Calculated_Properties.

Type: Object

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies the objects to be formatted. Enter a variable that contains the objects or
type a command
or expression that gets the objects.

Type: PSObject

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Property

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. The
calculated property
can be a script block or a hash table. Valid key-value pairs are:

Name (or Label ) - <string>

Expression - <string> or <script block>


FormatString - <string>

For more information, see


about_Calculated_Properties.

Type: Object[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-ShowError

Indicates that the cmdlet sends errors through the pipeline. This parameter is rarely
used, but can
be used as a debugging aid when you are formatting expressions in a
Format-List command, and the
expressions do not appear to be working.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-View

Specifies the name of an alternate list format or view. You cannot use the Property
and
View parameters in the same command.

Type: String

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSObject

You can pipe any object to this cmdlet.

Outputs
Microsoft.PowerShell.Commands.Internal.Format

This cmdlet returns the format objects that represent the list.

Notes
Windows PowerShell includes the following aliases for Format-List :

fl

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 PowerShell and by the cmdlets
that contain the Out
verb (the Out cmdlets), such as Out-Host or Out-File .

If you do not use a format cmdlet, PowerShell applies that default format for each object
that it
displays.

The GroupBy parameter assumes that the objects are sorted. Use Sort-Object before
using
Format-List to group the objects.

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 PowerShell directory, or you can create
your own views
in new PS1XML files and use the Update-FormatData cmdlet to include
them in PowerShell.

The alternate view for the View parameter must use the list format, otherwise, the
command
fails. If the alternate view is a table, use Format-Table . If the alternate view is
not a list or
a table, use Format-Custom .
If you want to use Format-List with the Property parameter, you need to include the
Force
parameter under any of the following conditions:

The input objects are formatted out-of-band using the ToString() method. This
applies to
[string] and .NET primitive types that are a superset of the built-in
numeric types such as
[int] , [long] , and others.

The input objects have no public properties.

The input objects are instances of the wrapper types PowerShell uses for output
streams other
than the Success output stream. This applies only when these
wrapper types are sent to the Success
output stream, which requires either having
captured them via common parameters such as
ErrorVariable first or using a
redirection such as *>&1 .

The wrapper types include:


System.Management.Automation.ErrorRecord
System.Management.Automation.WarningRecord
System.Management.Automation.VerboseRecord
System.Management.Automation.DebugRecord
System.Management.Automation.InformationRecord

Related Links
about_Calculated_Properties
Format-Custom
Format-Hex
Format-Table
Format-Wide
Format-Table
Reference
Module: Microsoft.PowerShell.Utility

Formats the output as a table.

Syntax
PowerShell

Format-Table

[[-Property] <Object[]>]

[-AutoSize]

[-RepeatHeader]

[-HideTableHeaders]

[-Wrap]

[-GroupBy <Object>]

[-View <string>]

[-ShowError]

[-DisplayError]

[-Force]

[-Expand <string>]

[-InputObject <psobject>]

[<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. You can use the Property parameter
to select the properties that you
want to display.

PowerShell uses default formatters to define how object types are displayed. You can
use .ps1xml
files to create custom views that display an output table with specified
properties. After a custom
view is created, use the View parameter to display the table
with your custom view. For more
information about views, see
about_Format.ps1xml.

You can 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 parameter. For more information about hash tables, see
about_Hash_Tables.
Examples

Example 1: Format PowerShell host


This example displays information about the host program for PowerShell in a table.

PowerShell

Get-Host | Format-Table -AutoSize

The Get-Host cmdlet gets System.Management.Automation.Internal.Host.InternalHost


objects that
represent the host. The objects are sent down the pipeline to Format-Table
and displayed in a
table. The AutoSize parameter adjusts the column widths to minimize
truncation.

Example 2: Format processes by BasePriority


In this example, processes are displayed in groups that have the same BasePriority
property.

PowerShell

Get-Process | Sort-Object -Property BasePriority | Format-Table -GroupBy


BasePriority -Wrap

The Get-Process cmdlet gets objects that represent each process on the computer and
sends them
down the pipeline to Sort-Object . The objects are sorted in the order of
their BasePriority
property.

The sorted objects are sent down the pipeline to Format-Table . The GroupBy parameter
arranges
the process data into groups based on their BasePriority property's value. The
Wrap
parameter ensures that data isn't truncated.

Example 3: Format processes by start date


This example displays information about the processes running on the computer. The
objects are
sorted and Format-Table uses a view to group the objects by their start date.

PowerShell

Get-Process | Sort-Object StartTime | Format-Table -View StartTime


Get-Process gets the System.Diagnostics.Process objects that represent the processes

running
on the computer. The objects are sent down the pipeline to Sort-Object , and
are sorted based on
the StartTime property.

The sorted objects are sent down the pipeline to Format-Table . The View parameter
specifies
the StartTime view that's defined in the PowerShell DotNetTypes.format.ps1xml
file for
System.Diagnostics.Process objects. The StartTime view converts each processes
start time to
a short date and then groups the processes by the start date.

The DotNetTypes.format.ps1xml file contains a Priority view for processes. You can
create your
own format.ps1xml files with customized views.

Example 4: Use a custom view for table output


In this example, a custom view displays a directory's contents. The custom view adds the
CreationTime column to the table output for System.IO.DirectoryInfo and
System.IO.FileInfo objects created by Get-ChildItem .

The custom view in this example was created from the view defined in PowerShell
source code. For
more information about views and the code used to create this
example's view, see
about_Format.ps1xml.

PowerShell

Get-ChildItem -Path C:\Test | Format-Table -View mygciview

Directory: C:\Test

Mode LastWriteTime CreationTime Length


Name

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


---

d----- 11/4/2019 15:54 9/24/2019 15:54


Archives

d----- 8/27/2019 14:22 8/27/2019 14:22


Drawings

d----- 10/23/2019 09:38 2/25/2019 09:38


Files

-a---- 11/7/2019 11:07 11/7/2019 11:07 11345


Alias.txt

-a---- 2/27/2019 15:15 2/27/2019 15:15 258


alias_out.txt

-a---- 2/27/2019 15:16 2/27/2019 15:16 258


alias_out2.txt
Get-ChildItem gets the contents of the current directory, C:\Test . The

System.IO.DirectoryInfo and System.IO.FileInfo objects are sent down the pipeline.


Format-Table uses the View parameter to specify the custom view mygciview that

includes
the CreationTime column.

The default Format-Table output for Get-ChildItem doesn't include the CreationTime
column.

Example 5: Use properties for table output


This example uses the Property parameter to display all the computer's services in a
two-column
table that shows the properties Name and DependentServices.

PowerShell

Get-Service | Format-Table -Property Name, DependentServices

Get-Service gets all the services on the computer and sends the
System.ServiceProcess.ServiceController objects down the pipeline. Format-Table uses
the
Property parameter to specify that the Name and DependentServices properties
are
displayed in the table.

Name and DependentServices are two of the object type's properties. To view all the
properties: Get-Service | Get-Member -MemberType Properties .

Example 6: Format a process and calculate its running


time
This example displays a table with the process name and total running time for the local
computer's
notepad processes. The total running time is calculated by subtracting the
start time of each
process from the current time.

PowerShell

Get-Process notepad |

Format-Table ProcessName, @{Label="TotalRunningTime"; Expression={(Get-


Date) - $_.StartTime}}

ProcessName TotalRunningTime

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

notepad 03:20:00.2751767

notepad 00:00:16.7710520
Get-Process gets all the local computer's notepad processes and sends the objects

down the
pipeline. Format-Table displays a table with two columns: ProcessName, a
Get-Process
property, and TotalRunningTime, a calculated property.

The TotalRunningTime property is specified by a hash table with two keys, Label and
Expression. The Label key specifies the property name. The Expression key specifies the
calculation. 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 7: Format Notepad processes


This example uses Get-CimInstance to get the running time for all notepad processes on
the
local computer. You can use Get-CimInstance with the ComputerName parameter
to get information
from remote computers.

PowerShell

$Processes = Get-CimInstance -Class win32_process -Filter


"name='notepad.exe'"

$Processes | Format-Table ProcessName, @{

Label = "Total Running Time"

Expression={(Get-Date) - $_.CreationDate}

ProcessName Total Running Time

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

notepad.exe 03:39:39.6260693

notepad.exe 00:19:56.1376922

Get-CimInstance gets instances of the WMI Win32_Process class that describes all the

local
computer's processes named notepad.exe. The process objects are stored in the
$Processes
variable.

The process objects in the $Processes variable are sent down the pipeline to Format-
Table , which
displays the ProcessName property and a new calculated property, Total
Running Time.

The command assigns the name of the new calculated property, Total Running Time, to
the
Label key. The Expression key's script block calculates how long the process has
been
running by subtracting the processes creation date from the current date. The
Get-Date cmdlet gets
the current date. The creation date is subtracted from the current
date. The result is the value of
Total Running Time.
Example 8: Troubleshooting format errors
The following examples show the results of adding the DisplayError or ShowError
parameters
with an expression.

PowerShell

Get-Date | Format-Table DayOfWeek,{ $_ / $null } -DisplayError

DayOfWeek $_ / $null

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

Wednesday #ERR

Get-Date | Format-Table DayOfWeek,{ $_ / $null } -ShowError

DayOfWeek $_ / $null

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

Wednesday

Failed to evaluate expression " $_ / $null ".

+ CategoryInfo : InvalidArgument: (11/27/2019


12:53:41:PSObject) [], RuntimeException

+ FullyQualifiedErrorId : mshExpressionError

Parameters
-AutoSize

Indicates that the cmdlet 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.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-DisplayError

Indicates that the cmdlet displays errors on the command line. This parameter can
be used as a
debugging aid when you're formatting expressions in a Format-Table
command and need to
troubleshoot the expressions.
Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Expand

Specifies the format of the collection object and the objects in the collection. This
parameter is
designed to format objects that support the
ICollection
(System.Collections) interface. The default value is EnumOnly.
The acceptable values
for this parameter are as follows:

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.

Type: String

Accepted values: CoreOnly, EnumOnly, Both

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Force

Indicates that the cmdlet directs the cmdlet to display all the error information. Use
with the
DisplayError or ShowError parameter. By default, when an error object is
written to the
error or display streams, only some error information is displayed.

Also required when formatting certain .NET types. For more information, see the
Notes
section.

Type: SwitchParameter

Position: Named
Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-GroupBy

Specifies 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. The GroupBy parameter expects that the objects
are sorted.
Use the Sort-Object cmdlet before using Format-Table to group the
objects.

The value of the GroupBy parameter can be a new calculated property. The
calculated property can
be a script block or a hash table. Valid key-value pairs are:

Name (or Label) - <string>


Expression - <string> or <script block>
FormatString - <string>

For more information, see


about_Calculated_Properties.

Type: Object

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-HideTableHeaders

Omits the column headings from the table.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


-InputObject

Specifies the objects to format. Enter a variable that contains the objects, or type a
command or
expression that gets the objects.

Type: PSObject

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Property

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
first object's
properties. For example, if the first object has PropertyA and PropertyB
but subsequent
objects have PropertyA, PropertyB, and PropertyC, then only the
PropertyA and
PropertyB headers are displayed.

The Property parameter is optional. You can't use the Property and View parameters
in
the same command.

The value of the Property parameter can be a new calculated property. The
calculated property
can be a script block or a hash table. Valid key-value pairs are:

Name (or Label) <string>


Expression - <string> or <script block>
FormatString - <string>
Width - <int32> - must be greater than 0
Alignment - value can be Left , Center , or Right

For more information, see


about_Calculated_Properties.

Type: Object[]

Position: 0

Default value: None

Accept pipeline input: False


Accept wildcard characters: True

-RepeatHeader

Repeats displaying the header of a table after every screen full. The repeated header
is useful when
the output is piped to a pager such as less or more or paging with a
screen reader.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-ShowError

This parameter sends errors through the pipeline. This parameter can be used as a
debugging aid when
you're formatting expressions in a Format-Table command and
need to troubleshoot the expressions.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-View

In PowerShell 5.1 and earlier versions, the default views are defined in
*.format.ps1xml files
stored in $PSHOME .

The View parameter lets you specify an alternate format or custom view for the
table. You can
use the default PowerShell views or create custom views. For more
information about how to create a
custom view, see about_Format.ps1xml.

The alternate and custom views for the View parameter must use the table format,
otherwise,
Format-Table fails. If the alternate view is a list, use the Format-List
cmdlet. If the
alternate view isn't a list or a table, use the Format-Custom cmdlet.

You can't use the Property and View parameters in the same command.

Type: String

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.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSObject

You can pipe any object to this cmdlet.

Outputs
Microsoft.PowerShell.Commands.Internal.Format

This cmdlet returns format objects that represent the table.

Notes
Windows PowerShell includes the following aliases for Format-Table :
ft

If you want to use Format-Table with the Property parameter, you need to include the
Force
parameter under any of the following conditions:

The input objects are normally formatted out-of-band using the ToString()
method. This applies
to [string] and .NET primitive types, which are a superset of
the built-in numeric types such as
[int] , [long] , and others.

The input objects have no public properties.

The input objects are instances of the wrapper types PowerShell uses for output
streams other
than the Success output stream. This applies only when these
wrapper types are sent to the Success
output stream that requires either having
captured them via common parameters such as
ErrorVariable first or using a
redirection such as *>&1 .

The wrapper types include:


System.Management.Automation.ErrorRecord
System.Management.Automation.WarningRecord
System.Management.Automation.VerboseRecord
System.Management.Automation.DebugRecord
System.Management.Automation.InformationRecord

Related Links
about_Calculated_Properties
about_Format.ps1xml
about_Hash_Tables
Export-FormatData
Format-Custom
Format-Hex
Format-List
Format-Wide
Get-FormatData
Get-Member
Get-CimInstance
Update-FormatData
Format-Wide
Reference
Module: Microsoft.PowerShell.Utility

Formats objects as a wide table that displays only one property of each object.

Syntax
PowerShell

Format-Wide

[[-Property] <Object>]

[-AutoSize]

[-Column <int>]

[-GroupBy <Object>]

[-View <string>]

[-ShowError]

[-DisplayError]

[-Force]

[-Expand <string>]

[-InputObject <psobject>]

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

Examples

Example 1: Format names of files in the current directory


This command displays the names of files in the current directory in three columns
across the
screen.

PowerShell

Get-ChildItem | Format-Wide -Column 3


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: Format names of registry keys


This command displays the names of registry keys in the
HKEY_CURRENT_USER\Software\Microsoft key.

PowerShell

Get-ChildItem HKCU:\software\microsoft | Format-Wide -Property pschildname -


AutoSize

The Get-ChildItem cmdlet gets objects representing the keys. The path is specified as
HKCU: , one
of the drives exposed by the 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.

Example 3: Troubleshooting format errors


The following examples show of the results of adding the DisplayError or ShowError
parameters with an expression.

PowerShell

PS /> Get-Date | Format-Wide { $_ / $null } -DisplayError

#ERR

PS /> Get-Date | Format-Wide { $_ / $null } -ShowError

Failed to evaluate expression " $_ / $null ".

+ CategoryInfo : InvalidArgument: (12/21/2018 8:18:01 AM:PSObject)


[], RuntimeException

+ FullyQualifiedErrorId : PSPropertyExpressionError

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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Column

Specifies the number of columns in the display. You cannot use the AutoSize and
Column
parameters in the same command.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-DisplayError

Displays errors at the command line. This parameter is rarely used, but can be used
as a debugging
aid when you are formatting expressions in a Format-Wide
command, and the expressions do not
appear to be working.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Expand
Formats the collection object, as well as the objects in the collection. This parameter
is designed
to format objects that support the System.Collections.ICollection
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.

Type: String

Accepted values: CoreOnly, EnumOnly, Both

Position: Named

Default value: EnumOnly

Accept pipeline input: False

Accept wildcard characters: False

-Force

Indicates that this cmdlet 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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-GroupBy

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. The
calculated property can
be a script block or a hash table. Valid key-value pairs are:

Name (or Label ) - <string>

Expression - <string> or <script block>


FormatString - <string>

For more information, see


about_Calculated_Properties.

Type: Object

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies the objects to format. Enter a variable that contains the objects, or type a
command or
expression that gets the objects.

Type: PSObject

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Property

Specifies the object property that appears in the display. 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. The
calculated property
can be a script block or a hash table. Valid key-value pairs are:

Expression - <string> or <script block>

FormatString - <string>
For more information, see
about_Calculated_Properties.

Type: Object

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-ShowError

Sends errors through the pipeline. This parameter is rarely used, but can be used as a
debugging
aid when you are formatting expressions in a Format-Wide command, and
the expressions do not
appear to be working.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-View

Specifies the name of an alternate table format or view. You cannot use the Property
and
View parameters in the same command.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSObject
You can pipe any object to this cmdlet.

Outputs
Microsoft.PowerShell.Commands.Internal.Format

This cmdlet returns format objects that represent the table.

Notes
Windows PowerShell includes the following aliases for Format-Wide :

fw

The GroupBy parameter assumes that the objects are sorted. Use Sort-Object before
using
Format-Custom to group the objects.

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 PowerShell directory or you can create
your own views
in new PS1XML files and use the Update-FormatData cmdlet to include
them in 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 .

Related Links
about_Calculated_Properties
Format-Custom
Format-Hex
Format-List
Format-Table
Get-Alias
Reference
Module: Microsoft.PowerShell.Utility

Gets the aliases for the current session.

Syntax
PowerShell

Get-Alias

[[-Name] <String[]>]

[-Exclude <String[]>]

[-Scope <String>]

[<CommonParameters>]

PowerShell

Get-Alias

[-Exclude <String[]>]

[-Scope <String>]

[-Definition <String[]>]

[<CommonParameters>]

Description
The Get-Alias cmdlet gets the aliases in the current session. This includes built-in
aliases,
aliases that you have set or imported, and aliases that you have added to your
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.

Beginning in Windows PowerShell 3.0, Get-Alias displays non-hyphenated alias names


in an
<alias> -> <definition> format to make it even easier to find the information
that you need.

Examples

Example 1: Get all aliases in the current session


PowerShell

Get-Alias

CommandType Name

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

Alias % -> ForEach-Object

Alias ? -> Where-Object


Alias ac -> Add-Content

Alias asnp -> Add-PSSnapin

Alias cat -> Get-Content

Alias cd -> Set-Location

Alias chdir -> Set-Location

Alias clc -> Clear-Content

Alias clear -> Clear-Host

Alias clhy -> Clear-History

...

This command gets all aliases in the current session.

The output shows the <alias> -> <definition> format that was introduced in Windows
PowerShell 3.0.
This format is used only for aliases that do not include hyphens, because
aliases with hyphens are
typically preferred names for cmdlets and functions, rather than
nicknames.

Example 2: Get aliases by name


PowerShell

Get-Alias -Name gp*, sp* -Exclude *ps

This command gets all aliases that begin with gp or sp, except for aliases that end with
ps.

Example 3: Get aliases for a cmdlet


PowerShell

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: Get aliases by property
PowerShell

Get-Alias | Where-Object {$_.Options -Match "ReadOnly"}

This command gets 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 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: Get aliases by name and filter by beginning


letter
PowerShell

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.

Parameters
-Definition

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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: True

-Exclude

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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Name

Specifies the aliases that this cmdlet gets. 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 .

Type: String[]

Position: 0

Default value: All aliases

Accept pipeline input: True

Accept wildcard characters: True

-Scope

Specifies the scope for which this cmdlet gets aliases. The acceptable values for this
parameter
are:

Global
Local

Script

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.

Type: String

Position: Named

Default value: Local

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a string containing an alias name to this cmdlet.

Outputs
AliasInfo

This cmdlet returns an object that represents each alias. It returns the same type of
object for
every alias, but PowerShell uses an arrow-based format to display the names
of non-hyphenated
aliases.

Notes
Windows PowerShell includes the following aliases for Get-Alias :

gal

To create a new alias, use Set-Alias or New-Alias . To delete an alias, use Remove-
Item .

The arrow-based alias name format is not used for aliases that include a hyphen.
These are likely
to be preferred substitute names for cmdlets and functions,
instead of typical abbreviations or
nicknames.

Related Links
Export-Alias
Import-Alias
New-Alias
Set-Alias
Alias Provider
about_Aliases
Get-Culture
Reference
Module: Microsoft.PowerShell.Utility

Gets the current culture set in the operating system.

Syntax
PowerShell

Get-Culture []

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, and the Set-Culture cmdlet in the
International module. The user-
interface (UI) culture determines which text strings are used for
user interface elements,
such as menus and messages.

Examples

Example 1: Get culture settings


PowerShell

Get-Culture

LCID Name DisplayName

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

1033 en-US English (United States)

This command displays information about the regional settings on the computer.

Example 2: Format the properties of a culture object


PowerShell

PS C:\> $C = Get-Culture

PS C:\> $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

PS C:\> $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

PS C:\> $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...}

PS C:\> $C.DateTimeFormat.FirstDayOfWeek

Sunday

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.

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
CultureInfo

This cmdlet returns a CultureInfo object representing 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.

Related Links
Set-Culture
Get-UICulture
Get-Date
Reference
Module: Microsoft.PowerShell.Utility

Gets the current date and time.

Syntax
PowerShell

Get-Date

[[-Date] <DateTime>]

[-Year <Int32>]

[-Month <Int32>]

[-Day <Int32>]

[-Hour <Int32>]

[-Minute <Int32>]

[-Second <Int32>]

[-Millisecond <Int32>]

[-DisplayHint <DisplayHintType>]

[-Format <String>]

[<CommonParameters>]

PowerShell

Get-Date

[[-Date] <DateTime>]

[-Year <Int32>]

[-Month <Int32>]

[-Day <Int32>]

[-Hour <Int32>]

[-Minute <Int32>]

[-Second <Int32>]

[-Millisecond <Int32>]

[-DisplayHint <DisplayHintType>]

[-UFormat <String>]

[<CommonParameters>]

Description
The Get-Date cmdlet gets a DateTime object that represents the current date or a date
that you
specify. Get-Date can format the date and time in several .NET 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.
Get-Date uses the computer's culture settings to determine how the output is

formatted. To view
your computer's settings, use (Get-Culture).DateTimeFormat .

Examples

Example 1: Get the current date and time


In this example, Get-Date displays the current system date and time. The output is in the
long-date and long-time formats.

PowerShell

Get-Date

Tuesday, June 25, 2019 14:53:32

Example 2: Get elements of the current date and time


This example shows how to use Get-Date to get either the date or time element. The
parameter uses
the arguments Date, Time, or DateTime.

PowerShell

Get-Date -DisplayHint Date

Tuesday, June 25, 2019

Get-Date uses the DisplayHint parameter with the Date argument to get only the date.

Example 3: Get the date and time with a .NET format


specifier
In this example, a .NET format specifier is used to customize the output's format. The
output is a
String object.

PowerShell

Get-Date -Format "dddd MM/dd/yyyy HH:mm K"

Tuesday 06/25/2019 16:17 -07:00


Get-Date uses the Format parameter to specify several format specifiers.

The .NET format specifiers used in this example are defined as follows:

Specifier Definition

dddd Day of the week - full name

MM Month number

dd Day of the month - 2 digits

yyyy Year in 4-digit format

HH:mm Time in 24-hour format - no seconds

K Time zone offset from Universal Time Coordinate (UTC)

For more information about .NET format specifiers, see


Custom date and time format
strings.

Example 4: Get the date and time with a UFormat


specifier
In this example, several UFormat format specifiers are used to customize the output's
format.
The output is a String object.

PowerShell

Get-Date -UFormat "%A %m/%d/%Y %R %Z"

Tuesday 06/25/2019 16:19 -07

Get-Date uses the UFormat parameter to specify several format specifiers.

The UFormat format specifiers used in this example are defined as follows:

Specifier Definition

%A Day of the week - full name

%m Month number

%d Day of the month - 2 digits

%Y Year in 4-digit format


Specifier Definition

%R Time in 24-hour format - no seconds

%Z Time zone offset from Universal Time Coordinate (UTC)

For a list of valid UFormat format specifiers, see the Notes section.

Example 5: Get a date's day of the year


In this example, a property is used to get the numeric day of the year.

The Gregorian calendar has 365 days, except for leap years that have 366 days. For
example, December
31, 2020 is day 366.

PowerShell

(Get-Date -Year 2020 -Month 12 -Day 31).DayOfYear

366

Get-Date uses three parameters to specify the date: Year, Month, and Day. The
command
is wrapped with parentheses so that the result is evaluated by the DayofYear
property.

Example 6: Check if a date is adjusted for daylight savings


time
This example uses a boolean method to verify if a date is adjusted by daylight savings
time.

PowerShell

$DST = Get-Date

$DST.IsDaylightSavingTime()

True

A variable, $DST stores the result of Get-Date . $DST uses the IsDaylightSavingTime
method
to test if the date is adjusted for daylight savings time.

Example 7: Convert the current time to UTC time


In this example, the current time is converted to UTC time. The UTC offset for the
system's locale
is used to convert the time. A table in the Notes section lists the valid
UFormat
format specifiers.

PowerShell

Get-Date -UFormat "%A %B/%d/%Y %T %Z"

$Time = Get-Date

$Time.ToUniversalTime()

Wednesday June/26/2019 10:45:26 -07

Wednesday, June 26, 2019 17:45:26

Get-Date uses the UFormat parameter with format specifiers to display the current
system date
and time. The format specifier %Z represents the UTC offset of -07.

The $Time variable stores the current system date and time. $Time uses the
ToUniversalTime()
method to convert the time based on the computer's UTC offset.

Example 8: Create a timestamp


In this example, a format specifier creates a timestamp String object for a directory
name. The
timestamp includes the date, time, and UTC offset.

PowerShell

$timestamp = Get-Date -Format o | ForEach-Object { $_ -replace ":", "." }

New-Item -Path C:\Test\$timestamp -Type Directory

Directory: C:\Test

Mode LastWriteTime Length Name

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

d----- 6/27/2019 07:59 2019-06-


27T07.59.24.4603750-07.00

The $timestamp variable stores the results of a Get-Date command. Get-Date uses the
Format
parameter with the format specifier of lowercase o to create a timestamp String
object. The
object is sent down the pipeline to ForEach-Object . A ScriptBlock contains
the $_ variable
that represents the current pipeline object. The timestamp string is
delimited by colons that are
replaced by periods.

New-Item uses the Path parameter to specify the location for a new directory. The path

includes the $timestamp variable as the directory name. The Type parameter specifies
that a
directory is created.

Parameters
-Date

Specifies a date and time. Time is optional and if not specified, returns 00:00:00.

Enter the date and time in a format that is standard for the system locale.

For example, in US English:

Get-Date -Date "6/25/2019 12:30:22" returns Tuesday, June 25, 2019 12:30:22

Type: DateTime

Aliases: LastWriteTime

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Day

Specifies the day of the month that is displayed. Enter a value from 1 to 31.

If the specified value is greater than the number of days in a month, PowerShell adds
the number of
days to the month. For example, Get-Date -Month 2 -Day 31 displays
March 3, not February 31.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-DisplayHint

Determines which elements of the date and time are displayed.


The accepted values are as follows:

Date: displays only the date


Time: displays only the time
DateTime: displays the date and time

Type: DisplayHintType

Accepted values: Date, Time, DateTime

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Format

Displays the date and time in the Microsoft .NET Framework format indicated by the
format specifier.
The Format parameter outputs a String object.

For a list of available .NET format specifiers, see


Custom date and time format
strings.

When the Format parameter is used, Get-Date only gets the DateTime object's
properties
necessary to display the date. As a result, some of the properties and
methods of DateTime
objects might not be available.

Starting in PowerShell 5.0, you can use the following additional formats as values for
the
Format parameter.

FileDate. A file or path-friendly representation of the current date in local time.


The format
is yyyyMMdd (case-sensitive, using a 4-digit year, 2-digit month, and
2-digit day). For example:
20190627.

FileDateUniversal. A file or path-friendly representation of the current date in


universal
time (UTC). The format is yyyyMMddZ (case-sensitive, using a 4-digit
year, 2-digit month,
2-digit day, and the letter Z as the UTC indicator). For
example: 20190627Z.

FileDateTime. A file or path-friendly representation of the current date and


time in local
time, in 24-hour format. The format is yyyyMMddTHHmmssffff (case-
sensitive, using a 4-digit
year, 2-digit month, 2-digit day, the letter T as a time
separator, 2-digit hour, 2-digit
minute, 2-digit second, and 4-digit millisecond).
For example: 20190627T0840107271.

FileDateTimeUniversal. A file or path-friendly representation of the current


date and time in
universal time (UTC), in 24-hour format. The format is
yyyyMMddTHHmmssffffZ (case-sensitive,
using a 4-digit year, 2-digit month, 2-

digit day, the letter T as a time separator, 2-digit


hour, 2-digit minute, 2-digit
second, 4-digit millisecond, and the letter Z as the UTC
indicator). For example:
20190627T1540500718Z.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Hour

Specifies the hour that is displayed. Enter a value from 0 to 23.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Millisecond

Specifies the milliseconds in the date. Enter a value from 0 to 999.

This parameter was introduced in PowerShell 3.0.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-Minute

Specifies the minute that is displayed. Enter a value from 0 to 59.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Month

Specifies the month that is displayed. Enter a value from 1 to 12.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Second

Specifies the second that is displayed. Enter a value from 0 to 59.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-UFormat

Displays the date and time in UNIX format. The UFormat parameter outputs a string
object.
UFormat specifiers are preceded by a percent sign ( % ), for example, %m , %d , and %Y .
The
Notes section contains a table of valid UFormat specifiers.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Year

Specifies the year that is displayed. Enter a value from 1 to 9999.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
DateTime

You can pipe a DateTime object to this cmdlet.

Outputs
DateTime

By default, this cmdlet returns a DateTime object.

When a DateTime object is sent down the pipeline to a cmdlet such as Add-Content that
expects
string input, PowerShell converts the object to a String object.

The method (Get-Date).ToString() converts a DateTime object a String object.

To display an object's properties and methods, send the object down the pipeline to
Get-Member .
For example, Get-Date | Get-Member .
String

When you use the Format or UFormat parameters, this cmdlet returns String objects.

Notes
DateTime objects are in long-date and long-time formats for the system locale.

The valid UFormat specifiers are displayed in the following table:

) Important

UFormat specifiers are changed or added in newer versions of PowerShell. For


example, %F was
added in PowerShell 6.2, so it isn't available in Windows
PowerShell 5.1 or older. Keep this in
mind when using UFormat specifiers in scripts
designed to be run on multiple versions of
PowerShell.

Format Meaning Example


specifier

%A Day of the week - full name Monday

%a Day of the week - abbreviated name Mon

%B Month name - full January

%b Month name - abbreviated Jan

%C Century 20 for 2019

%c Date and time - abbreviated Thu Jun 27 08:44:18


2019

%D Date in mm/dd/yy format 06/27/19

%d Day of the month - 2 digits 05

%e Day of the month - preceded by a space if only a single <space>5


digit

%G Same as 'Y'

%g Same as 'y'

%H Hour in 24-hour format 17

%h Same as 'b'
Format Meaning Example
specifier

%I Hour in 12-hour format 05

%j Day of the year (does not include leading 0 - Fixed in 1-366


PowerShell 6+)

%k Same as 'H'

%l Same as 'I' (Upper-case I) 05

%M Minutes 35

%m Month number 06

%n newline character

%p AM or PM

%R Time in 24-hour format -no seconds 17:45

%r Time in 12-hour format 09:15:36 AM

%S Seconds 05

%s Seconds elapsed since January 1, 1970 00:00:00 (converted 1150451174.95705


to local time)

%t Horizontal tab character

%T Time in 24-hour format 17:45:52

%U Same as 'W'

%u Day of the week - number Sunday = 0

%V Week of the year 01-53

%w Same as 'u'

%W Week of the year 00-52

%X Same as 'T'

%x Date in standard format for locale 06/27/19 for


English-US

%Y Year in 4-digit format 2019

%y Year in 2-digit format 19


Format Meaning Example
specifier

%Z Time zone offset from Universal Time Coordinate (UTC) -07

7 Note

Windows PowerShell's behavior with Get-Date -UFormat %s is incorrect in two


respects:

The return value is based on local time instead of UTC time.


The string representation of the seconds value has a fractional part. The
output is
culture-sensitive with respect to the decimal mark.

These behaviors have been fixed in PowerShell 6 and higher.

Related Links
ForEach-Object
Get-Culture
Get-Member
New-Item
New-TimeSpan
Set-Date
Get-Event
Reference
Module: Microsoft.PowerShell.Utility

Gets the events in the event queue.

Syntax
PowerShell

Get-Event

[[-SourceIdentifier] <String>]
[<CommonParameters>]

PowerShell

Get-Event

[-EventIdentifier] <Int32>

[<CommonParameters>]

Description
The Get-Event cmdlet gets events in the PowerShell event queue for the current session.
You can
get all events or use the EventIdentifier or SourceIdentifier parameter 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
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 .

Examples

Example 1: Get all events


PowerShell
PS C:\> Get-Event

This command gets all events in the event queue.

Example 2: Get events by source identifier


PowerShell

PS C:\> Get-Event -SourceIdentifier "PowerShell.ProcessCreated"

This command gets events in which the value of the SourceIdentifier property is
PowerShell.ProcessCreated.

Example 3: Get an event based on the time it was


generated
PowerShell

PS C:\> $Events = Get-Event

PS C:\> $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 : PS C:\> 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 :

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: Get an event by its identifier


PowerShell

PS C:\> Get-Event -EventIdentifier 2

This command gets the event with an event identifier of 2.

Parameters
-EventIdentifier

Specifies the event identifiers for which this cmdlet gets events.

Type: Int32

Aliases: Id

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-SourceIdentifier

Specifies source identifiers for which this cmdlet gets events. The default is all events
in the
event queue. Wildcards are not permitted.

Type: String
Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
PSEventArgs

This cmdlet 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
$EventArgs
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 $Args 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.

Related Links
New-Event
Register-EngineEvent
Register-ObjectEvent
Remove-Event
Unregister-Event
Wait-Event
Get-EventSubscriber
Reference
Module: Microsoft.PowerShell.Utility

Gets the event subscribers in the current session.

Syntax
PowerShell

Get-EventSubscriber

[[-SourceIdentifier] <String>]
[-Force]

[<CommonParameters>]

PowerShell

Get-EventSubscriber

[-SubscriptionId] <Int32>

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

Examples

Example 1: Get the event subscriber for a timer event


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.

PowerShell

$Timer = New-Object Timers.Timer

$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)

Register-ObjectEvent -InputObject $Timer -EventName Elapsed -


SourceIdentifier Timer.Elapsed

Get-EventSubscriber

SubscriptionId : 4

SourceObject : System.Timers.Timer

EventName : Elapsed

SourceIdentifier : Timer.Elapsed

Action :

HandlerDelegate :

SupportEvent : False

ForwardEvent : False

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: Use the dynamic module in PSEventJob in the


Action property of the event subscriber
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).

PowerShell

$Timer = New-Object Timers.Timer

$Timer.Interval = 500

$params = @{

InputObject = $Timer

EventName = 'Elapsed'

SourceIdentifier = 'Timer.Random'

Action = { $Random = Get-Random -Min 0 -Max 100 }

Register-ObjectEvent @params

Id Name State HasMoreData Location Command

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

3 Timer.Random NotStarted False $Random = Get-Random


...

$Timer.Enabled = $True

$Subscriber = Get-EventSubscriber -SourceIdentifier Timer.Random

($Subscriber.action).gettype().fullname

System.Management.Automation.PSEventJob

$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 : {}

...

& $Subscriber.action.module {$Random}

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

Parameters
-Force

Indicates that this cmdlet gets all event subscribers, including subscribers for events
that are
hidden by using the SupportEvent parameter of Register-ObjectEvent ,
Register-WmiEvent , and
Register-EngineEvent .

Type: SwitchParameter

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-SourceIdentifier

Specifies the SourceIdentifier property value that gets only the event subscribers. By
default,
Get-EventSubscriber gets all event subscribers in the session. Wildcards are
not permitted. This
parameter is case-sensitive.

Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-SubscriptionId

Specifies the subscription identifier that this cmdlet gets. By default, Get-
EventSubscriber gets
all event subscribers in the session.

Type: Int32

Aliases: Id

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
PSEventSubscriber

This cmdlet returns a PSEventSubscriber object for 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.

Related Links
Get-Event
New-Event
Register-EngineEvent
Register-ObjectEvent
Remove-Event
Unregister-Event
Wait-Event
Get-FileHash
Reference
Module: Microsoft.PowerShell.Utility

Computes the hash value for a file by using a specified hash algorithm.

Syntax
PowerShell

Get-FileHash

[-Path] <String[]>

[-Algorithm <String>]

[<CommonParameters>]

PowerShell

Get-FileHash

-LiteralPath <String[]>

[-Algorithm <String>]

[<CommonParameters>]

PowerShell

Get-FileHash

-InputStream <Stream>

[-Algorithm <String>]

[<CommonParameters>]

Description
The Get-FileHash cmdlet computes the hash value for a file by using a specified hash
algorithm.
A hash value is a unique value that corresponds to the content of the file.
Rather than identifying
the contents of a file by its file name, extension, or other
designation, a hash assigns a unique
value to the contents of a file. File names and
extensions can be changed without altering the
content of the file, and without
changing the hash value. Similarly, the file's content can be
changed without changing
the name or extension. However, changing even a single character in the
contents of a
file changes the hash value of the file.
The purpose of hash values is to provide a cryptographically-secure way to verify that
the contents
of a file have not been changed. While some hash algorithms, including
MD5 and SHA1, are no longer
considered secure against attack, the goal of a secure
hash algorithm is to render it impossible to
change the contents of a file -- either by
accident, or by malicious or unauthorized attempt -- and
maintain the same hash value.
You can also use hash values to determine if two different files have
exactly the same
content. If the hash values of two files are identical, the contents of the files
are also
identical.

By default, the Get-FileHash cmdlet uses the SHA256 algorithm, although any hash
algorithm that
is supported by the target operating system can be used.

Examples

Example 1: Compute the hash value for a file


This example uses the Get-FileHash cmdlet to compute the hash value for the
Powershell.exe file.
The hash algorithm used is the default, SHA256. The output is piped
to the Format-List cmdlet to
format the output as a list.

PowerShell

Get-FileHash $PSHOME\powershell.exe | Format-List

Algorithm : SHA256

Hash : 908B64B1971A979C7E3E8CE4621945CBA84854CB98D76367B791A6E22B5F6D53

Path : C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

Example 2: Compute the hash value for an ISO file


This example uses the Get-FileHash cmdlet and the SHA384 algorithm to compute the
hash value
for an ISO file that an administrator has downloaded from the internet. The
output is piped to the
Format-List cmdlet to format the output as a list.

PowerShell

Get-FileHash C:\Users\user1\Downloads\Contoso8_1_ENT.iso -Algorithm SHA384 |


Format-List

Algorithm : SHA384

Hash :
20AB1C2EE19FC96A7C66E33917D191A24E3CE9DAC99DB7C786ACCE31E559144FEAFC695C58E5
08E2EBBC9D3C96F21FA3

Path : C:\Users\user1\Downloads\Contoso8_1_ENT.iso

Example 3: Compute the hash value of a stream


For this example, we get are using System.Net.WebClient to download a package from
the
Powershell release page . The release
page also documents the SHA256 hash of
each package file. We can compare the published hash value
with the one we calculate
with Get-FileHash .

PowerShell

$wc = [System.Net.WebClient]::new()

$pkgurl =
'https://github.com/PowerShell/PowerShell/releases/download/v6.2.4/powershel
l_6.2.4-1.debian.9_amd64.deb'

$publishedHash =
'8E28E54D601F0751922DE24632C1E716B4684876255CF82304A9B19E89A9CCAC'

$FileHash = Get-FileHash -InputStream ($wc.OpenRead($pkgurl))

$FileHash.Hash -eq $publishedHash

True

Example 4: Compute the hash of a string


PowerShell does not provide a cmdlet to compute the hash of a string. However, you
can write a
string to a stream and use the InputStream parameter of Get-FileHash to
get the hash value.

PowerShell

$stringAsStream = [System.IO.MemoryStream]::new()

$writer = [System.IO.StreamWriter]::new($stringAsStream)

$writer.write("Hello world")

$writer.Flush()

$stringAsStream.Position = 0

Get-FileHash -InputStream $stringAsStream | Select-Object Hash

Hash

----

64EC88CA00B268E5BA1A35678A1B5316D212F4F366B2477232534A8AECA37F3C

Parameters
-Algorithm

Specifies the cryptographic hash function to use for computing the hash value of the
contents of the
specified file or stream. A cryptographic hash function has the
property that it is infeasible to
find two different files with the same hash value. Hash
functions are commonly used with digital
signatures and for data integrity. The
acceptable values for this parameter are:

SHA1
SHA256
SHA384
SHA512
MACTripleDES
MD5
RIPEMD160

If no value is specified, or if the parameter is omitted, the default value is SHA256.

For security reasons, MD5 and SHA1, which are no longer considered secure, should
only be used for
simple change validation, and should not be used to generate hash
values for files that require
protection from attack or tampering.

Type: String

Accepted values: SHA1, SHA256, SHA384, SHA512, MACTripleDES, MD5,


RIPEMD160

Position: Named

Default value: SHA256

Accept pipeline input: False

Accept wildcard characters: False

-InputStream

Specifies the input stream.

Type: Stream

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-LiteralPath

Specifies the path to a file. Unlike the Path parameter, the value of the LiteralPath
parameter is used exactly as it is typed. No characters are interpreted as wildcard
characters. If
the path includes escape characters, enclose the path in single
quotation marks. Single quotation
marks instruct PowerShell not to interpret
characters as escape sequences.

Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Path

Specifies the path to one or more files as an array. Wildcard characters are permitted.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

Inputs
String

You can pipe a string containing a path to a file to this cmdlet.

Outputs
Microsoft.PowerShell.Utility.FileHash
This cmdlet returns an object representing the path to the specified file, the value of the
computed hash, and the algorithm used to compute the hash.

Related Links
Format-List
Get-FormatData
Reference
Module: Microsoft.PowerShell.Utility

Gets the formatting data in the current session.

Syntax
PowerShell

Get-FormatData

[[-TypeName] <String[]>]

[-PowerShellVersion <Version>]
[<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 PowerShell, see


about_Format.ps1xml.

Examples

Example 1: Get all formatting data


This example gets all the formatting data in the session.

PowerShell

Get-FormatData
Example 2: Get formatting data by type name
This example gets the formatting data items whose names begin with
System.Management.Automation.Cmd .

PowerShell

Get-FormatData -TypeName 'System.Management.Automation.Cmd*'

Example 3: Examine a formatting data object


This example shows how to get a formatting data object and examine its properties.

PowerShell

$F = Get-FormatData -TypeName 'System.Management.Automation.Cmd*'

$F

TypeName FormatViewDefinition

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

HelpInfoShort {help , TableControl}

$F.FormatViewDefinition[0].control

Headers : {System.Management.Automation.TableControlColumnHeader,

System.Management.Automation.TableControlColumnHeader,

System.Management.Automation.TableControlColumnHeader,

System.Management.Automation.TableControlColumnHeader}

Rows : {System.Management.Automation.TableControlRow}

AutoSize : False

HideTableHeaders : False

GroupBy :

OutOfBand : False

$F.FormatViewDefinition[0].control.Headers

Label Alignment Width

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

CommandType Undefined 15

Name Undefined 50

Version Undefined 10

Source Undefined 0

Example 4: Get formatting data and export it


This example shows how to use Get-FormatData and Export-FormatData to export the
formatting
data that is added by a module.
PowerShell

$A = Get-FormatData

Import-Module bitstransfer

$B = Get-FormatData

Compare-Object $A $B

InputObject SideIndicator

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

Microsoft.BackgroundIntelligentTransfer.Management.BitsJob =>

Get-FormatData *bits* | Export-FormatData -FilePath


c:\test\bits.format.ps1xml

Get-Content c:\test\bits.format.ps1xml

<?xml version="1.0" encoding="utf-8"?><Configuration><ViewDefinitions>

<View>
<Name>Microsoft.BackgroundIntelligentTransfer.Management.BitsJob</Name>

...

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.

Example 5: Get formatting data based on the specified


version of PowerShell
This example shows how to use Get-FormatData to get format data for a specified
TypeName and
PowerShell version.

PowerShell

Get-FormatData -TypeName 'Microsoft.Powershell.Utility.FileHash' -


PowerShellVersion $PSVersionTable.PSVersion

TypeNames FormatViewDefinition

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

{Microsoft.Powershell.Utility.FileHash}
{Microsoft.Powershell.Utility.FileHash}
) Important

To ensure that the complete type formatting information is returned, you should
always include the
PowerShellVersion parameter with the appropriate version. If
the parameter and value are
omitted, you may not get all the correct type
information.

Parameters
-PowerShellVersion

Specify the version of PowerShell this cmdlet gets for the formatting data. Enter a
two digit number
separated by a period.

This parameter was added in PowerShell 5.1 to improve compatibility when remoting
computers running
older versions of PowerShell.

Type: Version

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-TypeName

Specifies the type names that this cmdlet gets for the formatting data.
Enter the type
names.
Wildcards are permitted.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
ExtendedTypeDefinition

Related Links
Export-FormatData
Update-FormatData
Get-Host
Reference
Module: Microsoft.PowerShell.Utility

Gets an object that represents the current host program.

Syntax
PowerShell

Get-Host []

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.

Examples

Example 1: Get information about the PowerShell console


host
PowerShell

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

This command displays information about the PowerShell console, which is the current
host program
for PowerShell in this example. It includes the name of the host, the
version of 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 other useful properties. Later examples examine
these
properties.

Example 2: Resize the PowerShell window


PowerShell

$H = Get-Host

$Win = $H.UI.RawUI.WindowSize

$Win.Height = 10

$Win.Width = 10

$H.UI.RawUI.Set_WindowSize($Win)

This command resizes the Windows PowerShell window to 10 lines by 10 characters.

Example 3: Get the PowerShell version for the host


PowerShell

(Get-Host).Version

Major Minor Build Revision

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

5 1 22621 963

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: Get the current culture for the host


PowerShell

(Get-Host).CurrentCulture | Format-List

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 - en-US

TextInfo : TextInfo - en-US

IsNeutralCulture : False

CultureTypes : SpecificCultures, InstalledWin32Cultures

NumberFormat : System.Globalization.NumberFormatInfo

DateTimeFormat : System.Globalization.DateTimeFormatInfo

Calendar : System.Globalization.GregorianCalendar

OptionalCalendars : {System.Globalization.GregorianCalendar}

UseUserOverride : True

IsReadOnly : True

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: Get the DateTimeFormat for the current


culture
PowerShell

(Get-Host).CurrentCulture.DateTimeFormat | Format-List

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

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: Get the RawUI property for the host


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.

PowerShell

(Get-Host).UI.RawUI

ForegroundColor : Gray

BackgroundColor : Black

CursorPosition : 0,28

WindowPosition : 0,0

CursorSize : 25

BufferSize : 120,29

WindowSize : 120,29

MaxWindowSize : 120,29

MaxPhysicalWindowSize : 1904,69

KeyAvailable : True

WindowTitle : PowerShell 7.3.3

Example 7: Set the background color for the PowerShell


console
These commands change the background color of the Windows PowerShell console to
black. The
Clear-Host command clears the screen to reset the console window to the
new color.

PowerShell

(Get-Host).UI.RawUI.BackgroundColor = "Black"

Clear-Host

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

Example 8: Set the background color for error messages


PowerShell

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

Inputs
None
You can't pipe objects to this cmdlet.

Outputs
System.Management.Automation.Internal.Host.InternalHost

This cmdlet returns an 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.

Related Links
Clear-Host
Read-Host
Write-Host
Get-Member
Reference
Module: Microsoft.PowerShell.Utility

Gets the properties and methods of objects.

Syntax
PowerShell

Get-Member

[-InputObject <PSObject>]

[[-Name] <String[]>]

[-MemberType <PSMemberTypes>]

[-View <PSMemberViewTypes>]

[-Static]

[-Force]

[<CommonParameters>]

Description
The Get-Member cmdlet gets the members, the properties and methods, of objects.

To specify the object, use the InputObject parameter or pipe an object to Get-Member .
To get
information about static members, the 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.

Get-Member returns a list of members that's sorted alphabetically. Methods are listed
first,
followed by the properties.

Examples

Example 1: Get the members of process objects


This command displays the properties and methods of the service objects generated by
the
Get-Service cmdlet.

Because the Get-Member part of the command doesn't have any parameters, it uses
default values for
the parameters. By default, Get-Member doesn't get static or intrinsic
members.

PowerShell

Get-Service | Get-Member

TypeName: System.ServiceProcess.ServiceController

Name MemberType Definition

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

Name AliasProperty Name = ServiceName

RequiredServices AliasProperty RequiredServices =


ServicesDependedOn

Disposed Event System.EventHandler


Disposed(System.Object, System.EventArgs)

Close Method void Close()

Continue Method void Continue()

CreateObjRef Method System.Runtime.Remoting.ObjRef


CreateObjRef(type requestedType)

Dispose Method void Dispose(), void


IDisposable.Dispose()

Equals Method bool Equals(System.Object obj)

ExecuteCommand Method void ExecuteCommand(int command)

GetHashCode Method int GetHashCode()

GetLifetimeService Method System.Object GetLifetimeService()

GetType Method type GetType()

InitializeLifetimeService Method System.Object


InitializeLifetimeService()

Pause Method void Pause()

Refresh Method void Refresh()

Start Method void Start(), void Start(string[]


args)

Stop Method void Stop()

WaitForStatus Method void


WaitForStatus(System.ServiceProcess.ServiceControllerSt...

CanPauseAndContinue Property bool CanPauseAndContinue {get;}

CanShutdown Property bool CanShutdown {get;}

CanStop Property bool CanStop {get;}

Container Property System.ComponentModel.IContainer


Container {get;}

DependentServices Property
System.ServiceProcess.ServiceController[] DependentServices {get;}

DisplayName Property string DisplayName {get;set;}

MachineName Property string MachineName {get;set;}

ServiceHandle Property
System.Runtime.InteropServices.SafeHandle ServiceHandle {get;}

ServiceName Property 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;}

StartType Property
System.ServiceProcess.ServiceStartMode StartType {get;}

Status Property
System.ServiceProcess.ServiceControllerStatus Status {get;}

ToString ScriptMethod System.Object ToString();

Example 2: Get members of service objects


This example gets all the members (properties and methods) of service objects retrieved
by the
Get-Service cmdlet, including the intrinsic members, such as PSBase, PSObject,
and the
get_ and set_ methods.

PowerShell

Get-Service | Get-Member -Force

(Get-Service Schedule).PSBase

The Get-Member command uses the Force parameter to add the intrinsic members and
compiler-generated members of the objects to the display. 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. For more information on
intrinsic members, see
about_Intrinsic_Members

Example 3: Get extended members of service objects


This example gets the methods and properties of service objects that were extended
using a
Types.ps1xml file or the Add-Member cmdlet.

PowerShell

Get-Service | Get-Member -View Extended

TypeName: System.ServiceProcess.ServiceController

Name MemberType Definition

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

Name AliasProperty Name = ServiceName

RequiredServices AliasProperty RequiredServices = ServicesDependedOn

ToString ScriptMethod System.Object ToString();

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: Get script properties of event log objects
This example gets the script properties of event log objects in the System log in Event
Viewer.

PowerShell

Get-WinEvent -LogName System -MaxEvents 1 | Get-Member -MemberType


NoteProperty

TypeName: System.Diagnostics.Eventing.Reader.EventLogRecord

Name MemberType Definition

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

Message NoteProperty string Message=The machine-default permission settings


do not grant Local ...

The MemberType parameter gets only objects with a value of NoteProperty for their
MemberType property.

The command returns the Message property of the EventLogRecord object.

Example 5: Get objects with a specified property


This example gets objects that have a MachineName property in the output from a list
of cmdlets.

The $list variable contains a list of cmdlets to be evaluated. The foreach statement
invokes
each command and sends the results to Get-Member . The Name parameter limits
the results from
Get-Member to members that have the name MachineName.

PowerShell

$list = "Get-Process", "Get-Service", "Get-Culture", "Get-PSDrive", "Get-


ExecutionPolicy"

foreach ($cmdlet in $list) {& $cmdlet | Get-Member -Name MachineName}

TypeName: System.Diagnostics.Process

Name MemberType Definition


---- ---------- ----------
MachineName Property string MachineName {get;}

TypeName: System.ServiceProcess.ServiceController

Name MemberType Definition


---- ---------- ----------
MachineName Property string MachineName {get;set;}
The results show that only process objects and service objects have a MachineName
property.

Example 6: Get members for an array


This example demonstrates how to find the members of an array of objects. When you
pipe and array of
objects to Get-Member , the cmdlet returns a member list for each
unique object type in the array.
If you pass the array using the InputObject parameter,
the array is treated as a single object.

PowerShell

$array = @(1,'hello')

$array | Get-Member

TypeName: System.Int32

Name MemberType Definition


---- ---------- ----------
CompareTo Method int CompareTo(System.Object value), int CompareTo(int
value), int ICompar...

Equals Method bool Equals(System.Object obj), bool Equals(int obj),


bool IEquatable[int...

GetHashCode Method int GetHashCode()

GetType Method type GetType()

GetTypeCode Method System.TypeCode GetTypeCode(), System.TypeCode


IConvertible.GetTypeCode()

ToBoolean Method bool IConvertible.ToBoolean(System.IFormatProvider


provider)

ToByte Method byte IConvertible.ToByte(System.IFormatProvider


provider)

...

TypeName: System.String

Name MemberType Definition

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

Clone Method System.Object Clone(),


System.Object ICloneable.Clone()

CompareTo Method int CompareTo(System.Object


value), int CompareTo(str...

Contains Method bool Contains(string value), bool


Contains(string val...

CopyTo Method void CopyTo(int sourceIndex,


char[] destination, int ...

EndsWith Method bool EndsWith(string value), bool


EndsWith(string val...

EnumerateRunes Method System.Text.StringRuneEnumerator


EnumerateRunes()

Equals Method bool Equals(System.Object obj),


bool Equals(string va...

GetEnumerator Method System.CharEnumerator


GetEnumerator(), System.Collect...

GetHashCode Method int GetHashCode(), int


GetHashCode(System.StringCompa...
...

Get-Member -InputObject $array

TypeName: System.Object[]

Name MemberType Definition

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

Add Method int IList.Add(System.Object value)

Address Method System.Object&, System.Private.CoreLib,


Version=4.0.0.0, Cu...

Clear Method void IList.Clear()

Clone Method System.Object Clone(), System.Object


ICloneable.Clone()

CompareTo Method int


IStructuralComparable.CompareTo(System.Object other, Sy...

...

The $array variable contains an Int32 object and a string object, as seen when the array
is piped to Get-Member . When $array is passed using the InputObject parameter Get-
Member
returns the members of the Object[] type.

Example 7: Determine which object properties you can


set
This example shows how to determine which properties of an object can be changed.

PowerShell

$File = Get-Item c:\test\textFile.txt

$File.PSObject.Properties | Where-Object isSettable | Select-Object -


Property Name

Name

----

PSPath

PSParentPath

PSChildName

PSDrive

PSProvider

PSIsContainer

IsReadOnly

CreationTime

CreationTimeUtc

LastAccessTime

LastAccessTimeUtc

LastWriteTime

LastWriteTimeUtc

Attributes

Example 8: List the properties of an object in the order


they were created
This example creates a new PSObject and adds properties to it. Get-Member lists the
properties
in alphabetic order. To see the properties in the order they were added to the
object you must use
the PSObject intrinsic member.

PowerShell

$Asset = New-Object -TypeName PSObject

$d = [ordered]@{Name="Server30";System="Server Core";PSVersion="4.0"}

$Asset | Add-Member -NotePropertyMembers $d -TypeName Asset

$Asset.PSObject.Properties | Select-Object Name, Value

Name Value

---- -----

Name Server30

System Server Core

PSVersion 4.0

Parameters
-Force

Adds the intrinsic members and the compiler-generated get_ and set_ methods to
the display.
The following list describes the properties that are added when you use
the Force parameter:

PSBase : The original properties of the .NET object without extension or

adaptation. These are


the properties defined for the object class.
PSAdapted : The properties and methods defined in the PowerShell extended
type system.
PSExtended : The properties and methods that were added in the Types.ps1xml
files or using the
Add-Member cmdlet.
PSObject : The adapter that converts the base object to a PowerShell PSObject

object.
PSTypeNames : A list of object types that describe the object, in order of

specificity. When
formatting the object, PowerShell searches for the types in the
Format.ps1xml files in the
PowerShell installation directory ( $PSHOME ). It uses the

formatting definition for the first


type that it finds.

By default, Get-Member gets these properties in all views except Base and Adapted,
but
doesn't display them.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies the object whose members are retrieved.

Using the InputObject parameter isn't 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
each string in an array of
strings.
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
strings.

Type: PSObject

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-MemberType

Specifies the member type that this cmdlet gets. The default is All .
The acceptable values for this parameter are:

AliasProperty
CodeProperty

Property
NoteProperty

ScriptProperty

Properties
PropertySet

Method
CodeMethod

ScriptMethod

Methods
ParameterizedProperty

MemberSet
Event

Dynamic

All

These values are defined as a flag-based enumeration. You can combine multiple
values together to
set multiple flags using this parameter. The values can be passed
to the MemberType parameter as
an array of values or as a comma-separated string
of those values. The cmdlet will combine the
values using a binary-OR operation.
Passing values as an array is the simplest option and also
allows you to use tab-
completion on the values.

For information about these values, see


PSMemberTypes Enumeration.

Not all objects have every type of member. If you specify a member type that the
object doesn't
have, 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.

Type: PSMemberTypes

Aliases: Type

Accepted values: AliasProperty, CodeProperty, Property, NoteProperty,


ScriptProperty, Properties, PropertySet, Method, CodeMethod,
ScriptMethod, Methods, ParameterizedProperty, MemberSet,
Event, Dynamic, All
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Name

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

Type: String[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Static

Indicates that this cmdlet 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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-View

Specifies that this cmdlet gets only particular types properties and methods. Specify
one or more of
the values. The default is Adapted, Extended.

The acceptable values for this parameter are:

Base. Gets only the original properties and methods of the .NET object (without
extension or
adaptation).
Adapted. Gets only the properties and methods defined in the PowerShell
extended type system.
Extended. Gets only the properties and methods that were added in a
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.

Type: PSMemberViewTypes

Accepted values: Extended, Adapted, Base, All

Position: Named

Default value: Adapted, Extended

Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSObject

You can pipe any object to this cmdlet.

Outputs
MemberDefinition
This cmdlet returns a MemberDefinition for each property or method that its gets.

Notes
Windows PowerShell includes the following aliases for Get-Member :

gm

You can get information about a collection object either using the InputObject
parameter or by
piping the object, preceded by a comma, to Get-Member .

You can use the $This automatic variable in script blocks that define the values of new
properties
and methods. The $This variable refers to the instance of the object to which
the properties and
methods are being added. For more information about the $This
variable, see
about_Automatic_Variables.

If you pass an object representing a type, like a type literal such as [int] , Get-Member
return information about the [System.RuntimeType] type. However, when you use the
Static
parameter, Get-Member returns the static members of the specific type
represented by the
System.RuntimeType instance.

Related Links
Add-Member
Get-PSBreakpoint
Reference
Module: Microsoft.PowerShell.Utility

Gets the breakpoints that are set in the current session.

Syntax
PowerShell

Get-PSBreakpoint

[-Script <String[]>]

[<CommonParameters>]

PowerShell

Get-PSBreakpoint

[-Script <String[]>]

-Variable <String[]>

[<CommonParameters>]

PowerShell

Get-PSBreakpoint

[-Script <String[]>]

-Command <String[]>

[<CommonParameters>]

PowerShell

Get-PSBreakpoint

[-Script <String[]>]

[-Type] <BreakpointType[]>

[<CommonParameters>]

PowerShell

Get-PSBreakpoint

[-Id] <Int32[]>

[<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
PowerShell scripts and commands. For more information about
the PowerShell debugger, see
about_Debuggers.

Examples

Example 1: Get all breakpoints for all scripts and functions


This command gets all breakpoints set on all scripts and functions in the current session.

PowerShell

Get-PSBreakpoint

Example 2: Get breakpoints by ID


This command gets the breakpoint with breakpoint ID 2.

PowerShell

Get-PSBreakpoint -Id 2

Function :

IncrementAction :

Enabled :

TrueHitCount : 0

Id : 2

Script : C:\ps-test\sample.ps1

ScriptName : C:\ps-test\sample.ps1

Example 3: Pipe an ID to `Get-PSBreakpoint`


These commands show how to get a breakpoint by piping a breakpoint ID to Get-
PSBreakpoint .

PowerShell
$B = `Set-PSBreakpoint` -Script "sample.ps1" -Command "Increment"

$B.Id | Get-PSBreakpoint

The Set-PSBreakpoint cmdlet creates a breakpoint on the Increment function in the


Sample.ps1
script and saves the breakpoint object in the $B variable. The Id property of

the breakpoint
object in the $B variable is piped to the Get-PSBreakpoint cmdlet to
display the breakpoint
information.

Example 4: Get breakpoints in specified script files


This command gets all of the breakpoints in the Sample.ps1 and SupportScript.ps1
files.

PowerShell

Get-PSBreakpoint -Script "Sample.ps1, SupportScript.ps1"

This command does not get other breakpoints that might be set in other scripts or on
functions in
the session.

Example 5: Get breakpoints in specified cmdlets


This command gets all Command breakpoints that are set on Read-Host or Write-Host
commands in
the Sample.ps1 file.

PowerShell

Get-PSBreakpoint -Command "Read-Host, Write-Host" -Script "Sample.ps1"

Example 6: Get Command breakpoints in a specified file


PowerShell

Get-PSBreakpoint -Type Command -Script "Sample.ps1"

This command gets all Command breakpoints in the Sample.ps1 file.

Example 7: Get breakpoints by variable


This command gets breakpoints that are set on the $Index and $Swap variables in the
current
session.

PowerShell

Get-PSBreakpoint -Variable "Index, Swap"

Example 8: Get all Line and Variable breakpoints in a file


This command gets all line and variable breakpoints in the Sample.ps1 script.

PowerShell

Get-PSBreakpoint -Type Line, Variable -Script "Sample.ps1"

Parameters
-Command

Specifies an array of command breakpoints that are set on the specified command
names. Enter the
command names, such as the name of a cmdlet or function.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Id

Specifies the breakpoint IDs that this cmdlet gets. Enter the IDs in a comma-
separated list. You can
also pipe breakpoint IDs to Get-PSBreakpoint .

Type: Int32[]

Position: 0

Default value: None

Accept pipeline input: True


Accept wildcard characters: False

-Script

Specifies an array of scripts that contain the breakpoints. Enter the path (optional)
and names of
one or more script files. If you omit the path, the default location is the
current directory.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Type

Specifies an array of breakpoint types that this cmdlet gets. Enter one or more types.
The
acceptable values for this parameter are:

Line
Command
Variable

You can also pipe breakpoint types to Get-PSBreakPoint .

Type: BreakpointType[]

Accepted values: Line, Variable, Command

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Variable

Specifies an array of variable breakpoints that are set on the specified variable
names. Enter the
variable names without dollar signs.

Type: String[]
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
Int32

You can pipe breakpoint IDs to this cmdlet.

BreakpointType

You can pipe breakpoint types to this cmdlet.

Outputs
CommandBreakpoint

LineBreakpoint

VariableBreakpoint

Breakpoint

This cmdlet returns objects that represent the breakpoints in the session.

Notes
Windows PowerShell includes the following aliases for Get-PSBreakpoint :

gbp

Related Links
Disable-PSBreakpoint
Enable-PSBreakpoint
Get-PSCallStack
Remove-PSBreakpoint
Set-PSBreakpoint
Get-PSCallStack
Reference
Module: Microsoft.PowerShell.Utility

Displays the current call stack.

Syntax
PowerShell

Get-PSCallStack []

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 .

Examples

Example 1: Get the call stack for a function


PowerShell

PS C:\> function my-alias {

$p = $args[0]

Get-Alias | where {$_.definition -like "*$p"} | format-table 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:\> 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*"} | format-table Definition,

[DBG]: PS C:\ps-test>get-pscallstack

Name CommandLineParameters UnboundArguments


Location

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


----

prompt {} {}
prompt

my-alias {} {get-content}
prompt

prompt {} {}
prompt

PS C:\> [DBG]: PS C:\ps-test> o

Definition Name

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

Get-Content gc

Get-Content cat

Get-Content type

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.

Inputs
None

You can't pipe objects to this cmdlet.


Outputs
CallStackFrame

This cmdlet returns an object representing the items in the call stack.

Related Links
Disable-PSBreakpoint
Enable-PSBreakpoint
Format-Table
Get-PSBreakpoint
Remove-PSBreakpoint
Set-PSBreakpoint
Get-Random
Reference
Module: Microsoft.PowerShell.Utility

Gets a random number, or selects objects randomly from a collection.

Syntax
PowerShell

Get-Random

[-SetSeed <Int32>]

[[-Maximum] <Object>]

[-Minimum <Object>]

[-Count <Int32>]

[<CommonParameters>]

PowerShell

Get-Random

[-SetSeed <Int32>]

[-InputObject] <Object[]>

[-Count <Int32>]

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

You can use the parameters of Get-Random to specify the minimum and maximum
values, the number of
objects returned from a collection, or a seed number.

U Caution

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 can't reset the seed
to its default value.

Deliberately setting the seed results in non-random, repeatable behavior. It should


only be used
when trying to reproduce behavior, such as when debugging or
analyzing a script that includes
Get-Random commands. Be aware that the seed
value could be set by other code in the same
session, such as an imported module.

Examples

Example 1: Get a random integer


This command gets a random integer between 0 (zero) and Int32.MaxValue.

PowerShell

Get-Random

3951433

Example 2: Get a random integer between 0 and 99


PowerShell

Get-Random -Maximum 100

47

Example 3: Get a random integer between -100 and 99


PowerShell

Get-Random -Minimum -100 -Maximum 100

56

Example 4: Get a random floating-point number


This command gets a random floating-point number greater than or equal to 10.7 and
less than 20.92.
PowerShell

Get-Random -Minimum 10.7 -Maximum 20.93

18.08467273887

Example 5: Get a random integer from an array


This command gets a randomly selected number from the specified array.

PowerShell

1, 2, 3, 5, 8, 13 | Get-Random

Example 6: Get several random integers from an array


This command gets three randomly selected numbers in random order from an array.

PowerShell

1, 2, 3, 5, 8, 13 | Get-Random -Count 3

13

Example 7: Randomize an entire collection


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.

PowerShell

1, 2, 3, 5, 8, 13 | Get-Random -Count ([int]::MaxValue)

13

Example 8: Get a random non-numeric value


This command returns a random value from a non-numeric collection.

PowerShell

"red", "yellow", "blue" | Get-Random

yellow

Example 9: Use the SetSeed parameter


This example shows the effect of using the SetSeed parameter.

Because SetSeed produces non-random behavior, it's typically used only to reproduce
results,
such as when debugging or analyzing a script.

PowerShell

# Commands with the default seed are pseudorandom

Get-Random -Maximum 100 -SetSeed 23

Get-Random -Maximum 100


Get-Random -Maximum 100
Get-Random -Maximum 100

74

56

84

46

# Commands with the same seed are not random

Get-Random -Maximum 100 -SetSeed 23

Get-Random -Maximum 100 -SetSeed 23

Get-Random -Maximum 100 -SetSeed 23

74

74

74

# SetSeed results in a repeatable series

Get-Random -Maximum 100 -SetSeed 23

Get-Random -Maximum 100


Get-Random -Maximum 100
Get-Random -Maximum 100
74

56

84

46

Example 10: Get random files


These commands get a randomly selected sample of 50 files from the C: drive of the
local computer.

PowerShell

$Files = Get-ChildItem -Path C:\* -Recurse

$Sample = $Files | Get-Random -Count 50

Example 11: Roll fair dice


This example rolls a fair die 1200 times and counts the outcomes. The first command,
ForEach-Object repeats the call to Get-Random from the piped in numbers (1-6). The

results are
grouped by their value with Group-Object and formatted as a table with
Select-Object .

PowerShell

1..1200 | ForEach-Object {

1..6 | Get-Random

} | Group-Object | Select-Object Name,Count

Name Count

---- -----

1 206

2 199

3 196

4 226

5 185

6 188

Parameters
-Count

Specifies the number of random objects or numbers to return. The default is 1.


When used with InputObject , if the value of Count exceeds the number of objects in
the
collection, Get-Random returns all the objects in random order.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies a collection of objects. Get-Random gets randomly selected objects in


random order from
the collection up to the number specified by Count. 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 .

Type: Object[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Maximum

Specifies a maximum value for the random number. Get-Random returns a value that's
less than the
maximum (not equal). Enter an integer, 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.

On a 64-bit computer, if the value of Minimum is a 32-bit integer, the default value
of
Maximum is Int32.MaxValue.

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.
Type: Object

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Minimum

Specifies a minimum value for the random number. Enter an integer, 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.

Type: Object

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SetSeed

Specifies a seed value for the random number generator. When you use SetSeed, the
cmdlet
generates pseudorandom numbers, which isn't cryptographically secure.

U Caution

Setting the seed results in non-random behavior. It should only be used when
trying to reproduce
behavior, such as when debugging or analyzing a script that
includes Get-Random commands.

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 can't reset the seed


to its default value.
Type: Nullable<T>[Int32]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
Object

You can pipe any object to this cmdlet. It selects values randomly from the piped
objects.

Outputs
Int32

Int64

Double

PSObject

This cmdlet returns an integer or floating-point number, or an object selected randomly


from a
submitted collection.

Notes
By default, Get-Random generates cryptographically secure randomness using the
RandomNumberGenerator class.

Get-Random doesn't always return the same data type as the input value. The following

table shows
the output type for each of the numeric input types.

Input Type Output Type

SByte Double

Byte Double

Int16 Double
Input Type Output Type

UInt16 Double

Int32 Int32

UInt32 Double

Int64 Int64

UInt64 Double

Double Double

Single Double

Beginning in Windows PowerShell 3.0, Get-Random supports 64-bit integers. In Windows


PowerShell
2.0, all values are cast to System.Int32.
Get-Runspace
Reference
Module: Microsoft.PowerShell.Utility

Gets active runspaces within a PowerShell host process.

Syntax
PowerShell

Get-Runspace

[[-Name] <String[]>]

[<CommonParameters>]

PowerShell

Get-Runspace

[-Id] <Int32[]>

[<CommonParameters>]

PowerShell

Get-Runspace

[-InstanceId] <Guid[]>

[<CommonParameters>]

Description
The Get-Runspace cmdlet gets active runspaces in a PowerShell host process.

Examples

Example 1: Get runspaces


PowerShell

Get-Runspace

Id Name ComputerName Type State Availability

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

1 Runspace1 localhost Local Opened Busy

2 Runspace2 localhost Local Opened Available

3 Runspace3 localhost Local Opened Available

Example 2: Get runspace by Id


PowerShell

Get-Runspace -Id 2

Id Name ComputerName Type State Availability

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

2 Runspace2 localhost Local Opened Available

Example 3: Get runspace by Name


PowerShell

Get-Runspace -Name Runspace1

Id Name ComputerName Type State Availability

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

1 Runspace1 localhost Local Opened Busy

Example 4: Get runspace by InstanceId


In this example, we identify an available runspace using the Name parameter and store
the return
object to the variable $activeRunspace . This allows you to use the properties
of the Runspace
in subsequent runs of Get-Runspace .

PowerShell

$activeRunspace = Get-Runspace -Name Runspace1

Get-Runspace -InstanceId $activeRunspace.InstanceId

Id Name ComputerName Type State Availability

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

1 Runspace1 localhost Local Opened Busy

Parameters
-Id
Specifies the Id of a runspace

Type: Int32[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InstanceId

Specifies the instance ID GUID of a running job.

Type: Guid[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Name

Specifies the Name of a runspace

Type: String[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Outputs
Runspace

This cmdlet returns a Runspace. You can pipe the results of a Get-Runspace command to
Debug-Runspace .
Related Links
Debug-Runspace
Get-RunspaceDebug
Reference
Module: Microsoft.PowerShell.Utility

Shows runspace debugging options.

Syntax
PowerShell

Get-RunspaceDebug

[[-RunspaceName] <String[]>]

[<CommonParameters>]

PowerShell

Get-RunspaceDebug

[-Runspace] <Runspace[]>

[<CommonParameters>]

PowerShell

Get-RunspaceDebug

[-RunspaceId] <Int32[]>

[<CommonParameters>]

PowerShell

Get-RunspaceDebug

[-RunspaceInstanceId] <Guid[]>
[<CommonParameters>]

PowerShell

Get-RunspaceDebug

[[-ProcessName] <String>]

[[-AppDomainName] <String[]>]

[<CommonParameters>]

Description
The Get-RunspaceDebug cmdlet shows runspace debugging options.

Examples

1: Show the state of the default runspace debugger


PowerShell

Get-RunspaceDebug

Id Name Enabled BreakAll

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

1 Runspace1 False False

Parameters
-AppDomainName

The name of the application domain that hosts the PowerShell runspace.

Type: String[]

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ProcessName

The name of the process that hosts the PowerShell runspace.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-Runspace

One or more Runspace objects to be disabled.

Type: Runspace[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-RunspaceId

One or more Runspace Id numbers to be disabled.

Type: Int32[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RunspaceInstanceId

One or more Runspace GUIDs to be disabled.

Type: Guid[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RunspaceName

One or more Runspace names to be disabled.

Type: String[]

Position: 0
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Related Links
Disable-RunspaceDebug
Enable-RunspaceDebug
Get-TraceSource
Reference
Module: Microsoft.PowerShell.Utility

Gets PowerShell components that are instrumented for tracing.

Syntax
PowerShell

Get-TraceSource

[[-Name] <String[]>]

[<CommonParameters>]

Description
The Get-TraceSource cmdlet gets the trace sources for PowerShell components that are
currently in
use. You can use the data to determine which 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 PowerShell developers, but they are available to
all users.

Examples

Example 1: Get trace sources by name


PowerShell

Get-TraceSource -Name "*provider*"

This command gets all of the trace sources that have names that include provider.

Example 2: Get all trace sources


PowerShell
Get-TraceSource

This command gets all of the PowerShell components that can be traced.

Parameters
-Name

Specifies the trace sources to get. Wildcards are permitted. The parameter name
Name is
optional.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

Inputs
String

You can pipe a string that contains the name of a trace source to this cmdlet.

Outputs
PSTraceSource

This cmdlet returns objects representing the trace sources.

Related Links
Set-TraceSource
Trace-Command
Get-TypeData
Reference
Module: Microsoft.PowerShell.Utility

Gets the extended type data in the current session.

Syntax
PowerShell

Get-TypeData

[[-TypeName] <String[]>]

[<CommonParameters>]

Description
The Get-TypeData cmdlet gets the extended type data in the current session. This
includes type
data that was added to the session by Types.ps1xml file and dynamic type
data that was added by
using the parameter of the Update-TypeData cmdlet.

You can use the extended type data that Get-TypeData returns to examine the type data
in the
session and send it to the Update-TypeData and Remove-TypeData cmdlets.

Extended type data adds properties and methods to objects in PowerShell. You can use
the added
properties and methods in the same ways that you would use the properties
and methods that are
defined in the object type. However, when writing scripts, be
aware that the added properties and
methods might not be present in every PowerShell
session.

For more information about Types.ps1xml files, see


about_Types.ps1xml. For more
information
about dynamic type data that the Update-TypeData cmdlet adds, see
Update-TypeData .

This cmdlet was introduced in Windows PowerShell 3.0.

Examples

Example 1: Get all extended type data


This example gets all extended type data in the current session.

PowerShell

Get-TypeData

Example 2: Get type data by name


This example gets all type data in the current session whose name is qualified with
"System.IO".

PowerShell

Get-TypeData -TypeName System.IO.*

TypeName Members

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

System.IO.DirectoryInfo {[Mode,
System.Management.Automation.Runspaces.CodePropert…

System.IO.FileInfo {[Mode,
System.Management.Automation.Runspaces.CodePropert…

Example 3: Get the script block that creates a property


value
This example gets the script block that creates the value of the EventID property of
EventLogEntry objects.

PowerShell

(Get-TypeData *EventLogEntry*).Members.EventID

GetScriptBlock SetScriptBlock IsHidden Name

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

$this.get_EventID() -band 0xFFFF False EventID

Example 4: Get the script block that defines a property


for a specified object
This example gets the script block that defines the DateTime property of
System.DateTime
objects in PowerShell.

PowerShell
(Get-TypeData -TypeName System.DateTime).Members["DateTime"].GetScriptBlock

if ((& { Set-StrictMode -Version 1; $this.DisplayHint }) -ieq "Date") {

"{0}" -f $this.ToLongDateString()

elseif ((& { Set-StrictMode -Version 1; $this.DisplayHint }) -ieq "Time") {

"{0}" -f $this.ToLongTimeString()

else {

"{0} {1}" -f $this.ToLongDateString(), $this.ToLongTimeString()

The command uses the Get-TypeData cmdlet to get the extended type data for the
System.DataTime
type. The command gets the Members property of the TypeData
object.

The Members property contains a hash table of properties and methods that are
defined by extended
type data. Each key in the Members hash table is a property or
method name and each value is the
definition of the property or method value.

The command gets the DateTime key in Members and its GetScriptBlock property
value.

The output shows the script block that creates the value of the DateTime property of
every
System.DateTime object in PowerShell.

Parameters
-TypeName

Specifies type data as an array only for the types with the specified names. By
default,
Get-TypeData gets all types in the session.

Enter type names or a name patterns. Full names, or name patterns with wildcard
characters are
required, even for types in the System namespace. Wildcards are
supported and the parameter name
TypeName is optional. You can also pipe type
names to Get-TypeData .

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True


Inputs
String

You can pipe strings containing type names to this cmdlet.

Outputs
TypeData

Notes
Get-TypeData gets only the extended type data in the current session. It does not get

extended
type data that is on the computer, but has not been added to the current
session, such as extended
types that are defined in modules that have not been
imported into the current session.

Related Links
about_Types.ps1xml
Remove-TypeData
Update-TypeData
Get-UICulture
Reference
Module: Microsoft.PowerShell.Utility

Gets the current UI culture settings in the operating system.

Syntax
PowerShell

Get-UICulture []

Description
The Get-UICulture cmdlet gets information about the current user interface (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.

Examples

Example 1: Get the UI culture


PowerShell

Get-UICulture

This command gets the current UI culture information.

Example 2: Get the UI culture and format the results


PowerShell

Get-UICulture | Format-List *
This command displays the values of all of the properties of the current UI culture in a
list.

Example 3: Get the value of the Calendar property


PowerShell

(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: Get the short date pattern


PowerShell

(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 | Get-Member .

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
CultureInfo

This cmdlet returns an object representing the current UI culture. In PowerShell 3.0 and
later,
it returns a CultureInfo object.

Microsoft.PowerShell.VistaCultureInfo

In Windows PowerShell 2.0 and earlier, this cmdlet returns a VistaCultureInfo object.
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.
Get-Unique
Reference
Module: Microsoft.PowerShell.Utility

Returns unique items from a sorted list.

Syntax
PowerShell

Get-Unique

[-InputObject <PSObject>]

[-AsString]

[<CommonParameters>]

PowerShell

Get-Unique

[-InputObject <PSObject>]

[-OnType]

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

Get-Unique is case-sensitive. As a result, strings that differ only in character casing are
considered to be unique.

Examples

Example 1: Get unique words in a text file


These commands find the number of unique words in a text file.

PowerShell
$A = $( foreach ($line in Get-Content C:\Test1\File1.txt) {

$line.tolower().split(" ")

}) | Sort-Object | Get-Unique

$A.count

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: Get unique integers in an array


This command finds the unique members of the set of integers.

PowerShell

1,1,1,1,12,23,4,5,4643,5,3,3,3,3,3,3,3 | Sort-Object | Get-Unique

12

23

4643

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: Get unique object types in a directory


This command uses the Get-ChildItem cmdlet to retrieve the contents of the local
directory, which
includes files and directories.

PowerShell

Get-ChildItem | Sort-Object {$_.GetType()} | Get-Unique -OnType


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: Get unique processes


This command gets the names of processes running on the computer with duplicates
eliminated.

PowerShell

Get-Process | Sort-Object | Select-Object processname | Get-Unique -AsString

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.

Parameters
-AsString

Indicates that this cmdlet uses 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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-InputObject

Specifies input for Get-Unique . Enter a variable that contains the objects or type a
command or
expression that gets the objects.

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

Type: PSObject

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-OnType

Indicates that this cmdlet returns only one object of each type.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSObject

You can pipe any type of object to this cmdlet.

Outputs
PSObject
This cmdlet returns its input objects without duplicates.

Notes
Windows PowerShell includes the following aliases for Get-Unique :

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.

Related Links
Select-Object
Sort-Object
Get-Variable
Reference
Module: Microsoft.PowerShell.Utility

Gets the variables in the current console.

Syntax
PowerShell

Get-Variable

[[-Name] <String[]>]

[-ValueOnly]

[-Include <String[]>]

[-Exclude <String[]>]

[-Scope <String>]

[<CommonParameters>]

Description
The Get-Variable cmdlet gets the 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.

Examples

Example 1: Get variables by letter


This command gets variables with names that begin with the letter m.
The command
also gets the value of the variables.

PowerShell

Get-Variable m*

Example 2: Get variable values by letter


This command gets only the values of the variables that have names that begin with m.
PowerShell

Get-Variable m* -ValueOnly

Example 3: Get variables by two letters


This command gets information about the variables that begin with either the letter M
or the letter
P.

PowerShell

Get-Variable -Include M*,P*

Example 4: Get variables by scope


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

PowerShell

Get-Variable -Scope 0

Compare-Object (Get-Variable -Scope 0) (Get-Variable -Scope 1)

Parameters
-Exclude

Specifies an array of items that this cmdlet excludes from the operation.
Wildcards
are permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True


-Include

Specifies an array of items upon which the cmdlet will act, excluding all others.
Wildcards are permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Name

Specifies the name of the variable.


Wildcards are permitted.
You can also pipe a
variable name to Get-Variable .

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-Scope

Specifies the variables in the scope.The acceptable values for this parameter are:

Global
Local
Script
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.

Type: String

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-ValueOnly

Indicates that this cmdlet gets only the value of the variable.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a string that contains the variable name to this cmdlet.

Outputs
PSVariable

By default, this cmdlet returns a AutomationPSVariable object for each variable that it
gets.
The object type depends on the variable.

Object[]

When you specify the ValueOnly parameter and the specified variable's value is a
collection,
this cmdlet returns a [System.Object[]] . This behavior prevents normal
pipeline operation from
processing the variable's values one at a time. A workaround to
force collection enumeration is to
enclose the Get-Variable command in parenthesis.

Notes
Windows PowerShell includes the following aliases for Get-Variable :

gv
This cmdlet does not manage environment variables. To manage environment
variables, you can use
the environment variable provider.

Related Links
Clear-Variable
New-Variable
Remove-Variable
Set-Variable
Group-Object
Reference
Module: Microsoft.PowerShell.Utility

Groups objects that contain the same value for specified properties.

Syntax
PowerShell

Group-Object

[-NoElement]

[-AsHashTable]

[-AsString]

[-InputObject <PSObject>]

[[-Property] <Object[]>]

[-Culture <String>]

[-CaseSensitive]

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

Examples

Example 1: Group files by extension


This example recursively gets the files under $PSHOME and groups them by filename
extension. The
output is sent to the Sort-Object cmdlet, which sorts them by the count
files found for the given
extension. The empty Name represents directories.

This example uses the NoElement parameter to omit the members of the group.
PowerShell

$files = Get-ChildItem -Path $PSHOME -Recurse

$files |

Group-Object -Property extension -NoElement |

Sort-Object -Property Count -Descending

Count Name

----- ----

365 .xml

231 .cdxml

197

169 .ps1xml

142 .txt

114 .psd1

63 .psm1

49 .xsd

36 .dll

15 .mfl

15 .mof

...

Example 2: Group integers by odds and evens


This example shows how to use script blocks as the value of the Property parameter.
This command
displays the integers from 1 to 20, grouped by odds and even.

PowerShell

1..20 | Group-Object -Property {$_ % 2}

Count Name Group

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

10 0 {2, 4, 6, 8...}

10 1 {1, 3, 5, 7...}

Example 3: Group event log events by EntryType


This example displays the 1,000 most recent entries in the System event log, grouped by
EntryType.

In the output, the Count column represents the number of entries in each group. The
Name
column represents the EventType values that define a group. The Group column
represents the
objects in each group.

PowerShell
Get-WinEvent -LogName System -MaxEvents 1000 | Group-Object -Property
LevelDisplayName

Count Name Group

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

153 Error {System.Diagnostics.Eventing.Reader.EventLogRecord,


System.Diag...}

722 Information {System.Diagnostics.Eventing.Reader.EventLogRecord,


System.Diag...}

125 Warning {System.Diagnostics.Eventing.Reader.EventLogRecord,


System.Diag...}

Example 4: Group processes by priority class


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
and sends the
objects down the pipeline. Group-Object groups the objects by the value
of the PriorityClass
property of the process.

The second example uses the NoElement parameter to remove the members of the
group from the
output. The result is a table with only the Count and Name property
value.

The results are shown in the following sample output.

PowerShell

Get-Process | Group-Object -Property PriorityClass

Count Name Group

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

55 Normal {System.Diagnostics.Process (AdtAgent),


System.Diagnosti...

1 {System.Diagnostics.Process (Idle)}

3 High {System.Diagnostics.Process (Newproc),


System.Diagnostic...

2 BelowNormal {System.Diagnostics.Process (winperf),

Get-Process | Group-Object -Property PriorityClass -NoElement

Count Name

----- ----

55 Normal

3 High

2 BelowNormal
Example 5: Group processes by name
The following example uses Group-Object to group multiple instances of processes
running on the
local computer. Where-Object displays processes with more than one
instance.

PowerShell

Get-Process | Group-Object -Property Name -NoElement | Where-Object


{$_.Count -gt 1}

Count Name

----- ----

2 csrss

5 svchost

2 winlogon

2 wmiprvse

Example 6: Group objects in a hash table


This example uses the AsHashTable and AsString parameters to return the groups in a
hash
table, 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, $A.Get to display the values of the Get key in $A .
The
values are CmdletInfo object. The AsString parameter doesn't convert the objects in
the
groups to strings.

PowerShell

$A = Get-Command Get-*, Set-* -CommandType cmdlet |

Group-Object -Property Verb -AsHashTable -AsString

$A

Name Value

---- -----

Get {Get-Acl, Get-Alias, Get-AppLockerFileInformation, Get-


AppLockerPolicy...}

Set {Set-Acl, Set-Alias, Set-AppBackgroundTaskResourcePolicy, Set-


AppLockerPolicy...}

$A.Get

CommandType Name Version Source

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

Cmdlet Get-Acl 3.0.0.0


Microsoft.PowerShell.Security

Cmdlet Get-Alias 3.1.0.0


Microsoft.PowerShell.Utility

Cmdlet Get-AppLockerFileInformation 2.0.0.0 AppLocker

Cmdlet Get-AppLockerPolicy 2.0.0.0 AppLocker

...

Example 10: Group hashtables by their key values with


calculated properties
This example shows how you can group hashtable objects by the value of their keys.
You can
specify one or more scriptblocks for the Property parameter. The expressions in
these
scriptblocks are used to group for the input like the values for named properties.

PowerShell

@(

@{ name = 'a' ; weight = 7 }

@{ name = 'b' ; weight = 1 }

@{ name = 'c' ; weight = 3 }

@{ name = 'd' ; weight = 7 }

) | Group-Object -Property { $_.weight } -NoElement

Count Name

----- ----

2 7

1 1

1 3

Parameters
-AsHashTable

Indicates that this cmdlet 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.

Type: SwitchParameter

Aliases: AHT

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-AsString

Indicates that this cmdlet 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.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-CaseSensitive

Indicates that this cmdlet makes the grouping case-sensitive. Without this
parameter, the property
values of objects in a group might have different cases.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


-Culture

Specifies the culture to use when comparing strings.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

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 .

Type: PSObject

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-NoElement

Indicates that this cmdlet omits the members of a group from the results.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


-Property

Specifies the properties for grouping. The objects are arranged into named groups
based on the value
of the specified properties. When no property is specified,
objects are grouped by their value or
the ToString() representation of their value.
The output is sorted in ascending order by the group
names.

The value of the Property parameter can be a new calculated property. The
calculated property
can be a script block or a hash table. Valid key-value pairs are:

Expression - <string> or <script block>

For more information, see


about_Calculated_Properties.

Type: Object[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSObject

You can pipe any object to this cmdlet.

Outputs
GroupInfo

By default, this cmdlet returns a GroupInfo object.

Hashtable

When you use the AsHashTable parameter, this cmdlet returns a Hashtable object.

Notes
Windows PowerShell includes the following aliases for Group-Object :

group
You can use the GroupBy parameter of the formatting cmdlets, such as Format-Table
and
Format-List , 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 doesn't require that the objects being grouped are of the same Microsoft

.NET type.
When grouping objects of different .NET 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 type, the property values are grouped by 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 type in different objects, Group-Object uses the .NET type of
the first occurrence of the
property as the .NET 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 isn't included in the
group.

Missing Properties.

Objects that don't have a specified property can't be grouped. Objects that aren't
grouped appear
in the final GroupInfo object output in a group named
AutomationNull.Value .

The output is sorted in ascending order by the group names. The items belonging to
each group are
not sorted. They are listed in the order in which they were received.

Related Links
about_Calculated_Properties
about_Hash_Tables
Compare-Object
ForEach-Object
Measure-Object
New-Object
Select-Object
Sort-Object
Tee-Object
Where-Object
Import-Alias
Reference
Module: Microsoft.PowerShell.Utility

Imports an alias list from a file.

Syntax
PowerShell

Import-Alias

[-Path] <String>

[-Scope <String>]

[-PassThru]

[-Force]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Import-Alias

-LiteralPath <String>

[-Scope <String>]

[-PassThru]

[-Force]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Import-Alias cmdlet imports an alias list from a file.

Beginning in Windows PowerShell 3.0, as a security feature, Import-Alias does not


overwrite existing aliases by default.
To overwrite an existing alias, after assuring that the
contents of the alias file is safe, use the Force parameter.

Examples

Example 1: Import aliases from a file


PowerShell

Import-Alias test.txt

This command imports alias information from a file named test.txt.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Force

Allows the cmdlet to import an alias that is already defined or is read only.
You can
use the following command to display information about the currently-defined
aliases:

Get-Alias | Select-Object Name, Options

If the corresponding alias is read-only, it will be displayed in the value of the Options
property.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-LiteralPath
Specifies the path to a file that includes exported alias information.
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 PowerShell not to
interpret any characters as escape sequences.

Type: String

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-PassThru

Returns an object representing the item with which you are working.
By default, this
cmdlet does not generate any output.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Path

Specifies the path to a file that includes exported alias information.


Wildcards are
allowed but they must resolve to a single name.

Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True


-Scope

Specifies the scope into which the aliases are imported.


The acceptable values for
this parameter are:

Global
Local
Script
A number relative to the current scope (0 through the number of scopes, where
0 is the current scope and 1 is its parent)

The default is Local.


For more information, see about_Scopes.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs.


The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a string that contains a path to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

AliasInfo

When you use the PassThru parameter, this cmdlet returns an AliasInfo object
representing
the alias.

Notes
Windows PowerShell includes the following aliases for Import-Alias :

ipal

Related Links
Export-Alias
Get-Alias
New-Alias
Set-Alias
Import-Clixml
Reference
Module: Microsoft.PowerShell.Utility

Imports a CLIXML file and creates corresponding objects in PowerShell.

Syntax
PowerShell

Import-Clixml

[-Path] <String[]>

[-IncludeTotalCount]

[-Skip <UInt64>]

[-First <UInt64>]

[<CommonParameters>]

PowerShell

Import-Clixml

-LiteralPath <String[]>

[-IncludeTotalCount]

[-Skip <UInt64>]

[-First <UInt64>]

[<CommonParameters>]

Description
The Import-Clixml cmdlet imports a Common Language Infrastructure (CLI) XML file
with data that
represents Microsoft .NET Framework objects and creates the PowerShell
objects. For more information
about CLI, see Language independence.

A valuable use of Import-Clixml on Windows computers is to import credentials and


secure strings
that were exported as secure XML using Export-Clixml . For an example,
see Example 2.

Import-Clixml uses the byte-order-mark (BOM) to detect the encoding format of the

file. If the
file has no BOM, it assumes the encoding is UTF8.

Examples
Example 1: Import a serialized file and recreate an object
This example uses the Export-Clixml cmdlet to save a serialized copy of the process
information
returned by Get-Process . Import-Clixml retrieves the serialized file's
contents and recreates an
object that is stored in the $Processes variable.

PowerShell

Get-Process | Export-Clixml -Path .\pi.xml

$Processes = Import-Clixml -Path .\pi.xml

Example 2: Import a secure credential object


In this example, given a credential that you've stored in the $Credential variable by
running the
Get-Credential cmdlet, you can run the Export-Clixml cmdlet to save the
credential to disk.

) Important

Export-Clixml only exports encrypted credentials on Windows. On non-Windows


operating systems
such as macOS and Linux, credentials are exported in plain text.

PowerShell

$Credxmlpath = Join-Path (Split-Path $Profile) TestScript.ps1.credential

$Credential | Export-Clixml $Credxmlpath

$Credxmlpath = Join-Path (Split-Path $Profile) TestScript.ps1.credential

$Credential = Import-Clixml $Credxmlpath

The Export-Clixml cmdlet encrypts credential objects by using the Windows Data
Protection API.
The encryption ensures that only your user account can decrypt the
contents of the credential
object. The exported CLIXML file can't be used on a different
computer or by a different user.

In the example, the file in which the credential is stored is represented by


TestScript.ps1.credential . Replace TestScript with the name of the script with which

you're
loading the credential.

You send the credential object down the pipeline to Export-Clixml , and save it to the
path,
$Credxmlpath , that you specified in the first command.
To import the credential automatically into your script, run the final two commands. Run
Import-Clixml to import the secured credential object into your script. This import
eliminates the
risk of exposing plain-text passwords in your script.

Parameters
-First

Gets only the specified number of objects. Enter the number of objects to get.

Type: UInt64

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-IncludeTotalCount

Reports the total number of objects in the data set followed by the selected objects.
If the cmdlet
can't determine the total count, it displays Unknown total count. The
integer has an
Accuracy property that indicates the reliability of the total count
value. The value of
Accuracy ranges from 0.0 to 1.0 where 0.0 means that the
cmdlet couldn't count the
objects, 1.0 means that the count is exact, and a value
between 0.0 and 1.0 indicates an
increasingly reliable estimate.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-LiteralPath

Specifies the path to the XML files. Unlike Path, the value of the LiteralPath
parameter is
used exactly as it's typed. No characters are interpreted as wildcards. If
the path includes escape
characters, enclose it in single quotation marks. Single
quotation marks tell PowerShell not to
interpret any characters as escape sequences.
Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Path

Specifies the path to the XML files.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Skip

Ignores the specified number of objects and then gets the remaining objects. Enter
the number of
objects to skip.

Type: UInt64

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a string containing a path to this cmdlet.


Outputs
PSObject

This cmdlet returns objects that were 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> .

Related Links
Export-Clixml
Introducing XML Serialization
Join-Path
Securely Store Credentials on Disk
Use PowerShell to Pass Credentials to Legacy Systems
Import-Csv
Reference
Module: Microsoft.PowerShell.Utility

Creates table-like custom objects from the items in a character-separated value (CSV)
file.

Syntax
PowerShell

Import-Csv

[[-Path] <string[]>]

[[-Delimiter] <char>]

[-LiteralPath <string[]>]

[-Header <string[]>]

[-Encoding <string>]

[<CommonParameters>]

PowerShell

Import-Csv

[[-Path] <string[]>]

-UseCulture

[-LiteralPath <string[]>]

[-Header <string[]>]

[-Encoding <string>]

[<CommonParameters>]

Description
The Import-Csv cmdlet creates table-like custom objects from the items in CSV files.
Each column
in the CSV file becomes a property of the custom object and the items in
rows become the property
values. Import-Csv works on any CSV file, including 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
and the item
delimiter, or direct Import-Csv to use the list separator for the current
culture as the item
delimiter.
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 deal with files.

If a header row entry in a CSV file contains an empty or null value, PowerShell inserts a
default
header row name and displays a warning message.

Import-Csv uses the byte-order-mark (BOM) to detect the encoding format of the file. If

the
file has no BOM, it assumes the encoding is UTF8.

Examples

Example 1: Import process objects


This example shows how to export and then import a CSV file of process objects.

PowerShell

Get-Process | Export-Csv -Path .\Processes.csv

$P = Import-Csv -Path .\Processes.csv

$P | 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()

BasePriority NoteProperty string BasePriority=8

Company NoteProperty string Company=Microsoft Corporation

...

$P | Format-Table

Name SI Handles VM WS PM NPM


Path

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


---

ApplicationFrameHost 4 407 2199293489152 15884288 15151104 23792


C:\WINDOWS\system32\ApplicationFrameHost.exe

...

wininit 0 157 2199112204288 4591616 1630208 10376

winlogon 4 233 2199125549056 7659520 2826240 10992


C:\WINDOWS\System32\WinLogon.exe

WinStore.App 4 846 873435136 33652736 26607616 55432


C:\Program
Files\WindowsApps\Microsoft.WindowsStore_11712.1001.13.0_x64__8weky...

WmiPrvSE 0 201 2199100219392 8830976 3297280 10632


C:\WINDOWS\system32\wbem\wmiprvse.exe

WmiPrvSE 0 407 2199157727232 18509824 12922880 16624


C:\WINDOWS\system32\wbem\wmiprvse.exe

WUDFHost 0 834 2199310204928 51945472 87441408 24984


C:\Windows\System32\WUDFHost.exe

The Get-Process cmdlet sends process objects down the pipeline to the Export-Csv .
The
Export-Csv cmdlet converts the process objects to CSV strings and saves the strings
in the
Processes.csv file. The Import-Csv cmdlet imports the CSV strings from the
Processes.csv file.
The strings are saved in the $P variable. The $P variable is sent down
the pipeline to the
Get-Member cmdlet that displays the properties of the imported CSV
strings. The $P variable
is sent down the pipeline to the Format-Table cmdlet and
displays the objects.

Example 2: Specify the delimiter


This example shows how to use the Delimiter parameter of the Import-Csv cmdlet.

PowerShell

Get-Process | Export-Csv -Path .\Processes.csv -Delimiter :

$P = Import-Csv -Path .\Processes.csv -Delimiter :

$P | Format-Table

The Get-Process cmdlet sends process objects down the pipeline to Export-Csv . The
Export-Csv
cmdlet converts the process objects to CSV strings and saves the strings in

the Processes.csv file.


The Delimiter parameter is used to specify a colon delimiter. The
Import-Csv cmdlet imports
the CSV strings from the Processes.csv file. The strings are

saved in the $P variable. To $P


variable is sent down the pipeline to the Format-Table
cmdlet.

Example 3: Specify the current culture for the delimiter


This example shows how to use the Import-Csv cmdlet with the UseCulture parameter.

PowerShell

(Get-Culture).TextInfo.ListSeparator

Get-Process | Export-Csv -Path .\Processes.csv -UseCulture

Import-Csv -Path .\Processes.csv -UseCulture


The Get-Culture cmdlet uses the nested properties TextInfo and ListSeparator to get
the
current culture's default list separator. The Get-Process cmdlet sends process
objects down the
pipeline to Export-Csv . The Export-Csv cmdlet converts the process
objects to CSV strings and
saves the strings in the Processes.csv file. The UseCulture
parameter uses the current
culture's default list separator. The Import-Csv cmdlet
imports the CSV strings from the
Processes.csv file.

Example 4: Change property names in an imported object


This example shows how to use the Header parameter of Import-Csv to change the
names of
properties in the resulting imported object.

PowerShell

Start-Job -ScriptBlock { Get-Process } | Export-Csv -Path .\Jobs.csv -


NoTypeInformation

$Header = 'State', 'MoreData', 'StatusMessage', 'Location', 'Command',


'StateInfo', 'Finished',

'InstanceId', 'Id', 'Name', 'ChildJobs', 'BeginTime', 'EndTime',


'JobType', 'Output', 'Error',

'Progress', 'Verbose', 'Debug', 'Warning', 'Information'

# Delete the default header from file

$A = Get-Content -Path .\Jobs.csv

$A = $A[1..($A.Count - 1)]

$A | Out-File -FilePath .\Jobs.csv

$J = Import-Csv -Path .\Jobs.csv -Header $Header

$J

State : Running

MoreData : True

StatusMessage :

Location : localhost

Command : Get-Process

StateInfo : Running

Finished : System.Threading.ManualResetEvent

InstanceId : a259eb63-6824-4b97-a033-305108ae1c2e

Id : 1

Name : Job1

ChildJobs :
System.Collections.Generic.List`1[System.Management.Automation.Job]

BeginTime : 12/20/2018 18:59:57

EndTime :

JobType : BackgroundJob

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.Management.Automation
.VerboseRecord]

Debug :
System.Management.Automation.PSDataCollection`1[System.Management.Automation
.DebugRecord]

Warning :
System.Management.Automation.PSDataCollection`1[System.Management.Automation
.WarningRecord]

Information :
System.Management.Automation.PSDataCollection`1[System.Management.Automation
.InformationRecord]

The Start-Job cmdlet starts a background job that runs Get-Process . A job object is
sent down
the pipeline to the Export-Csv cmdlet and converted to a CSV string. The
NoTypeInformation
parameter removes the type information header from CSV output
and is optional in PowerShell v6 and
higher. The $Header variable contains a custom
header that replaces the following default values:
HasMoreData, JobStateInfo,
PSBeginTime, PSEndTime, and PSJobTypeName. The $A
variable uses the Get-Content
cmdlet to get the CSV string from the Jobs.csv file. The $A
variable is used to remove
the default header from the file. The Out-File cmdlet saves the new
version of the
Jobs.csv file in the $A variable. The Import-Csv cmdlet imports the Jobs.csv file
and uses
the Header parameter to apply the $Header variable. The $J variable contains the
imported PSCustomObject and displays the object in the PowerShell console.

Example 5: Create a custom object using a CSV file


This example shows how to create a custom object in PowerShell by using a CSV file.

PowerShell

Get-Content -Path .\Links.csv

113207,about_Aliases

113208,about_Arithmetic_Operators

113209,about_Arrays

113210,about_Assignment_Operators

113212,about_Automatic_Variables

113213,about_Break

113214,about_Command_Precedence

113215,about_Command_Syntax

144309,about_Comment_Based_Help

113216,about_CommonParameters

113217,about_Comparison_Operators

113218,about_Continue

113219,about_Core_Commands

113220,about_Data_Section

$A = Import-Csv -Path .\Links.csv -Header 'LinkID', 'TopicTitle'

$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()

LinkID NoteProperty string LinkID=113207

TopicTitle NoteProperty string TopicTitle=about_Aliases

$A | Where-Object -Property TopicTitle -Like '*alias*'

LinkID TopicTitle

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

113207 about_Aliases

To create your Links.csv file, use the values shown in the Get-Content output.

The Get-Content cmdlet displays the Links.csv file. The Import-Csv cmdlet imports the
Links.csv
file. The Header parameter specifies the property names LinkId and TopicTitle.
The
objects are stored in the $A variable. The Get-Member cmdlet shows the property
names from the
Header parameter. The Where-Object cmdlet selects objects with the
TopicTitle property
that includes alias.

Example 6: Import a CSV that is missing a value


This example shows how the Import-Csv cmdlet in PowerShell responds when the
header row in a CSV
file includes a null or empty value. Import-Csv substitutes a default
name for the missing header
row that becomes the property name of the object that
Import-Csv returns.

PowerShell

Get-Content -Path .\Projects.csv

ProjectID,ProjectName,,Completed

13,Inventory,Redmond,True

440,,FarEast,True

469,Marketing,Europe,False

Import-Csv -Path .\Projects.csv

WARNING: One or more headers were not specified. Default names starting with
"H" have been used in

place of any missing headers.

ProjectID ProjectName H1 Completed

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

13 Inventory Redmond True

440 FarEast True

469 Marketing Europe False

(Import-Csv -Path .\Projects.csv).H1

WARNING: One or more headers were not specified. Default names starting with
"H" have been used in

place of any missing headers.

Redmond

FarEast

Europe

To create your Projects.csv file, use the values shown in the example's Get-Content
output.

The Get-Content cmdlet displays the Projects.csv file. The header row is missing a value
between
ProjectName and Completed. The Import-Csv cmdlet imports the Projects.csv
file and
displays a warning message because H1 is a default header name. The (Import-
Csv -Path .\Projects.csv).H1 command gets the H1 property values and displays a
warning.

Parameters
-Delimiter

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 single


quotation marks. To specify escaped special characters such as tab ( `t ), enclose it in
double
quotation marks.

If you specify a character other than the actual string delimiter in the file, Import-Csv
cannot
create the objects from the CSV strings and will return the CSV strings.

Type: Char

Position: 1
Default value: comma (,)

Accept pipeline input: False

Accept wildcard characters: False

-Encoding

Specifies the type of encoding for the target file. The default value is Default .

The acceptable values for this parameter are as follows:

ASCII Uses ASCII (7-bit) character set.

BigEndianUnicode Uses UTF-16 with the big-endian byte order.


Default Uses the encoding that corresponds to the system's active code page

(usually ANSI).
OEM Uses the encoding that corresponds to the system's current OEM code
page.
Unicode Uses UTF-16 with the little-endian byte order.
UTF7 Uses UTF-7.

UTF8 Uses UTF-8.

UTF32 Uses UTF-32 with the little-endian byte order.

Type: String

Accepted values: ASCII, BigEndianUnicode, Default, OEM, Unicode, UTF7, UTF8,


UTF32

Position: Named

Default value: Default

Accept pipeline input: False

Accept wildcard characters: False

-Header

Specifies an alternate column header row for the imported file. The column header
determines the
property names of the objects created by Import-Csv .

Enter column headers as a character-separated list. Do not enclose the header string
in quotation
marks. Enclose each column header in single quotation marks.
If you enter fewer column headers than there are data columns, the remaining data
columns are
discarded. If you enter more column headers than there are data
columns, the additional column
headers are created with empty data columns.

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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-LiteralPath

Specifies the path to the CSV file to import. 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
PowerShell not to interpret any characters as escape sequences.

Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Path

Specifies the path to the CSV file to import.


You can also pipe a path to Import-Csv .

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True


Accept wildcard characters: False

-UseCulture

Uses the list separator for the current culture as the item delimiter. To find the list
separator
for a culture, use the following command: (Get-
Culture).TextInfo.ListSeparator .

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a string that contains a path to this cmdlet.

Outputs
Object

This cmdlet returns the objects described by the content in the CSV file.

Notes
Windows PowerShell includes the following aliases for Import-Csv :

ipcsv

Because the imported objects are CSV versions of the object type, they are not
recognized and
formatted by the PowerShell type formatting entries that format the
non-CSV versions of the object
type.

The result of an Import-Csv command is a collection of strings that form a table-like


custom
object. Each row is a separate string, so you can use the Count property of the
object to count
the table rows. The columns are the properties of the object and items
in the rows are the property
values.

The column header row determines the number of columns and the column names. The
column names are
also the names of the properties of the objects. The first row is
interpreted to be the column
headers, unless you use the Header parameter to specify
column headers. If any row has more
values than the header row, the additional values
are ignored.

If the column header row is missing a value or contains a null or empty value, Import-
Csv uses
H followed by a number for the missing column header and property name.

In the CSV file, each object is represented by a character-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 represented by the name of the property value.
Export-Csv does not export the
methods of the object.

Related Links
ConvertFrom-Csv
ConvertTo-Csv
Export-Csv
Get-Culture
Import-LocalizedData
Reference
Module: Microsoft.PowerShell.Utility

Imports language-specific data into scripts and functions based on the UI culture that's
selected
for the operating system.

Syntax
PowerShell

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's 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's 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
filename, to add supported commands, and to suppress the error message
that appears if the .psd1
files aren't found.

The Import-LocalizedData cmdlet supports the script internationalization initiative that


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

Examples

Example 1: Import text strings


This example imports text strings into the $Messages variable. It uses the default values
of all
other cmdlet parameters.

PowerShell

Import-LocalizedData -BindingVariable "Messages"

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 into the $Messages variable.

Example 2: Import localized data strings


This example is run at the command line not in a script. It gets localized data strings
from the
Test.psd1 file and displays them at the command line. Because the command
isn't used in a script,
the FileName parameter is required. The command uses the
UICulture parameter to specify the
en-US culture.

PowerShell

Import-LocalizedData -FileName "Test.psd1" -UICulture "en-US"

Name Value

---- -----

Msg3 "Use $_ to represent the object that's being processed."

Msg2 "This command requires the credentials of a member of the


Administrators group on the...

Msg1 "The Name parameter is missing from the command."

Import-LocalizedData returns a hashtable that contains the localized data strings.

Example 3: Import UI culture strings


PowerShell
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 4: Import localized data into a script


This example shows how to use localized data in a simple script.

PowerShell

PS C:\> # 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's being processed."

'@

# In C:\Test\Test.ps1

Import-LocalizedData -BindingVariable "Messages"

Write-Host $Messages.Msg2

# In Windows PowerShell

PS C:\> .\Test.ps1

This command requires the credentials of a member of the Administrators


group on the computer.

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

hashtable. 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 5: Replace default text strings in a script


This example shows how to use Import-LocalizedData to replace default text strings
defined in the
DATA section of a script.

PowerShell

PS C:\> # 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...

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 hashtable and
stores in the value of the
$UserMessages variable.

The script also includes an Import-LocalizedData command, which imports a hashtable


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 hashtable 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 6: Suppress error messages if the UI culture isn't
found
This example shows how to suppress the error messages that appear when Import-
LocalizedData can't
find the directories that match the user's UI culture or can't find a

.psd1 file for the script in


those directories.

PowerShell

PS C:\> # In Day1.ps1

Import-LocalizedData -BindingVariable "Day"

# In Day2.ps1

Import-LocalizedData -BindingVariable "Day" -ErrorAction:SilentlyContinue

PS C:\> .\Day1.ps1

Import-LocalizedData : Can't 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

PS C:\> .\Day2.ps1

Today is Tuesday

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.

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

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-BindingVariable

Specifies the variable into which the text strings are imported. Enter a variable name
without a
dollar sign ( $ ).

In Windows PowerShell 2.0, this parameter is required. In Windows PowerShell 3.0,


this parameter is
optional. If you omit this parameter, Import-LocalizedData returns
a hashtable of the text
strings. The hashtable is passed down the pipeline or
displayed at the command line.

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


aren't specifying default text
strings, you can select any variable name.

Type: String

Aliases: Variable

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-FileName
Specifies the name of the data file ( .psd1) to be imported. Enter a filename. You can
specify a
filename that doesn't include its .psd1 filename extension, or you can
specify the filename
including the .psd1 filename extension. Data files should be
saved as Unicode or UTF-8.

The FileName parameter is required when Import-LocalizedData isn't used in a


script.
Otherwise, the parameter is optional and the default value is the base name of
the script. You can
use this parameter to direct Import-LocalizedData to search for a
different .psd1 file.

For example, if the FileName is omitted and the script name is FindFiles.ps1 ,
Import-LocalizedData searches for the FindFiles.psd1 data file.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SupportedCommand

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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-UICulture

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 can't find the
directory, or the directory doesn't 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 can't find the subdirectory
or .psd1 file, the command fails and the data is
displayed in the default language specified in
the script.

Type: String

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
Hashtable

This cmdlet saves the hashtable in the variable 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 hashtable of key-value pairs, and save
the hashtable in a file with the
same name as the script and a .psd1 filename
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 hashtable. Save
the hashtable in a <ScriptName>.psd1 file. Then create a de-DE
subdirectory under the script
directory, and save the German <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 can't find a subdirectory with the name of the UI culture,


or the
subdirectory doesn't 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 can't 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
hashtable of
user messages into the value of the BindingVariable parameter in the
command. Then, when you
display a message from the hashtable in the variable,
the localized message is displayed.

For more information, see


about_Script_Internationalization.

Related Links
Write-Host
Import-PowerShellDataFile
about_Data_Files
Import-PowerShellDataFile
Reference
Module: Microsoft.PowerShell.Utility

Imports values from a .PSD1 file without invoking its contents.

Syntax
PowerShell

Import-PowerShellDataFile

[[-Path] <string[]>]

[<CommonParameters>]

PowerShell

Import-PowerShellDataFile

[-LiteralPath <string[]>]

[<CommonParameters>]

Description
The Import-PowerShellDataFile cmdlet safely imports key-value pairs from hashtables
defined in a
.PSD1 file. The values could be imported using Invoke-Expression on the
contents of the file.
However, Invoke-Expression runs any code contained in the file.
This could produce unwanted
results or execute unsafe code. Import-
PowerShellDataFile imports the data without invoking the
code.

7 Note

You can only import the first 500 key-value pairs.

Examples

Example 1: Retrieve values from PSD1


This example retrieves the key-value pairs stored in the hashtable kept inside the
Configuration.psd1 file. Get-Content is used to show the contents of the
Configuration.psd1
file.

PowerShell

Get-Content .\Configuration.psd1

$config = Import-PowerShellDataFile .\Configuration.psd1

$config.AllNodes

@{

AllNodes = @(

@{

NodeName = 'DSC-01'

@{

NodeName = 'DSC-02'

Name Value

---- -----

NodeName DSC-01

NodeName DSC-02

Parameters
-LiteralPath

The path to the file being imported. All characters in the path are treated as literal
values.

Type: String[]

Aliases: PSPath, LP

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Path
The path to the file being imported. Wildcards are allowed but only the first
matching file is
imported.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

Outputs
Hashtable

This cmdlet returns the data from the file as a hash table.

Related Links
Invoke-Expression
Import-LocalizedData
about_Data_Files
Import-PSSession
Reference
Module: Microsoft.PowerShell.Utility

Imports commands from another session into the current session.

Syntax
PowerShell

Import-PSSession

[-Prefix <String>]

[-DisableNameChecking]

[[-CommandName] <String[]>]
[-AllowClobber]

[-ArgumentList <Object[]>]

[-CommandType <CommandTypes>]

[-Module <String[]>]

[-FullyQualifiedModule <ModuleSpecification[]>]

[[-FormatTypeName] <String[]>]

[-Certificate <X509Certificate2>]

[-Session] <PSSession>

[<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
the Get-Command cmdlet 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.

Beginning in Windows PowerShell 3.0, you can use the Import-Module cmdlet to import
modules from a
remote session into the current session. This feature uses implicit
remoting. It is equivalent to
using Import-PSSession to import selected modules from a
remote session into the current session.

Examples

Example 1: Import all commands from a PSSession


PowerShell

$S = New-PSSession -ComputerName Server01

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: Import commands that end with a specific
string
PowerShell

$S = New-PSSession https://ps.testlabs.com/powershell

Import-PSSession -Session $S -CommandName *-test -FormatTypeName *

New-Test -Name Test1

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: Import cmdlets from a PSSession


PowerShell

$S1 = New-PSSession -ComputerName s1

$S2 = New-PSSession -ComputerName s2

Import-PSSession -Session s1 -Type cmdlet -Name New-Test, Get-Test -


FormatTypeName *

Import-PSSession -Session s2 -Type Cmdlet -Name Set-Test -FormatTypeName *

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: Run an imported command as a background


job
PowerShell

$S = New-PSSession -ComputerName Server01

Import-PSSession -Session $S -CommandName *-test* -FormatTypeName *

$batch = New-Test -Name Batch -AsJob

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: Import cmdlets and functions from a


Windows PowerShell module
PowerShell

$S = New-PSSession -ComputerName Server01

Invoke-Command -Session $S {Import-Module TestManagement}

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: Create a module in a temporary file


PowerShell

PS C:\> 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_tcw1

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

zunz.ttf

ModuleType : Script

PrivateData : {ImplicitRemoting}

AccessMode : ReadWrite

ExportedAliases : {}

ExportedCmdlets : {}

ExportedFunctions : {[Get-Date, Get-Date], [SearchHelp, SearchHelp]}

ExportedVariables : {}

NestedModules : {}

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: Run a command that is hidden by an


imported command
PowerShell

PS C:\> Import-PSSession $S -CommandName Get-Date -FormatTypeName * -


AllowClobber

PS C:\> Get-Command Get-Date -All

CommandType Name Definition

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

Function Get-Date ...

Cmdlet Get-Date Get-Date [[-Date] <DateTime>] [-Year <Int32>] [-


Month <Int32>]

PS C:\> Get-Date

09074

PS C:\> (Get-Command -Type Cmdlet -Name Get-Date).PSSnapin.Name

Microsoft.PowerShell.Utility

PS C:\> Microsoft.PowerShell.Utility\Get-Date

Sunday, March 15, 2009 2:08:26 PM

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 All parameter of the Get-Command cmdlet to get all 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: Import commands that have a specific string


in their names
PowerShell

PS C:\> 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: Use the Module parameter to discover which


commands were imported into the session
PowerShell

PS C:\> $M = Import-PSSession -Session $S -CommandName *bits* -


FormatTypeName *bits*

PS C:\> 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

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

Parameters
-AllowClobber

Indicates that this cmdlet 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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-ArgumentList

Specifies an array of commands that results from using the specified arguments
(parameter values).

For instance, 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: .

Type: Object[]

Aliases: Args

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Certificate

Specifies the client certificate that is used to sign the format files (*.Format.ps1xml)
or script
module files (.psm1) in the temporary module that Import-PSSession
creates.

Enter a variable that contains a certificate or a command or expression that gets the
certificate.

To find a certificate, use the Get-PfxCertificate cmdlet or use the Get-ChildItem


cmdlet in the
Certificate (Cert:) drive. If the certificate is not valid or does not have
sufficient authority,
the command fails.

Type: X509Certificate2

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-CommandName

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

Type: String[]

Aliases: Name

Position: 2

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-CommandType

Specifies the type of command objects. The default value is Cmdlet. Use
CommandType or its
alias, Type. The acceptable values for this parameter 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.
These values are defined as a flag-based enumeration. You can combine multiple
values together to
set multiple flags using this parameter. The values can be passed
to the CommandType parameter
as an array of values or as a comma-separated
string of those values. The cmdlet will combine the
values using a binary-OR
operation. Passing values as an array is the simplest option and also
allows you to
use tab-completion on the values.

Type: CommandTypes

Aliases: Type

Accepted values: Alias, Function, Filter, Cmdlet, ExternalScript, Application,


Script, Workflow, Configuration, All

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-DisableNameChecking

Indicates that this cmdlet suppresses the message that warns you when you import a
cmdlet or
function whose name includes an unapproved verb or a prohibited
character.

By default, when a module that you import exports cmdlets or functions that have
unapproved verbs in
their names, the Windows PowerShell displays the following
warning message:

"WARNING: Some imported command names include unapproved verbs which


might make them less
discoverable. Use the Verbose parameter for more detail or
type Get-Verb to see the list of
approved verbs."

This message is only a warning. The complete module is still imported, including the
non-conforming
commands. Although the message is displayed to module users,
the naming problem should be fixed by
the module author.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-FormatTypeName

Specifies 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


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

Type: String[]

Position: 3

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-FullyQualifiedModule

The value can be a module name, a full module specification, or a path to a module
file.

When the value is a path, the path can be fully qualified or relative. A relative path is
resolved
relative to the script that contains the using statement.

When the value is a name or module specification, PowerShell searches the


PSModulePath for the
specified module.

A module specification is a hashtable that has the following keys.

ModuleName - Required Specifies the module name.


GUID - Optional Specifies the GUID of the module.

It's also Required to specify at least one of the three below keys.
ModuleVersion - Specifies a minimum acceptable version of the module.

MaximumVersion - Specifies the maximum acceptable version of the module.


RequiredVersion - Specifies an exact, required version of the module. This

can't be used with


the other Version keys.

You can't specify the FullyQualifiedModule parameter in the same command as a


Module
parameter. The two parameters are mutually exclusive.

Type: ModuleSpecification[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Module

Specifies and array of commands in the Windows PowerShell snap-ins and modules.
Enter the snap-in
and module names. Wildcards are not permitted.

Import-PSSession cannot import providers from a snap-in.

For more information, see about_PSSnapins


and about_Modules.

Type: String[]

Aliases: PSSnapin

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Prefix

Specifies a 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 instance, 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.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Session

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.

Type: PSSession

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
PSModuleInfo

This cmdlet returns the same module object that New-Module and Get-Module cmdlets
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
Windows PowerShell includes the following aliases for Import-PSSession :

ipsn

Import-PSSession relies on the 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.

Import-PSSession does not import variables or 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. To
prevent name conflicts, use the Prefix parameter. 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 these cmdlets 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 temporary 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.

In Windows PowerShell 2.0, help topics for commands that are imported from
another session do not
include the prefix that you assign by using the Prefix
parameter. To get help for an imported
command in Windows PowerShell 2.0, use
the original (non-prefixed) command name.

Related Links
Export-PSSession
Invoke-Expression
Reference
Module: Microsoft.PowerShell.Utility

Runs commands or expressions on the local computer.

Syntax
PowerShell

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 is returned (echoed) unchanged.

Expressions are evaluated and run in the current scope. For more information, see
about_Scopes.

U Caution

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.

Examples

Example 1: Evaluate an expression


PowerShell

$Command = "Get-Process"

$Command

Get-Process

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

...

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. PowerShell
echoes the string.

The third command uses Invoke-Expression to evaluate the string.

Example 2: Run a script on the local computer


PowerShell

Invoke-Expression -Command "C:\ps-test\testscript.ps1"

"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: Run a command in a variable


PowerShell

$Command = 'Get-Process | where {$_.cpu -gt 1000}'

Invoke-Expression $Command

This example runs a command string that is saved in the $Command 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 variable.

Example 4: Get and run a cmdlet Help example


PowerShell

$Cmdlet_name = "Get-ComputerInfo"

$Example_number = 1

$Example_code = (Get-Help $Cmdlet_name).examples.example[($Example_number-


1)].code

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 fails if the example number is not valid.

7 Note

If the example code from the help file has output in the example, PowerShell
attempts to run the
output along with the code and an error will be thrown.

Parameters
-Command

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.

Type: String

Position: 0

Default value: None

Accept pipeline input: True


Accept wildcard characters: False

Inputs
String

You can pipe a string representing the expression to invoke to this cmdlet. Use the
$Input
automatic variable to represent the input objects in the command.

PSObject

You can pipe an object representing the expression to invoke to this cmdlet. Use the
$Input
automatic variable to represent the input objects in the command.

Outputs
None

This cmdlet returns no output of its own, but the invoked command may return output.

Notes
Windows PowerShell includes the following aliases for Invoke-Expression :

iex

In most cases, you invoke expressions using PowerShell's call operator and achieve the
same results.
The call operator is a safer method. For more information, see
about_Operators.

Related Links
Invoke-Command
about_Scopes
Invoke-RestMethod
Reference
Module: Microsoft.PowerShell.Utility

Sends an HTTP or HTTPS request to a RESTful web service.

Syntax
PowerShell

Invoke-RestMethod

[-Method <WebRequestMethod>]

[-UseBasicParsing]

[-Uri] <Uri>

[-WebSession <WebRequestSession>]

[-SessionVariable <String>]
[-Credential <PSCredential>]

[-UseDefaultCredentials]

[-CertificateThumbprint <String>]

[-Certificate <X509Certificate>]

[-UserAgent <String>]

[-DisableKeepAlive]

[-TimeoutSec <Int32>]

[-Headers <IDictionary>]

[-MaximumRedirection <Int32>]

[-Proxy <Uri>]

[-ProxyCredential <PSCredential>]

[-ProxyUseDefaultCredentials]

[-Body <Object>]

[-ContentType <String>]

[-TransferEncoding <String>]

[-InFile <String>]

[-OutFile <String>]

[-PassThru]

[<CommonParameters>]

Description
The Invoke-RestMethod cmdlet sends HTTP and HTTPS requests to Representational
State Transfer
(REST) web services that return richly structured data.

PowerShell formats the response based to the data type. For an RSS or ATOM feed,
PowerShell returns
the Item or Entry XML nodes. For JavaScript Object Notation (JSON)
or XML, PowerShell converts, or
deserializes, the content into [PSCustomObject] objects.
7 Note

When the REST endpoint returns multiple objects, the objects are received as an
array. If you pipe
the output from Invoke-RestMethod to another command, it is
sent as a single [Object[]]
object. The contents of that array are not enumerated
for the next command on the pipeline.

This cmdlet is introduced in Windows PowerShell 3.0.

7 Note

By default, script code in the web page may be run when the page is being parsed
to populate the
ParsedHtml property. Use the UseBasicParsing switch to suppress
this.

Examples

Example 1: Get the PowerShell RSS feed


PowerShell

Invoke-RestMethod -Uri https://devblogs.microsoft.com/powershell/feed/ |

Format-Table -Property Title, pubDate

Title pubDate

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

Join the PowerShell 10th Anniversary Celebration! Tue, 08


Nov 2016 23:00:04 +0000

DSC Resource Kit November 2016 Release Thu, 03


Nov 2016 00:19:07 +0000

PSScriptAnalyzer Community Call - Oct 18, 2016 Thu, 13


Oct 2016 17:52:35 +0000

New Home for In-Box DSC Resources Sat, 08


Oct 2016 07:13:10 +0000

New Social Features on Gallery Fri, 30


Sep 2016 23:04:34 +0000

PowerShellGet and PackageManagement in PowerShell Gallery and GitHub Thu, 29


Sep 2016 22:21:42 +0000

PowerShell Security at DerbyCon Wed, 28


Sep 2016 01:13:19 +0000

DSC Resource Kit September Release Thu, 22


Sep 2016 00:25:37 +0000

PowerShell DSC and implicit remoting broken in KB3176934 Tue, 23


Aug 2016 15:07:50 +0000

PowerShell on Linux and Open Source! Thu, 18


Aug 2016 15:32:02 +0000

This command uses the Invoke-RestMethod cmdlet to get information from the
PowerShell Blog RSS
feed. The command uses the Format-Table cmdlet to display the
values of the Title and
pubDate properties of each blog in a table.

Example 2
In the following example, a user runs Invoke-RestMethod to perform a POST request on
an intranet
website in the user's organization.

PowerShell

$Cred = Get-Credential

# Next, allow the use of self-signed SSL certificates.

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {
$True }

# Create variables to store the values consumed by the Invoke-RestMethod


command.

# The search variable contents are later embedded in the body variable.

$Server = 'server.contoso.com'

$Url = "https://${server}:8089/services/search/jobs/export"

$Search = "search index=_internal | reverse | table


index,host,source,sourcetype,_raw"

# The cmdlet handles URL encoding. The body variable describes the search
criteria, specifies CSV as

# the output mode, and specifies a time period for returned data that starts
two days ago and ends

# one day ago. The body variable specifies values for parameters that apply
to the particular REST

# API with which Invoke-RestMethod is communicating.

$Body = @{

search = $Search

output_mode = "csv"

earliest_time = "-2d@d"

latest_time = "-1d@d"

# Now, run the Invoke-RestMethod command with all variables in place,


specifying a path and file

# name for the resulting CSV output file.

Invoke-RestMethod -Method Post -Uri $url -Credential $Cred -Body $body -


OutFile output.csv

{"preview":true,"offset":0,"result":
{"sourcetype":"contoso1","count":"9624"}}

{"preview":true,"offset":1,"result":{"sourcetype":"contoso2","count":"152"}}

{"preview":true,"offset":2,"result":
{"sourcetype":"contoso3","count":"88494"}}

{"preview":true,"offset":3,"result":
{"sourcetype":"contoso4","count":"15277"}}

Example 3: Pass multiple headers


This example demonstrates, how to pass multiple headers in from a hash-table to a
REST API.

PowerShell

$headers = @{

'userId' = 'UserIDValue'

'token' = 'TokenValue'

Invoke-RestMethod -Uri $uri -Method Post -Headers $headers -Body $body

APIs often require passed headers for authentication, validation etc.

Example 3: Submitting form data


When the body is a form, or it is the output of another Invoke-WebRequest call,
PowerShell sets
the request content to the form fields.

For example:

PowerShell

$R = Invoke-WebRequest https://website.com/login.aspx

$R.Forms[0].Name = "MyName"

$R.Forms[0].Password = "MyPassword"

Invoke-RestMethod https://website.com/service.aspx -Body $R.Forms[0]

Example 4: Enumerate returned items on the pipeline


GitHub returns multiple objects an array. If you pipe the output to another command, it
is sent as a
single [Object[]] object.

To enumerate the objects into the pipeline, pipe the results to Write-Output or wrap the
cmdlet in
parentheses. The following example counts the number of objects returned by
GitHub. Then counts the
number of objects enumerated to the pipeline.

PowerShell

$uri = 'https://api.github.com/repos/microsoftdocs/powershell-docs/issues'

$x = 0

Invoke-RestMethod -Uri $uri | ForEach-Object { $x++ }

$x

$x = 0

(Invoke-RestMethod -Uri $uri) | ForEach-Object { $x++ }

$x

30

$x = 0

Invoke-RestMethod -Uri $uri | Write-Output | ForEach-Object { $x++ }

$x

30

Parameters
-Body

Specifies the body of the request. The body is the content of the request that follows
the headers.
You can also pipe a body value to Invoke-RestMethod .

The Body parameter can be used to specify a list of query parameters or specify the
content of
the response.

When the input is a GET request, and the body is an IDictionary (typically, a hash
table), the body
is added to the URI as query parameters. For other request types
(such as POST), the body is set as
the value of the request body in the standard
name=value format.

2 Warning

The verbose output of a POST body will end with with -1-byte payload , even
though
the size of the body is both known and sent in the Content-Length HTTP
header.
Type: Object

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Certificate

Specifies the client certificate that is used for a secure web request. Enter a variable
that
contains a certificate or a command or 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 sufficient
authority, the command
fails.

Type: X509Certificate

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-CertificateThumbprint

Specifies the digital public key certificate (X509) of a user account that has
permission to send
the request. 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.

Type: String

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-ContentType

Specifies the content type of the web request.

If this parameter is omitted and the request method is POST, Invoke-RestMethod sets
the content
type to "application/x-www-form-urlencoded". Otherwise, the content
type is not specified in the
call.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Credential

Specifies a user account that has permission to send the request. The default is the
current user.

Type a user name, such as User01 or Domain01\User01, or enter a PSCredential


object
generated by the Get-Credential cmdlet.

Credentials are stored in a PSCredential


object and the password is stored as a
SecureString.

7 Note

For more information about SecureString data protection, see


How secure is
SecureString?.

Type: PSCredential

Position: Named

Default value: Current user

Accept pipeline input: False


Accept wildcard characters: False

-DisableKeepAlive

Sets the KeepAlive value in the HTTP header to False. By default, KeepAlive is True.
KeepAlive establishes a persistent connection to the server to facilitate subsequent
requests.

Type: SwitchParameter

Position: Named

Default value: KeepAlive

Accept pipeline input: False

Accept wildcard characters: False

-Headers

Specifies the headers of the web request. Enter a hash table or dictionary.

To set UserAgent headers, use the UserAgent parameter. You cannot use this
parameter to specify
UserAgent or cookie headers.

Type: IDictionary

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InFile

Gets the content of the web request from a file.

Enter a path and file name. If you omit the path, the default is the current location.

Type: String

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-MaximumRedirection

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.

Type: Int32

Position: Named

Default value: 5

Accept pipeline input: False

Accept wildcard characters: False

-Method

Specifies the method used for the web request. The acceptable values for this
parameter are:

Default

Delete
Get

Head

Merge
Options

Patch
Post

Put

Trace

Type: WebRequestMethod

Accepted values: Default, Get, Head, Post, Put, Delete, Trace, Options, Merge,
Patch

Position: Named

Default value: Default

Accept pipeline input: False


Accept wildcard characters: False

-OutFile

Saves the response body in the specified output file. Enter a path and file name. If
you omit the
path, the default is the current location.

By default, Invoke-RestMethod returns the results to the pipeline.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-PassThru

This parameter is valid only when the OutFile parameter is also used in the
command. The intent
is to have the results written to the file and to the pipeline.

7 Note

When you use the PassThru parameter, the output is written to the pipeline but
the file is
empty. For more information, see
PowerShell Issue #15409 .

Type: SwitchParameter

Position: Named

Default value: No output

Accept pipeline input: False

Accept wildcard characters: False

-Proxy

Uses a proxy server for the request, rather than connecting directly to the Internet
resource. Enter
the URI of a network proxy server.

Type: Uri
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ProxyCredential

Specifies a user account that has permission to use the proxy server that is specified
by the
Proxy parameter. 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.

This parameter is valid only when the Proxy parameter is also used in the command.
You cannot
use the ProxyCredential and ProxyUseDefaultCredentials parameters in
the same command.

Type: PSCredential

Position: Named

Default value: Current user

Accept pipeline input: False

Accept wildcard characters: False

-ProxyUseDefaultCredentials

Uses the credentials of the current user to access the proxy server that is specified by
the
Proxy parameter.

This parameter is valid only when the Proxy parameter is also used in the command.
You cannot
use the ProxyCredential and ProxyUseDefaultCredentials parameters in
the same command.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-SessionVariable

Creates a variable containing the web request session. Enter a variable name without
the dollar sign
( $ ) symbol.

When you specify a session variable, Invoke-RestMethod creates a web request


session object and
assigns it to a variable with the specified name in your PowerShell
session. You can use the
variable in your session as soon as the command completes.

Unlike a remote session, the web request session isn't a persistent connection. It's an
object that
contains information about the connection and the request, including
cookies, credentials, the
maximum redirection value, and the user agent string. You
can use it to share state and data among
web requests.

To use the web request session in subsequent web requests, specify the session
variable in the value
of the WebSession parameter. PowerShell uses the data in the
web request session object when
establishing the new connection. To override a
value in the web request session, use a cmdlet
parameter, such as UserAgent or
Credential. Parameter values take precedence over values in
the web request
session.

You can't use the SessionVariable and WebSession parameters in the same
command.

Type: String

Aliases: SV

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-TimeoutSec

Specifies how long the request can be pending before it times out. Enter a value in
seconds. The
default value, 0, specifies an indefinite time-out.

A Domain Name System (DNS) query can take up to 15 seconds to return or time
out. If your request
contains a host name that requires resolution, and you set
TimeoutSec to a value greater than zero,
but less than 15 seconds, it can take 15
seconds or more before a WebException is thrown, and your
request times out.
Type: Int32

Position: Named

Default value: 0

Accept pipeline input: False

Accept wildcard characters: False

-TransferEncoding

Specifies a value for the transfer-encoding HTTP response header. The acceptable
values for this
parameter are:

Chunked

Compress
Deflate

GZip

Identity

Type: String

Accepted values: chunked, compress, deflate, gzip, identity

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Uri

Specifies the Uniform Resource Identifier (URI) of the Internet resource to which the
web request is
sent. This parameter supports HTTP, HTTPS, FTP, and FILE values.

This parameter is required. The parameter name (Uri) is optional.

Type: Uri

Position: 0

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-UseBasicParsing

Indicates that the cmdlet uses basic parsing. The cmdlet returns the raw HTML in a
String
object.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-UseDefaultCredentials

Uses the credentials of the current user to send the web request.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-UserAgent

Specifies a user agent string for the web request.

The default user agent is similar to "Mozilla/5.0 (Windows NT; Windows NT 6.1; en-
US)
WindowsPowerShell/3.0" with slight variations for each operating system and
platform.

To test a website with the standard user agent string that is used by most Internet
browsers, use
the properties of the PSUserAgent class, such as
Chrome, FireFox,
Internet Explorer, Opera, and Safari.

Type: String

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-WebSession

Specifies a web request session. Enter the variable name, including the dollar sign
( $ ).

To override a value in the web request session, use a cmdlet parameter, such as
UserAgent or
Credential. Parameter values take precedence over values in the web
request session.

Unlike a remote session, the web request session is not a persistent connection. It is
an object
that contains information about the connection and the request, including
cookies, credentials, the
maximum redirection value, and the user agent string. You
can use it to share state and data among
web requests.

To create a web request session, enter a variable name (without a dollar sign) in the
value of the
SessionVariable parameter of an Invoke-RestMethod command. Invoke-
RestMethod creates the
session and saves it in the variable. In subsequent commands,

use the variable as the value of the


WebSession parameter.

You cannot use the SessionVariable and WebSession parameters in the same
command.

Type: WebRequestSession

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
Object

You can pipe the body of a web request to this cmdlet.

Outputs
Int64

When the request returns an integer, this cmdlet returns that integer.

String

When the request returns a string, this cmdlet returns that string.

XmlDocument

When the request returns valid XML, this cmdlet returns it as an XmlDocument.

PSObject

When the request returns JSON strings, this cmdlet returns a PSObject representing the
data.

Notes
Windows PowerShell includes the following aliases for Invoke-RestMethod :

irm

Related Links
ConvertTo-Json
ConvertFrom-Json
Invoke-WebRequest
Invoke-WebRequest
Reference
Module: Microsoft.PowerShell.Utility

Gets content from a web page on the internet.

Syntax
PowerShell

Invoke-WebRequest

[-UseBasicParsing]

[-Uri] <Uri>

[-WebSession <WebRequestSession>]

[-SessionVariable <String>]
[-Credential <PSCredential>]

[-UseDefaultCredentials]

[-CertificateThumbprint <String>]

[-Certificate <X509Certificate>]

[-UserAgent <String>]

[-DisableKeepAlive]

[-TimeoutSec <Int32>]

[-Headers <IDictionary>]

[-MaximumRedirection <Int32>]

[-Method <WebRequestMethod>]

[-Proxy <Uri>]

[-ProxyCredential <PSCredential>]

[-ProxyUseDefaultCredentials]

[-Body <Object>]

[-ContentType <String>]

[-TransferEncoding <String>]

[-InFile <String>]

[-OutFile <String>]

[-PassThru]

[<CommonParameters>]

Description
The Invoke-WebRequest cmdlet sends HTTP, HTTPS, FTP, and FILE requests to a web
page or web
service. It parses the response and returns collections of forms, links,
images, and other
significant HTML elements.

This cmdlet was introduced in Windows PowerShell 3.0.


7 Note

By default, script code in the web page may be run when the page is being parsed
to populate the
ParsedHtml property. Use the -UseBasicParsing switch to suppress
this.

) Important

The examples in this article reference hosts in the contoso.com domain. This is a
fictitious
domain used by Microsoft for examples. The examples are designed to
show how to use the cmdlets.
However, since the contoso.com sites don't exist, the
examples don't work. Adapt the examples
to hosts in your environment.

Examples

Example 1: Send a web request


This example uses the Invoke-WebRequest cmdlet to send a web request to the Bing.com
site.

PowerShell

$Response = Invoke-WebRequest -URI https://www.bing.com?


q=how+many+feet+in+a+mile

$Response.AllElements | Where-Object {

$_.name -like "* Value" -and $_.tagName -eq "INPUT"

} | Select-Object Name, Value

name value

---- -----

From Value 1

To Value 5280

The first command issues the request and saves the response in the $Response variable.

The second command filters the objects in the AllElements property where the name
property
is like "* Value" and the tagName is "INPUT". The filtered results are piped to
Select-Object
to select the name and value properties.

Example 2: Use a stateful web service


This example shows how to use the Invoke-WebRequest cmdlet with a stateful web
service, such as
Facebook.

PowerShell

$R = Invoke-WebRequest https://www.facebook.com/login.php -SessionVariable


fb

# This command stores the first form in the Forms property of the $R
variable in the $Form variable.

$Form = $R.Forms[0]

# This command shows the fields available in the Form.

$Form.fields

Key Value

--- -----

...

email

pass

...

# These commands populate the username and password of the respective Form
fields.

$Form.Fields["email"]="User01@Fabrikam.com"

$Form.Fields["pass"]="P@ssw0rd"

# This command creates the Uri that will be used to log in to facebook.

# The value of the Uri parameter is the value of the Action property of the
form.

$Uri = "https://www.facebook.com" + $Form.Action

# Now the Invoke-WebRequest cmdlet is used to sign into the Facebook web
service.

# The WebRequestSession object in the $FB variable is passed as the value of


the WebSession parameter.

# The value of the Body parameter is the hash table in the Fields property
of the form.

# The value of the *Method* parameter is POST. The command saves the output
in the $R variable.

$R = Invoke-WebRequest -Uri $Uri -WebSession $FB -Method POST -Body


$Form.Fields

$R.StatusDescription

The first command uses the Invoke-WebRequest cmdlet to send a sign-in request. The
command
specifies a value of "FB" for the value of the SessionVariable parameter, and
saves the result
in the $R variable. When the command completes, the $R variable
contains an
HtmlWebResponseObject and the $FB variable contains a
WebRequestSession object.

After the Invoke-WebRequest cmdlet signs in to facebook, the StatusDescription


property of the
web response object in the $R variable indicates that the user is signed
in successfully.
Example 3: Get links from a web page
This command gets the links in a web page.

PowerShell

(Invoke-WebRequest -Uri
"https://devblogs.microsoft.com/powershell/").Links.Href

The Invoke-WebRequest cmdlet gets the web page content. Then the Links property of
the
returned HtmlWebResponseObject is used to display the Href property of each link.

Example 4: Catch non success messages from Invoke-


WebRequest
When Invoke-WebRequest encounters a non-success HTTP message (404, 500, etc.), it
returns no
output and throws a terminating error. To catch the error and view the
StatusCode you can
enclose execution in a try/catch block.

PowerShell

try

$Response = Invoke-WebRequest -Uri "www.microsoft.com/unkownhost"

# This will only execute if the Invoke-WebRequest is successful.

$StatusCode = $Response.StatusCode

catch

$StatusCode = $_.Exception.Response.StatusCode.value__

$StatusCode

404

The terminating error is caught by the catch block, which retrieves the StatusCode from
the
Exception object.

Example 8: Download multiple files at the same time


The Invoke-WebRequest cmdlet can only download one file at a time. The following
example uses
Start-ThreadJob to create multiple thread jobs to download multiple files
at the same time.
PowerShell

$baseUri = 'https://github.com/PowerShell/PowerShell/releases/download'

$files = @(

@{

Uri = "$baseUri/v7.3.0-preview.5/PowerShell-7.3.0-preview.5-win-
x64.msi"

OutFile = 'PowerShell-7.3.0-preview.5-win-x64.msi'

},

@{

Uri = "$baseUri/v7.3.0-preview.5/PowerShell-7.3.0-preview.5-win-
x64.zip"

OutFile = 'PowerShell-7.3.0-preview.5-win-x64.zip'

},

@{

Uri = "$baseUri/v7.2.5/PowerShell-7.2.5-win-x64.msi"

OutFile = 'PowerShell-7.2.5-win-x64.msi'

},

@{

Uri = "$baseUri/v7.2.5/PowerShell-7.2.5-win-x64.zip"

OutFile = 'PowerShell-7.2.5-win-x64.zip'

$jobs = @()

foreach ($file in $files) {

$jobs += Start-ThreadJob -Name $file.OutFile -ScriptBlock {

$params = $using:file

Invoke-WebRequest @params
}

Write-Host "Downloads started..."

Wait-Job -Job $jobs

foreach ($job in $jobs) {

Receive-Job -Job $job

7 Note

To use the Start-ThreadJob cmdlet you must install the ThreadJob module from
the PowerShell
Gallery.

Parameters
-Body
Specifies the body of the request. The body is the content of the request that follows
the headers.
You can also pipe a body value to Invoke-WebRequest .

The Body parameter can be used to specify a list of query parameters or specify the
content of
the response.

When the input is a GET request and the body is an IDictionary (typically, a hash
table), the
body is added to the URI as query parameters. For other request types
(such as POST), the body is
set as the value of the request body in the standard
name=value format.

When the body is a form, or it is the output of an Invoke-WebRequest call, PowerShell


sets the
request content to the form fields.
For example:

$r = Invoke-WebRequest https://website.com/login.aspx
$r.Forms\[0\].Name =

"MyName"
$r.Forms\[0\].Password = "MyPassword"
Invoke-RestMethod
https://website.com/service.aspx -Body $r

or -

Invoke-RestMethod https://website.com/service.aspx -Body $r.Forms\[0\]

Type: Object

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Certificate

Specifies the client certificate that's used for a secure web request. Enter a variable
that
contains a certificate or a command or 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 isn't valid or doesn't have sufficient
authority, the command
fails.

Type: X509Certificate

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-CertificateThumbprint

Specifies the digital public key certificate (X509) of a user account that has
permission to send
the request. 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 don't work with domain accounts.

To get a certificate thumbprint, use the Get-Item or Get-ChildItem command in the


PowerShell
Cert: drive.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ContentType

Specifies the content type of the web request.

If this parameter is omitted and the request method is POST, Invoke-WebRequest sets
the content
type to application/x-www-form-urlencoded . Otherwise, the content type
isn't specified in the
call.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Credential

Specifies a user account that has permission to send the request. The default is the
current user.
Type a user name, such as User01 or Domain01\User01, or enter a PSCredential
object
generated by the Get-Credential cmdlet.

Credentials are stored in a PSCredential


object and the password is stored as a
SecureString.

7 Note

For more information about SecureString data protection, see


How secure is
SecureString?.

Type: PSCredential

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-DisableKeepAlive

Indicates that the cmdlet sets the KeepAlive value in the HTTP header to False. By
default,
KeepAlive is True. KeepAlive establishes a persistent connection to the
server to
facilitate subsequent requests.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Headers

Specifies the headers of the web request. Enter a hash table or dictionary.

To set UserAgent headers, use the UserAgent parameter. You cannot use this
parameter to
specify UserAgent or cookie headers.

Type: IDictionary
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InFile

Gets the content of the web request from a file.

Enter a path and file name. If you omit the path, the default is the current location.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-MaximumRedirection

Specifies how many times 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.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Method

Specifies the method used for the web request. The acceptable values for this
parameter are:

Default
Delete
Get

Head
Merge

Options
Patch

Post

Put
Trace

Type: WebRequestMethod

Accepted values: Default, Get, Head, Post, Put, Delete, Trace, Options, Merge,
Patch

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-OutFile

Specifies the output file for which this cmdlet saves the response body. Enter a path
and file name.
If you omit the path, the default is the current location.

By default, Invoke-WebRequest returns the results to the pipeline. To send the results
to a file
and to the pipeline, use the Passthru parameter.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-PassThru

Indicates that the cmdlet returns the results, in addition to writing them to a file. This
parameter
is valid only when the OutFile parameter is also used in the command.

Type: SwitchParameter
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Proxy

Specifies a proxy server for the request, rather than connecting directly to the
Internet resource.
Enter the URI of a network proxy server.

Type: Uri

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ProxyCredential

Specifies a user account that has permission to use the proxy server specified by the
Proxy
parameter. 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.

This parameter is valid only when the Proxy parameter is also used in the command.
You can't use
the ProxyCredential and ProxyUseDefaultCredentials parameters in
the same command.

Type: PSCredential

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ProxyUseDefaultCredentials
Indicates that the cmdlet uses the credentials of the current user to access the proxy
server that
is specified by the Proxy parameter.

This parameter is valid only when the Proxy parameter is also used in the command.
You can't use
the ProxyCredential and ProxyUseDefaultCredentials parameters in
the same command.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SessionVariable

Specifies a variable for which this cmdlet creates a web request session and saves it
in the value.
Enter a variable name without the dollar sign ( $ ) symbol.

When you specify a session variable, Invoke-WebRequest creates a web request


session object and
assigns it to a variable with the specified name in your PowerShell
session. You can use the
variable in your session as soon as the command completes.

Unlike a remote session, the web request session isn't a persistent connection. It's an
object that
contains information about the connection and the request, including
cookies, credentials, the
maximum redirection value, and the user agent string. You
can use it to share state and data among
web requests.

To use the web request session in subsequent web requests, specify the session
variable in the value
of the WebSession parameter. PowerShell uses the data in the
web request session object when
establishing the new connection. To override a
value in the web request session, use a cmdlet
parameter, such as UserAgent or
Credential. Parameter values take precedence over values in
the web request
session.

You can't use the SessionVariable and WebSession parameters in the same
command.

Type: String

Aliases: SV

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-TimeoutSec

Specifies how long the request can be pending before it times out. Enter a value in
seconds. The
default value, 0, specifies an indefinite time-out.

A Domain Name System (DNS) query can take up to 15 seconds to return or time
out. If your request
contains a host name that requires resolution, and you set
TimeoutSec to a value greater than
zero, but less than 15 seconds, it can take 15
seconds or more before a WebException is thrown,
and your request times out.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-TransferEncoding

Specifies a value for the transfer-encoding HTTP response header. The acceptable
values for this
parameter are:

Chunked

Compress
Deflate

GZip

Identity

Type: String

Accepted values: chunked, compress, deflate, gzip, identity

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-Uri

Specifies the Uniform Resource Identifier (URI) of the Internet resource to which the
web request is
sent. Enter a URI. This parameter supports HTTP, HTTPS, FTP, and FILE
values.

This parameter is required. The parameter name Uri is optional.

Type: Uri

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-UseBasicParsing

Indicates that the cmdlet uses the response object for HTML content without
Document Object Model
(DOM) parsing. This parameter is required when Internet
Explorer is not installed on the computers,
such as on a Server Core installation of a
Windows Server operating system.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-UseDefaultCredentials

Indicates that the cmdlet uses the credentials of the current user to send the web
request.

Type: SwitchParameter

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-UserAgent

Specifies a user agent string for the web request. The default user agent is similar to
Mozilla/5.0 (Windows NT; Windows NT 6.1; en-US) WindowsPowerShell/3.0 with slight
variations for
each operating system and platform.

To test a website with the standard user agent string that is used by most Internet
browsers, use
the properties of the PSUserAgent class,
such as Chrome, FireFox,
InternetExplorer, Opera, and Safari. For example, the following command
uses the
user agent string for Internet Explorer:
Invoke-WebRequest -Uri https://website.com/
-UserAgent ([Microsoft.PowerShell.Commands.PSUserAgent]::InternetExplorer)

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WebSession

Specifies a web request session. Enter the variable name, including the dollar sign
( $ ).

To override a value in the web request session, use a cmdlet parameter, such as
UserAgent or
Credential. Parameter values take precedence over values in the web
request session.

Unlike a remote session, the web request session is not a persistent connection. It is
an object
that contains information about the connection and the request, including
cookies, credentials, the
maximum redirection value, and the user agent string. You
can use it to share state and data among
web requests.

To create a web request session, enter a variable name, without a dollar sign, in the
value of the
SessionVariable parameter of an Invoke-WebRequest command. Invoke-
WebRequest creates the
session and saves it in the variable. In subsequent commands,

use the variable as the value of the


WebSession parameter.
You can't use the SessionVariable and WebSession parameters in the same
command.

Type: WebRequestSession

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
Object

You can pipe the body of a web request to this cmdlet.

Outputs
HtmlWebResponseObject

This cmdlet returns the response object representing the result of the web request.

Notes
Windows PowerShell includes the following aliases for Invoke-WebRequest :

iwr

Related Links
Invoke-RestMethod
ConvertFrom-Json
ConvertTo-Json
Measure-Command
Reference
Module: Microsoft.PowerShell.Utility

Measures the time it takes to run script blocks and cmdlets.

Syntax
PowerShell

Measure-Command

[-InputObject <PSObject>]

[-Expression] <ScriptBlock>

[<CommonParameters>]

Description
The Measure-Command cmdlet runs a script block or cmdlet internally, times the execution
of the
operation, and returns the execution time.

7 Note

Script blocks run by Measure-Command run in the current scope, not a child scope.

Examples

Example 1: Measure a command


This example measures the time it takes to run a Get-EventLog command that gets the
events in the
Windows PowerShell event log.

PowerShell

Measure-Command { Get-EventLog "windows powershell" }

Example 2: Compare two outputs from Measure-


Command
The first command measures the time it takes to process a recursive Get-ChildItem
command that
uses the Path parameter to get only .txt files in the C:\Windows
directory and its
subdirectories.

The second command measures the time it takes to process a recursive Get-ChildItem
command that
uses the provider-specific Filter parameter.

These commands show the value of using a provider-specific filter in PowerShell


commands.

PowerShell

Measure-Command { Get-ChildItem -Path C:\Windows\*.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

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

Example 3: Piping input to Measure-Command


Objects that are piped to Measure-Command are available to the script block that is passed
to the
Expression parameter. The script block is executed once for each object on the
pipeline.

PowerShell
# Perform a simple operation to demonstrate the InputObject parameter

# Note that no output is displayed.

10, 20, 50 | Measure-Command -Expression { for ($i=0; $i -lt $_; $i++) {$i}
}

Days : 0

Hours : 0

Minutes : 0

Seconds : 0

Milliseconds : 12

Ticks : 122672

TotalDays : 1.41981481481481E-07

TotalHours : 3.40755555555556E-06

TotalMinutes : 0.000204453333333333

TotalSeconds : 0.0122672

TotalMilliseconds : 12.2672

Example 4: Displaying output of measured command


To display output of expression in Measure-Command you can use a pipe to Out-Default .

PowerShell

# Perform the same operation as above adding Out-Default to every execution.

# This will show that the ScriptBlock is in fact executing for every item.

10, 20, 50 | Measure-Command -Expression {for ($i=0; $i -lt $_; $i++) {$i};
"$($_)" | Out-Default }

10

20

50

Days : 0

Hours : 0

Minutes : 0

Seconds : 0

Milliseconds : 11

Ticks : 113745

TotalDays : 1.31649305555556E-07

TotalHours : 3.15958333333333E-06

TotalMinutes : 0.000189575

TotalSeconds : 0.0113745

TotalMilliseconds : 11.3745

Example 5: Measuring execution in a child scope


Measure-Command runs the script block in the current scope, so the script block can

modify values
in the current scope. To avoid changes to the current scope, you must
wrap the script block in
braces ( {} ) and use the invocation operator ( & ) to execute the
block in a child scope.

PowerShell

$foo = 'Value 1'

$null = Measure-Command { $foo = 'Value 2' }

$foo

$null = Measure-Command { & { $foo = 'Value 3' } }

$foo

Value 2

Value 2

For more information about the invocation operator, see


about_Operators.

Parameters
-Expression

Specifies the expression that is being timed. Enclose the expression in braces ( {} ).

Type: ScriptBlock

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Objects bound to the InputObject parameter are optional input for the script block
passed to the
Expression parameter. Inside the script block, $_ can be used to
reference the current object
in the pipeline.

Type: PSObject

Position: Named

Default value: None


Accept pipeline input: True

Accept wildcard characters: False

Inputs
PSObject

You can pipe an object to this cmdlet.

Outputs
TimeSpan

This cmdlet returns a time span object representing the result.

Related Links
Invoke-Command
Trace-Command
Measure-Object
Reference
Module: Microsoft.PowerShell.Utility

Calculates the numeric properties of objects, and the characters, words, and lines in
string
objects, such as files of text.

Syntax
PowerShell

Measure-Object

[-InputObject <PSObject>]

[[-Property] <String[]>]

[-Sum]

[-Average]

[-Maximum]

[-Minimum]

[<CommonParameters>]

PowerShell

Measure-Object

[-InputObject <PSObject>]

[[-Property] <String[]>]

[-Line]

[-Word]

[-Character]

[-IgnoreWhiteSpace]

[<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. You
can use
Measure-Object to count objects or count objects with a specified Property. You
can also use
Measure-Object to calculate the Minimum, Maximum, Sum,
StandardDeviation and
Average of numeric values. For String objects, you can also use
Measure-Object to
count the number of lines, words, and characters.
Examples

Example 1: Count the files and folders in a directory


This command counts the files and folders in the current directory.

PowerShell

Get-ChildItem | Measure-Object

Example 2: Measure the files in a directory


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.

PowerShell

Get-ChildItem | Measure-Object -Property length -Minimum -Maximum -Sum -


Average

Example 3: Measure text in a text file


This command displays the number of characters, words, and lines in the Text.txt file.
Without the Raw parameter, Get-Content outputs the file as an array of lines.

The first command uses Set-Content to add some default text to a file.

PowerShell

"One", "Two", "Three", "Four" | Set-Content -Path C:\Temp\tmp.txt

Get-Content C:\Temp\tmp.txt | Measure-Object -Character -Line -Word

Lines Words Characters Property

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

4 4 15

Example 4: Measure objects containing a specified


Property
This example counts the number of objects that have a DisplayName property. The first
two
commands retrieve all the services and processes on the local machine. The third
command counts the
combined number of services and processes. The last command
combines the two collections and pipes
the result to Measure-Object .

The System.Diagnostics.Process object does not have a DisplayName property, and is


left out
of the final count.

PowerShell

$services = Get-Service
$processes = Get-Process

$services + $processes | Measure-Object

$services + $processes | Measure-Object -Property DisplayName

Count : 682

Average :

Sum :

Maximum :

Minimum :

Property :

Count : 290

Average :

Sum :

Maximum :

Minimum :

Property : DisplayName

Example 5: Measure the contents of a CSV file


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.

PowerShell

Import-Csv d:\test\serviceyrs.csv | Measure-Object -Property years -Minimum


-Maximum -Average

Example 6: Measure Boolean values


This example demonstrates how 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.

PowerShell

Get-ChildItem | Measure-Object -Property psiscontainer -Maximum -Sum -


Minimum -Average

Count : 126

Average : 0.0634920634920635

Sum : 8

Maximum : 1

Minimum : 0

StandardDeviation :

Property : PSIsContainer

Example 7: Measure strings


The following example measures the number of lines, first a single string, then across
several
strings. The newline character `n separates strings into multiple lines.

PowerShell

# The newline character `n separates the string into separate lines, as


shown in the output.

"One`nTwo`nThree"

"One`nTwo`nThree" | Measure-Object -Line

One

Two

Three

Lines Words Characters Property

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

# The first string counts as a single line.

# The second string is separated into two lines by the newline character.

"One", "Two`nThree" | Measure-Object -Line

Lines Words Characters Property

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

# The Word switch counts the number of words in each InputObject

# Each InputObject is treated as a single line.

"One, Two", "Three", "Four Five" | Measure-Object -Word -Line

Lines Words Characters Property

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

3 5

Parameters
-Average

Indicates that the cmdlet displays the average value of the specified properties.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Character

Indicates that the cmdlet counts the number of characters in the input objects.

7 Note

The Word, Char and Line switches count inside each input object, as well as
across
input objects. See Example 7.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-IgnoreWhiteSpace

Indicates that the cmdlet ignores white space in character counts.


By default, white
space is not ignored.

Type: SwitchParameter
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies the objects to be measured.


Enter a variable that contains the objects, or
type a command or expression that gets the objects.

When you use the InputObject parameter with Measure-Object , instead of piping
command results
to Measure-Object , the InputObject value is treated as a single
object.

It is recommended that you use Measure-Object in the pipeline if you want to


measure a
collection of objects based on whether the objects have specific values in
defined properties.

Type: PSObject

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Line

Indicates that the cmdlet counts the number of lines in the input objects.

7 Note

The Word, Char and Line switches count inside each input object, as well as
across
input objects. See Example 7.

Type: SwitchParameter

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-Maximum

Indicates that the cmdlet displays the maximum value of the specified properties.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Minimum

Indicates that the cmdlet displays the minimum value of the specified properties.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Property

Specifies one or more properties to measure. If you do not specify any other
measures,
Measure-Object counts the objects that have the properties you specify.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Sum
Indicates that the cmdlet displays the sum of the values of the specified properties.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Word

Indicates that the cmdlet counts the number of words in the input objects.

7 Note

The Word, Char and Line switches count inside each input object, as well as
across
input objects. See Example 7.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSObject

You can pipe objects to this cmdlet.

Outputs
GenericMeasureInfo

By default, this cmdlet returns a GenericMeasureInfo object.

TextMeasureInfo
When you use the Word parameter, this cmdlet returns a TextMeasureInfo object.

Notes
Windows PowerShell includes the following aliases for Measure-Object :

measure

Related Links
Compare-Object
ForEach-Object
Group-Object
New-Object
Select-Object
Sort-Object
Tee-Object
Where-Object
New-Alias
Reference
Module: Microsoft.PowerShell.Utility

Creates a new alias.

Syntax
PowerShell

New-Alias

[-Name] <String>

[-Value] <String>

[-Description <String>]

[-Option <ScopedItemOptions>]

[-PassThru]

[-Scope <String>]

[-Force]

[-WhatIf]

[-Confirm]

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

Examples

Example 1: Create an alias for a cmdlet


PowerShell

New-Alias -Name "List" Get-ChildItem

This command creates an alias named List to represent the Get-ChildItem cmdlet.
Example 2: Create a read-only alias for a cmdlet
PowerShell

New-Alias -Name "C" -Value Get-ChildItem -Description "quick gci alias" -


Option ReadOnly

Get-Alias -Name "C" | Format-List *

This command creates an alias named C to represent the Get-ChildItem 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.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Description

Specifies a description of the alias. You can type any string. If the description includes
spaces,
enclose it in quotation marks.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-Force

Indicates that the cmdlet acts like Set-Alias if the alias named already exists.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Name

Specifies the new alias. You can use any alphanumeric characters in an alias, but the
first
character cannot be a number.

Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Option

Specifies the value of the Options property of the alias.


Valid values are:

None : The alias has no constraints (default value)


ReadOnly : The alias can be deleted but cannot be changed except by using the

Force parameter
Constant : The alias cannot be deleted or changed
Private : The alias is available only in the current scope

AllScope : The alias is copied to any new scopes that are created
Unspecified : The option is not specified

These values are defined as a flag-based enumeration. You can combine multiple
values together to
set multiple flags using this parameter. The values can be passed
to the Option parameter as an
array of values or as a comma-separated string of
those values. The cmdlet will combine the values
using a binary-OR operation.
Passing values as an array is the simplest option and also allows you
to use tab-
completion on the values.

To see the Options property of all aliases in the session, type


Get-Alias | Format-
Table -Property Name, Options -AutoSize .

Type: ScopedItemOptions

Accepted values: None, ReadOnly, Constant, Private, AllScope, Unspecified

Position: Named

Default value: [System.Management.Automation.ScopedItemOptions]::None

Accept pipeline input: False

Accept wildcard characters: False

-PassThru

Returns an object representing the item with which you are working. By default, this
cmdlet does not
generate any output.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Scope

Specifies the scope of the new alias. The acceptable values for this parameter are:

Global
Local

Script

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.

Type: String
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Value

Specifies the name of the cmdlet or command element that is being aliased.

Type: String

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None
By default, this cmdlet returns no output.

AliasInfo

When you use the PassThru parameter, this cmdlet returns an AliasInfo object
representing
the new alias.

Notes
Windows PowerShell includes the following aliases for New-Alias :

nal

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 .

Related Links
Export-Alias
Get-Alias
Import-Alias
Set-Alias
New-Event
Reference
Module: Microsoft.PowerShell.Utility

Creates a new event.

Syntax
PowerShell

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

Examples

Example 1: Create a new event in the event queue


PowerShell

PS C:\> New-Event -SourceIdentifier Timer -Sender windows.timer -MessageData


"Test"

This command creates a new event in the PowerShell event queue. It uses a
Windows.Timer object
to send the event.

Example 2: Raise an event in response to another event


PowerShell

PS C:\> 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 PowerShell
event queue,
you do not need to register for that event.

Parameters
-EventArguments

Specifies an object that contains options for the event.

Type: PSObject[]
Position: 2

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-MessageData

Specifies additional data associated with the event. The value of this parameter
appears in the
MessageData property of the event object.

Type: PSObject

Position: 3

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Sender

Specifies the object that raises the event. The default is the PowerShell engine.

Type: PSObject

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SourceIdentifier

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.

Type: String

Position: 0

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

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

Related Links
Get-Event
Register-EngineEvent
Register-ObjectEvent
Remove-Event
Unregister-Event
Wait-Event
New-Guid
Reference
Module: Microsoft.PowerShell.Utility

Creates a GUID.

Syntax
PowerShell

New-Guid []

Description
The New-Guid cmdlet creates a random globally unique identifier (GUID). If you need a
unique ID in
a script, you can create a GUID, as needed.

Examples

Example 1: Create a GUID


PowerShell

New-Guid

This command creates a random GUID. Alternatively, you could store the output of this
cmdlet in a
variable to use elsewhere in a script.

Outputs
Guid

This cmdlet returns a GUID.


New-Object
Reference
Module: Microsoft.PowerShell.Utility

Creates an instance of a Microsoft .NET Framework or COM object.

Syntax
PowerShell

New-Object

[-TypeName] <String>

[[-ArgumentList] <Object[]>]

[-Property <IDictionary>]

[<CommonParameters>]

PowerShell

New-Object

[-ComObject] <String>

[-Strict]

[-Property <IDictionary>]

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

Examples

Example 1: Create a System.Version object


This example creates a System.Version object using the "1.2.3.4" string as the
constructor.
PowerShell

New-Object -TypeName System.Version -ArgumentList "1.2.3.4"

Major Minor Build Revision

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

1 2 3 4

Example 2: Create an Internet Explorer COM object


This example creates two instances of the COM object that represents the Internet
Explorer
application. The first instance uses the Property parameter hash table to call
the Navigate2
method and set the Visible property of the object to $True to make the
application visible.
The second instance gets the same results with individual commands.

PowerShell

$IE1 = New-Object -COMObject InternetExplorer.Application -Property


@{Navigate2="www.microsoft.com"; Visible = $True}

# The following command gets the same results as the example above.

$IE2 = New-Object -COMObject InternetExplorer.Application`

$IE2.Navigate2("www.microsoft.com")`

$IE2.Visible = $True`

Example 3: Use the Strict parameter to generate a non-


terminating error
This example demonstrates that adding the Strict parameter causes the New-Object
cmdlet to
generate a non-terminating error when the COM object uses an interop
assembly.

PowerShell

$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


primary interop assembly. If

this type exposes different members than the IDispatch 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


Example 4: Create a COM object to manage Windows
desktop
This example shows how to create and use a COM object to manage your Windows
desktop.

The first command uses the ComObject parameter of the New-Object cmdlet 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. Among
the methods is the ToggleDesktop method. The
third command calls the
ToggleDesktop method of the object to minimize the open windows on your
desktop.

PowerShell

$Objshell = New-Object -COMObject "Shell.Application"

$objshell | Get-Member

$objshell.ToggleDesktop()

TypeName: System.__ComObject#{866738b9-6cf2-4de8-8767-f794ebe74f4e}

Name MemberType Definition

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

AddToRecent Method void AddToRecent (Variant, string)

BrowseForFolder Method Folder BrowseForFolder (int, string, int,


Variant)

CanStartStopService Method Variant CanStartStopService (string)

CascadeWindows Method void CascadeWindows ()

ControlPanelItem Method void ControlPanelItem (string)

EjectPC Method void EjectPC ()

Explore Method void Explore (Variant)

ExplorerPolicy Method Variant ExplorerPolicy (string)

FileRun Method void FileRun ()

FindComputer Method void FindComputer ()

FindFiles Method void FindFiles ()

FindPrinter Method void FindPrinter (string, string, string)

GetSetting Method bool GetSetting (int)

GetSystemInformation Method Variant GetSystemInformation (string)

Help Method void Help ()

IsRestricted Method int IsRestricted (string, string)

IsServiceRunning Method Variant IsServiceRunning (string)

MinimizeAll Method void MinimizeAll ()

NameSpace Method Folder NameSpace (Variant)

Open Method void Open (Variant)

RefreshMenu Method void RefreshMenu ()

ServiceStart Method Variant ServiceStart (string, Variant)

ServiceStop Method Variant ServiceStop (string, Variant)

SetTime Method void SetTime ()

ShellExecute Method void ShellExecute (string, Variant, Variant,


Variant, Variant)

ShowBrowserBar Method Variant ShowBrowserBar (string, Variant)

ShutdownWindows Method void ShutdownWindows ()

Suspend Method void Suspend ()

TileHorizontally Method void TileHorizontally ()

TileVertically Method void TileVertically ()

ToggleDesktop Method void ToggleDesktop ()

TrayProperties Method void TrayProperties ()

UndoMinimizeALL Method void UndoMinimizeALL ()

Windows Method IDispatch Windows ()

WindowsSecurity Method void WindowsSecurity ()

WindowSwitcher Method void WindowSwitcher ()

Application Property IDispatch Application () {get}

Parent Property IDispatch Parent () {get}

Example 5: Pass multiple arguments to a constructor


This example shows how to create an object with a constructor that takes multiple
parameters. The
parameters must be put in an array when using ArgumentList
parameter.

PowerShell

$array = @('One', 'Two', 'Three')

$parameters = @{

TypeName = 'System.Collections.Generic.HashSet[string]'

ArgumentList = ([string[]]$array,
[System.StringComparer]::OrdinalIgnoreCase)

$set = New-Object @parameters

PowerShell binds each member of the array to a parameter of the constructor.

7 Note

This example uses parameter splatting for readability. For more information, see
about_Splatting.

Example 6: Calling a constructor that takes an array as a


single parameter
This example shows how to create an object with a constructor that takes a parameter
that is an
array or collection. The array parameter must be put in wrapped inside
another array.
PowerShell

$array = @('One', 'Two', 'Three')

# This command throws an exception.

$set = New-Object -TypeName 'System.Collections.Generic.HashSet[string]' -


ArgumentList $array

# This command succeeds.

$set = New-Object -TypeName 'System.Collections.Generic.HashSet[string]' -


ArgumentList (,[string[]]$array)

$set

New-Object : Cannot find an overload for "HashSet`1" and the argument count:
"3".

At line:1 char:8

+ $set = New-Object -TypeName 'System.Collections.Generic.HashSet[strin ...

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : InvalidOperation: (:) [New-Object],


MethodException

+ FullyQualifiedErrorId :
ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectComm
and

One

Two

Three

The first attempt to create the object in this example fails. PowerShell attempted to bind
the three
members of $array to parameters of the constructor but the constructor does
not take three
parameter. Wrapping $array in another array prevents PowerShell from
attempting to bind the three
members of $array to parameters of the constructor.

Parameters
-ArgumentList

Specifies an array of arguments to pass to the constructor of the .NET Framework


class. If the
constructor takes a single parameter that is an array, you must wrap that
parameter inside another
array. For example:

$cert = New-Object

System.Security.Cryptography.X509Certificates.X509Certificate -ArgumentList
(,$bytes)

For more information about the behavior of ArgumentList, see about_Splatting.

The alias for ArgumentList is Args.


Type: Object[]

Aliases: Args

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ComObject

Specifies the programmatic identifier (ProgID) of the COM object.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Property

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.

Type: IDictionary

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-Strict

Indicates that the cmdlet generates a non-terminating error when a COM object that
you attempt to
create uses an interop assembly. This feature distinguishes actual
COM objects from .NET Framework
objects with COM-callable wrappers.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-TypeName

Specifies the fully qualified name of the .NET Framework class. You cannot specify
both the
TypeName parameter and the ComObject parameter.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
Object

This cmdlet returns the object that it creates.


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

Related Links
about_Object_Creation
Compare-Object
Group-Object
Measure-Object
Select-Object
Sort-Object
Tee-Object
New-TemporaryFile
Reference
Module: Microsoft.PowerShell.Utility

Creates a temporary file.

Syntax
PowerShell

New-TemporaryFile

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
This cmdlet creates temporary files that you can use in scripts.

The New-TemporaryFile cmdlet creates an empty file that has the .tmp file name
extension.
This cmdlet names the file tmp<NNNN>.tmp , where <NNNN> is a random
hexadecimal number.
The cmdlet creates the file in your TEMP folder.

This cmdlet uses the Path.GetTempPath() method to find


your TEMP folder. This method
checks for the existence of environment variables in the following
order and uses the
first path found:

On Windows platforms:

1. The path specified by the TMP environment variable.


2. The path specified by the TEMP environment variable.
3. The path specified by the USERPROFILE environment variable.
4. The Windows directory.

On non-Windows platforms: Uses the path specified by the TMPDIR environment


variable.

Examples

Example 1: Create a temporary file


PowerShell

$TempFile = New-TemporaryFile

This command generates a .tmp file in your temporary folder, and then stores a
reference to the file
in the $TempFile variable. You can use this file later in your script.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs.


The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Outputs
FileInfo
This cmdlet returns a FileInfo object that represents the temporary file.
New-TimeSpan
Reference
Module: Microsoft.PowerShell.Utility

Creates a TimeSpan object.

Syntax
PowerShell

New-TimeSpan

[[-Start] <DateTime>]

[[-End] <DateTime>]

[<CommonParameters>]

PowerShell

New-TimeSpan

[-Days <Int32>]

[-Hours <Int32>]

[-Minutes <Int32>]

[-Seconds <Int32>]

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

Examples

Example 1: Create a TimeSpan object for a specified


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

PowerShell

$TimeSpan = New-TimeSpan -Hours 1 -Minutes 25

$TimeSpan

Days : 0

Hours : 1

Minutes : 25

Seconds : 0

Milliseconds : 0

Ticks : 51000000000

TotalDays : 0.0590277777777778

TotalHours : 1.41666666666667

TotalMinutes : 85

TotalSeconds : 5100

TotalMilliseconds : 5100000

Example 2: Create a TimeSpan object for a time interval


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.

PowerShell

New-TimeSpan -End (Get-Date -Year 2010 -Month 1 -Day 1)

Example 3: Get the date 90 days from the current date


PowerShell

$90days = New-TimeSpan -Days 90

(Get-Date) + $90days

These commands return the date that is 90 days after the current date.

Example 4: Discover the TimeSpan since a file was


updated
This command tells you how long it has been since the about_remote
help file was last
updated.
You can use this command format on any file, or any other object that has a
LastWriteTime
property.

This command works because the Start parameter of New-TimeSpan has an alias of
LastWriteTime. When you pipe an object that has a LastWriteTime property to New-
TimeSpan ,
PowerShell uses the value of the LastWriteTime property as the value of the

Start parameter.

PowerShell

Get-ChildItem $PSHOME\en-us\about_remote.help.txt | New-TimeSpan

Days : 321

Hours : 21

Minutes : 59

Seconds : 22

Milliseconds : 312

Ticks : 278135623127728

TotalDays : 321.916230471907

TotalHours : 7725.98953132578

TotalMinutes : 463559.371879547

TotalSeconds : 27813562.3127728

TotalMilliseconds : 27813562312.7728

Parameters
-Days

Specifies the days in the time span.


The default value is 0.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-End

Specifies the end of a time span.


The default value is the current date and time.

Type: DateTime
Position: 1

Default value: Current date and time

Accept pipeline input: True

Accept wildcard characters: False

-Hours

Specifies the hours in the time span.


The default value is zero.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Minutes

Specifies the minutes in the time span.


The default value is 0.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Seconds

Specifies the length of the time span in seconds.


The default value is 0.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-Start

Specifies 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 value is the current date and time.

You can use Start or its alias, LastWriteTime.


The LastWriteTime alias lets you pipe
objects that have a LastWriteTime property,
such as files in the file system
[System.Io.FileIO] , to the Start parameter of New-TimeSpan .

Type: DateTime

Aliases: LastWriteTime

Position: 0

Default value: Current date and time

Accept pipeline input: True

Accept wildcard characters: False

Inputs
DateTime

You can pipe a DateTime object representing the start time to this cmdlet.

Outputs
TimeSpan

This cmdlet returns an object representing the time span.

Related Links
Get-Date
Set-Date
New-Variable
Reference
Module: Microsoft.PowerShell.Utility

Creates a new variable.

Syntax
PowerShell

New-Variable

[-Name] <String>

[[-Value] <Object>]

[-Description <String>]

[-Option <ScopedItemOptions>]

[-Visibility <SessionStateEntryVisibility>]

[-Force]

[-PassThru]

[-Scope <String>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The New-Variable cmdlet creates a new variable in 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, 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.

Examples

Example 1: Create a variable


PowerShell

New-Variable days
This command creates a new variable named days. You are not required to type the
Name parameter.

Example 2: Create a variable and assign it a value


PowerShell

New-Variable -Name "zipcode" -Value 98033

This command creates a variable named zipcode and assigns it the value 98033.

Example 3: Create a variable with the ReadOnly option


PowerShell

PS C:\> New-Variable -Name Max -Value 256 -Option ReadOnly

PS C:\> New-Variable -Name max -Value 1024

New-Variable : A variable with name 'max' already exists.

At line:1 char:1

+ New-Variable -Name max -Value 1024

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : ResourceExists: (max:String) [New-Variable],


SessionStateException

+ FullyQualifiedErrorId :
VariableAlreadyExists,Microsoft.PowerShell.Commands.NewVariableCommand

PS C:\> New-Variable -Name max -Value 1024 -Force

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: Assign multiple options to a variable


PowerShell

New-Variable -Name 'TestVariable' -Value 'Test Value' -Option


AllScope,Constant

This example creates a variable and assigns the AllScope and Constant options so the
variable
will be available in the current scope and any new scopes created and cannot
be changed or deleted.

Example 5: Create a private variable


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.

PowerShell

PS C:\> New-Variable -Name counter -Visibility Private

#Effect of private variable in a module.

PS C:\> Get-Variable c*

Name Value

---- -----

Culture en-US

ConsoleFileName

ConfirmPreference High

CommandLineParameters {}

PS C:\> $counter

"Cannot access the variable '$counter' because it is a private variable"

At line:1 char:1

+ $counter

+ ~~~~~~~~

+ CategoryInfo : PermissionDenied: (counter:String) [],


SessionStateException

+ FullyQualifiedErrorId : VariableIsPrivate

PS C:\> Get-Counter

Name Value

---- -----

Counter1 3.1415

...

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.
Example 6: Create a variable with a space
This example demonstrates that variables with spaces can be created. The variables can
be accessed
using the Get-Variable cmdlet or directly by delimiting a variable with
braces.

PowerShell

PS C:\> New-Variable -Name 'with space' -Value 'abc123xyz'

PS C:\> Get-Variable -Name 'with space'

Name Value

---- -----

with space abc123xyz

PS C:\> ${with space}

abc123xyz

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Description

Specifies a description of the variable.

Type: String

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-Force

Indicates that the cmdlet creates a 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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Name

Specifies a name for the new variable.

Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Option

Specifies the value of the Options property of the variable. The acceptable values for
this
parameter are:

None - Sets no options. None is the default.

ReadOnly - Can be deleted. Cannot be changed, except by using the Force

parameter.
Private - The variable is available only in the current scope.

AllScope - The variable is copied to any new scopes that are created.
Constant - Cannot be deleted or changed. Constant is valid only when you are

creating a
variable. You cannot change the options of an existing variable to
Constant .

These values are defined as a flag-based enumeration. You can combine multiple
values together to
set multiple flags using this parameter. The values can be passed
to the Option parameter as an
array of values or as a comma-separated string of
those values. The cmdlet will combine the values
using a binary-OR operation.
Passing values as an array is the simplest option and also allows you
to use tab-
completion on the values.

To see the Options property of all variables in the session, type


Get-Variable |
Format-Table -Property name, options -AutoSize .

Type: ScopedItemOptions

Accepted values: None, ReadOnly, Constant, Private, AllScope, Unspecified

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-PassThru

Returns an object representing the item with which you are working. By default, this
cmdlet does not
generate any output.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Scope

Specifies the scope of the new variable. The acceptable values for this parameter are:
Global - Variables created in the global scope are accessible everywhere in a

PowerShell
process.
Local - The local scope refers to the current scope, this can be any scope

depending on the
context. Local is the default scope when the scope
parameter is not specified.
Script - Variables created in the script scope are accessible only within the

script file or
module they are created in.
A number relative to the current scope (0 through the number of scopes, where
0 is the current
scope, 1 is its parent, 2 the parent of the parent scope, and so
on). Negative numbers cannot be
used.

7 Note

The parameter also accepts the value of Private . Private is not actually a
scope but an
optional setting for a variable. However, using the Private value
with this cmdlet does not
change the visibility of the variable. For more
information, see
about_Scopes.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Value

Specifies the initial value of the variable.

Type: Object

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Visibility
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. The
acceptable values for this parameter 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.

Type: SessionStateEntryVisibility

Accepted values: Public, Private

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
Object

You can pipe any object to New-Variable .


Outputs
None

By default, this cmdlet returns no output.

PSVariable

When you use the PassThru parameter, this cmdlet returns a PSVariable object
representing
the new variable.

Notes
Windows PowerShell includes the following aliases for New-Variable :

nv

Related Links
Clear-Variable
Get-Variable
Remove-Variable
Set-Variable
Out-File
Reference
Module: Microsoft.PowerShell.Utility

Sends output to a file.

Syntax
PowerShell

Out-File

[-FilePath] <string>

[[-Encoding] <string>]

[-Append]

[-Force]

[-NoClobber]

[-Width <int>]

[-NoNewline]

[-InputObject <psobject>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Out-File

[[-Encoding] <string>]

-LiteralPath <string>

[-Append]

[-Force]

[-NoClobber]

[-Width <int>]

[-NoNewline]

[-InputObject <psobject>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Out-File cmdlet sends output to a file. It implicitly uses PowerShell's formatting
system to
write to the file. The file receives the same display representation as the
terminal. This means
that the output may not be ideal for programmatic processing
unless all input objects are strings.
When you need to specify parameters for the output,
use Out-File rather than the redirection
operator ( > ). For more information about
redirection, see
about_Redirection.

Examples

Example 1: Send output and create a file


This example shows how to send a list of the local computer's processes to a file. If the
file does
not exist, Out-File creates the file in the specified path.

PowerShell

Get-Process | Out-File -FilePath .\Process.txt

Get-Content -Path .\Process.txt

NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName

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

29 22.39 35.40 10.98 42764 9 Application

53 99.04 113.96 0.00 32664 0 CcmExec

27 96.62 112.43 113.00 17720 9 Code

The Get-Process cmdlet gets the list of processes running on the local computer. The
Process
objects are sent down the pipeline to the Out-File cmdlet. Out-File uses the
FilePath
parameter and creates a file in the current directory named Process.txt. The
Get-Content
command gets content from the file and displays it in the PowerShell

console.

Example 2: Prevent an existing file from being


overwritten
This example prevents an existing file from being overwritten. By default, Out-File
overwrites
existing files.

PowerShell

Get-Process | Out-File -FilePath .\Process.txt -NoClobber

Out-File : The file 'C:\Test\Process.txt' already exists.

At line:1 char:15

+ Get-Process | Out-File -FilePath .\Process.txt -NoClobber

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The Get-Process cmdlet gets the list of processes running on the local computer. The
Process
objects are sent down the pipeline to the Out-File cmdlet. Out-File uses the
FilePath
parameter and attempts to write to a file in the current directory named
Process.txt. The
NoClobber parameter prevents the file from being overwritten and
displays a message that the
file already exists.

Example 3: Send output to a file in ASCII format


This example shows how to encode output with a specific encoding type.

PowerShell

$Procs = Get-Process

Out-File -FilePath .\Process.txt -InputObject $Procs -Encoding ASCII -Width


50

The Get-Process cmdlet gets the list of processes running on the local computer. The
Process
objects are stored in the variable, $Procs . Out-File uses the FilePath parameter
and creates
a file in the current directory named Process.txt. The InputObject parameter
passes the
process objects in $Procs to the file Process.txt. The Encoding parameter
converts the
output to ASCII format. The Width parameter limits each line in the file to
50 characters so
some data might be truncated.

Example 4: Use a provider and send output to a file


This example shows how to use the Out-File cmdlet when you are not in a FileSystem
provider
drive. Use the Get-PSProvider cmdlet to view the providers on your local
computer. For more
information, see about_Providers.

PowerShell

PS> Set-Location -Path Alias:

PS> Get-Location

Path

----

Alias:\

PS> Get-ChildItem | Out-File -FilePath C:\TestDir\AliasNames.txt

PS> Get-Content -Path C:\TestDir\AliasNames.txt

CommandType Name

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

Alias % -> ForEach-Object

Alias ? -> Where-Object


Alias ac -> Add-Content

Alias cat -> Get-Content

The Set-Location command uses the Path parameter to set the current location to the
registry
provider Alias: . The Get-Location cmdlet displays the complete path for
Alias: .
Get-ChildItem sends objects down the pipeline to the Out-File cmdlet. Out-

File uses the


FilePath parameter to specify the complete path and filename for the
output,
C:\TestDir\AliasNames.txt. The Get-Content cmdlet uses the Path parameter
and displays the
file's content in the PowerShell console.

Example 5: Set file output width for entire scope


This example uses $PSDefaultParameterValues to set the Width parameter for all
invocations of
Out-File and the redirection operartors ( > and >> ) to 2000. This ensures
that everywhere
within the current scope that you output table formatted data to file,
PowerShell uses a line width
of 2000 instead of a line width determined by the
PowerShell host's console width.

PowerShell

function DemoDefaultOutFileWidth() {

try {

$PSDefaultParameterValues['out-file:width'] = 2000

$logFile = "$pwd\logfile.txt"

Get-ChildItem Env:\ > $logFile

Get-Service -ErrorAction Ignore | Format-Table -AutoSize | Out-File


$logFile -Append

Get-Process | Format-Table Id,SI,Name,Path,MainWindowTitle >>


$logFile

finally {

$PSDefaultParameterValues.Remove('out-file:width')

DemoDefaultOutFileWidth

For more information about $PSDefaultParameterValues , see


about_Preference_Variables.
Parameters
-Append

Adds the output to the end of an existing file. If no Encoding is specified, the cmdlet
uses the
default encoding. That encoding may not match the encoding of the target
file. This is the same
behavior as the redirection operator ( >> ).

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Encoding

Specifies the type of encoding for the target file. The default value is unicode .

The acceptable values for this parameter are as follows:

ascii Uses ASCII (7-bit) character set.

bigendianunicode Uses UTF-16 with the big-endian byte order.

default Uses the encoding that corresponds to the system's active code page
(usually ANSI).
oem Uses the encoding that corresponds to the system's current OEM code
page.
string Same as unicode .

unicode Uses UTF-16 with the little-endian byte order.


unknown Same as unicode .

utf7 Uses UTF-7.


utf8 Uses UTF-8.

utf32 Uses UTF-32 with the little-endian byte order.

Type: String

Accepted values: ASCII, BigEndianUnicode, Default, OEM, String, Unicode,


Unknown, UTF7, UTF8, UTF32

Position: 1

Default value: Unicode

Accept pipeline input: False

Accept wildcard characters: False

-FilePath

Specifies the path to the output file.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Force

Overrides the read-only attribute and overwrites an existing read-only file. The Force
parameter
does not override security restrictions.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-InputObject

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.

Type: PSObject

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-LiteralPath

Specifies the path to the output file. The LiteralPath parameter is used exactly as it is
typed.
Wildcard characters are not accepted. If the path includes escape characters,
enclose it in single
quotation marks. Single quotation marks tell PowerShell not to
interpret any characters as escape
sequences. For more information, see
about_Quoting_Rules.

Type: String

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-NoClobber

NoClobber prevents an existing file from being overwritten and displays a message
that the file
already exists. By default, if a file exists in the specified path, Out-File
overwrites the file
without warning.

Type: SwitchParameter

Aliases: NoOverwrite

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-NoNewline

Specifies that the content written to the file does not end with a newline character.
The string
representations of the input objects are concatenated to form the output.
No spaces or newlines are
inserted between the output strings. No newline is added
after the last output string.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Width

Specifies the number of characters in each line of output. Any additional characters
are truncated,
not wrapped. If this parameter is not used, the width is determined by
the characteristics of the
host. The default for the PowerShell console is 80
characters. If you want to control the width for
all invocations of Out-File as well as
the redirection operators ( > and >> ), set
$PSDefaultParameterValues['out-
file:width'] = 2000 before using Out-File .
Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSObject

You can pipe any object to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
Input objects are automatically formatted as they would be in the terminal, but you can
use a
Format-* cmdlet to explicitly control the formatting of the output to the file. For
example,
Get-Date | Format-List | Out-File out.txt

To send a PowerShell command's output to the Out-File cmdlet, use the pipeline.
Alternatively, you
can store data in a variable and use the InputObject parameter to
pass data to the Out-File
cmdlet.

Out-File saves data to a file but it does not produce any output objects to the pipeline.

Related Links
about_Providers
about_Quoting_Rules
Out-Default
Out-GridView
Out-Host
Out-Null
Out-Printer
Out-String
Tee-Object
Out-GridView
Reference
Module: Microsoft.PowerShell.Utility

Sends output to an interactive table in a separate window.

Syntax
PowerShell

Out-GridView

[-InputObject <PSObject>]

[-Title <String>]

[-PassThru]

[<CommonParameters>]

PowerShell

Out-GridView

[-InputObject <PSObject>]

[-Title <String>]

[-Wait]

[<CommonParameters>]

PowerShell

Out-GridView

[-InputObject <PSObject>]

[-Title <String>]

[-OutputMode <OutputModeOption>]

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

Because this cmdlet requires a user interface, it does not work on Windows Server Core
or Windows
Nano Server.

You can use the following features of the table to examine your data:
Hide, show, and reorder columns
Sort rows
Quick filter
Add criteria filter
Copy and paste

For full instructions, see the Notes section of this article.

Examples

Example 1: Output processes to a grid view


This example gets the processes running on the local computer and sends them to a
grid view window.

PowerShell

Get-Process | Out-GridView

Example 2: Use a variable to output processes to a grid


view
This example also gets the processes running on the local computer and sends them to
a grid view
window.

PowerShell

$P = Get-Process

$P | Out-GridView

The output of the Get-Process cmdlet is saved in the $P variable. Then, $P is piped to
Out-GridView .

Example 3: Display a selected properties in a grid view


This example displays selected properties of the running processes in a grid view.

PowerShell

Get-Process | Select-Object -Property Name, WorkingSet, PeakWorkingSet |

Sort-Object -Property WorkingSet -Descending | Out-GridView


The output of Get-Process is piped to Select-Object to select the Name, WorkingSet,
and
PeakWorkingSet properties. Another pipeline operator sends the filtered objects to
the
Sort-Object cmdlet to sort them in descending order by the value of the
WorkingSet property.
Then, the sorted results are piped to Out-GridView . You can now
use the features of the grid view
to search, sort, and filter the data.

Example 4: Save output to a variable, and then output a


grid view
This example saves cmdlet output in a variable then sends it to Out-GridView .

PowerShell

($A = Get-ChildItem -Path $PSHOME -Recurse) | Out-GridView

Get-ChildItem gets all the files in the PowerShell installation directory and its

subdirectories
using the the $PSHOME automatic variable. 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: Output processes for a specified computer to


a grid view
This example displays the processes that are running on the Server01 computer in a grid
view window.

PowerShell

Get-Process -ComputerName "Server01" | ogv -Title "Processes - Server01"

The examle uses ogv , which is the alias for the Out-GridView cmdlet. The Title
parameter
specifies the window title.

Example 6: Output data from remote computers to a grid


view
This example shows how to send data collected from remote computers to Out-
GridView .
PowerShell

Invoke-Command -ComputerName S1, S2, S3 -ScriptBlock {Get-Culture} | Out-


GridView

Invoke-Command runs Get-Culture on three remote computers. The resulting data is


piped to
Out-GridView . Notice that the script block that runs on the remote computer
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.

Example 7: Pass multiple items through `Out-GridView`


This example lets you select multiple processes from the Out-GridView window. The
processes that
you select are passed to the Export-Csv command and written to the
ProcessLog.csv file.

PowerShell

Get-Process | Out-GridView -PassThru | Export-Csv -Path .\ProcessLog.csv

The PassThru parameter of Out-GridView lets you send multiple items down the
pipeline. The
PassThru parameter is equivalent to using the Multiple value of the
OutputMode
parameter.

Example 8: Create a Windows shortcut to `Out-GridView`


This example shows how to use the Wait parameter of Out-GridView to create a
Windows shortcut
to the Out-GridView window.

PowerShell

pwsh -Command "Get-Service | Out-GridView -Wait"

This command line can be used in a Windows shortcut. Without the Wait parameter,
PowerShell
would exit as soon as the Out-GridView window opened, which would close
the Out-GridView window
almost immediately.

Parameters
-InputObject
Specifies object that the cmdlet accepts as input for Out-GridView .

When you use the InputObject parameter to send a collection 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 .

Type: PSObject

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-OutputMode

Specifies the items that the interactive window sends down the pipeline as input to
other commands.
By default, this cmdlet does not generate any output. To send
items from the interactive window down
the pipeline, click to select the items and
then click OK.

The values of this parameter determine how many items you can send down the
pipeline.

None . No items. This is the default value.

Single . Zero items or one item. Use this value when the next command can

take only one input


object.
Multiple . Zero, one, or many items. Use this value when the next command

can take multiple input


objects. This value is equivalent to the Passthru
parameter.

This parameter was introduced in Windows PowerShell 3.0.

Type: OutputModeOption

Accepted values: None, Single, Multiple

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-PassThru

Indicates that the cmdlet sends items from the interactive window down the pipeline
as input to
other commands. By default, this cmdlet does not generate any output.
This parameter is equivalent
to using the Multiple value of the OutputMode
parameter.

To send items from the interactive window down the pipeline, click to select the
items and then
click OK. Shift-click and Ctrl-click are supported.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Title

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 .

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Wait

Indicates that the cmdlet suppresses the command prompt and prevents Windows
PowerShell from closing
until the Out-GridView window is closed. By default, the
command prompt returns when the
Out-GridView window opens.

This feature lets you use the Out-GridView cmdlets in Windows shortcuts. When Out-
GridView is
used in a shortcut without the Wait parameter, the Out-GridView window

appears only
momentarily before PowerShell closes.
Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSObject

You can pipe any object to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

PSObject

When you use the PassThru parameter, this cmdlet returns objects representing the
selected
rows.

Notes
You cannot use a remote command to open a grid view window on another computer.

The command output that you send to Out-GridView cannot be formatted using the
Format cmdlets,
such as 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

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.
Use this key: To perform this action:

UpArrow Move up one row. Moves to column headers from first row of data.

DownArrow Move down one row.

LeftArrow In column header row, move left one column.

RightArrow In column header row, move right one column.

ContextMenuKey In column header row, displays the Select Columns option.

Enter or In column header row, sort column data (toggle A-Z, Z-A).
Spacebar

How to Use the Grid View Window Features

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 Select Columns box appear in the
grid view window.

To reorder columns:

You can drag and drop columns into the desired location. Or use the following steps:

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

Related Links
Out-File
Out-Printer
Out-String
Out-Printer
Reference
Module: Microsoft.PowerShell.Utility

Sends output to a printer.

Syntax
PowerShell

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. Since the cmdlet doesn't have any way to configure the print job, the
resulting print job
uses the default settings defined for the printer.

7 Note

This cmdlet was reintroduced in PowerShell 7. This cmdlet is only available on


Windows systems
that support the Windows Desktop.

Examples

Example 1 - Send a file to be printed on the default


printer
This example shows how to print a file, even though Out-Printer does not have a Path
parameter.

PowerShell

Get-Content -Path ./readme.txt | Out-Printer


Get-Content gets the contents of the readme.txt file in the current directory and pipes it

to
Out-Printer , which sends it to the default printer.

Example 2: Print a string to a remote printer


This example prints Hello, World to the Prt-6B Color printer on Server01.

PowerShell

"Hello, World" | Out-Printer -Name "\\Server01\Prt-6B Color"

The Name parameter selects a specific printer, rather than the default.

Example 3 - Print a help topic to the default printer


This example prints the full version of the Help topic for Get-CimInstance .

PowerShell

$H = Get-Help -Full Get-CimInstance

Out-Printer -InputObject $H

Get-Help gets the full version of the Help topic for Get-CimInstance and stores it in the
$H
variable. The InputObject parameter passes the value of $H to Out-Printer .

Parameters
-InputObject

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.

Type: PSObject

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name
Sends the output to the specified printer. The parameter name Name is optional.

Type: String

Aliases: PrinterName

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSObject

You can pipe any object to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
The cmdlets that contain the Out verb 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.

Out-Printer sends data to the printer, but does not emit any output objects to the

pipeline. If
you pipe the output of Out-Printer to Get-Member , Get-Member reports that
no objects have been
specified.

Related Links
Out-File
Out-String
Out-String
Reference
Module: Microsoft.PowerShell.Utility

Outputs input objects as a string.

Syntax
PowerShell

Out-String

[-Stream]

[-Width <Int32>]

[-InputObject <PSObject>]

[<CommonParameters>]

Description
The Out-String cmdlet converts input objects into 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 line at a time or create an array of strings.
This
cmdlet lets you search and manipulate string output as you would in traditional
shells when object
manipulation is less convenient.

PowerShell also adds the OSS function that calls Out-String -Stream as a shorthand way
to use
Out-String in a pipeline.

Examples

Example 1: Get the current culture and convert the data


to strings
This example gets the regional settings for the current user and converts the object data
to
strings.

PowerShell

$C = Get-Culture | Select-Object -Property *

Out-String -InputObject $C -Width 100

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 - en-US

TextInfo : TextInfo - en-US

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

The $C variable stores a Selected.System.Globalization.CultureInfo object. The object is


the
result of Get-Culture sending output down the pipeline to Select-Object . The
Property
parameter uses an asterisk ( * ) wildcard to specify all properties are contained
in the object.

Out-String uses the InputObject parameter to specify the CultureInfo object stored in

the
$C variable. The objects in $C are converted to a string.

7 Note

To view the Out-String array, store the output to a variable and use an array index
to view the
elements. For more information about the array index, see
about_Arrays.

$str = Out-String -InputObject $C -Width 100

Example 2: Working with objects


This example demonstrates the difference between working with objects and working
with strings. The
command displays an alias that includes the text gcm, the alias for Get-
Command .
PowerShell

Get-Alias | Out-String -Stream | Select-String -Pattern "gcm"

Alias gcm -> Get-Command

Get-Alias gets the System.Management.Automation.AliasInfo objects, one for each

alias, and
sends the objects down the pipeline. Out-String uses the Stream parameter
to convert each
object to a string rather than concatenating all the objects into a single
string.
The System.String objects are sent down the pipeline and Select-String uses
the Pattern
parameter to find matches for the text gcm.

7 Note

If you omit the Stream parameter, the command displays all the aliases because
Select-String
finds the text gcm in the single string that Out-String returns.

Example 3: Use the Width parameter to prevent


truncation.
While most output from Out-String is wrapped to the next line, there are scenarios
where the
output is truncated by the formatting system before being passed to Out-
String . You can avoid
truncation using the Width parameter.

PowerShell

PS> @{TestKey = ('x' * 200)} | Out-String

Name Value

---- -----

TestKey xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...

PS> @{TestKey = ('x' * 200)} | Out-String -Width 250

Name Value

---- -----

TestKey
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxx

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Parameters
-InputObject

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.

Type: PSObject

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Stream

By default, Out-String outputs a single string formatted as you would see it in the
console
including any blank headers or trailing newlines. The Stream parameter
enables Out-String to
output each line one by one. The only exception to this are
multiline strings. In that case,
Out-String will still output the string as a single,
multiline string.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Width

Specifies the number of characters in each line of output. Any additional characters
are wrapped to
the next line or truncated depending on the formatter cmdlet used.
The Width parameter applies
only to objects that are being formatted. If you omit
this parameter, the width is determined by the
characteristics of the host program. In
terminal (console) windows, the current window width is used
as the default value.
PowerShell console windows default to a width of 80 characters on
installation.

Type: Int32

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSObject

You can pipe any object to this cmdlet.

Outputs
String

This cmdlet returns the string that it creates from the input object.

Notes
The cmdlets that contain the Out verb don't format objects. The Out cmdlets send
objects to the
formatter for the specified display destination.

Related Links
about_Formatting
Out-Default
Out-File
Out-Host
Out-Null
Out-GridView
Out-Printer
Read-Host
Reference
Module: Microsoft.PowerShell.Utility

Reads a line of input from the console.

Syntax
PowerShell

Read-Host

[[-Prompt] <Object>]

[-AsSecureString]

[<CommonParameters>]

Description
The Read-Host cmdlet reads a line of input from the console (stdin). 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.

7 Note

Read-Host has a limit of 8190 characters it can accept as input from a user.

Examples

Example 1: Save console input to a variable


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

PowerShell

$Age = Read-Host "Please enter your age"

Example 2: Save console input as a secure string


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

PowerShell

$pwd_secure_string = Read-Host "Enter a Password" -AsSecureString

Parameters
-AsSecureString

Indicates that the cmdlet 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).

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Prompt

Specifies the text of the prompt. Type a string. If the string includes spaces, enclose it
in
quotation marks. PowerShell appends a colon ( : ) to the text that you enter.

Type: Object

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None
You can't pipe objects to this cmdlet.

Outputs
String

By default, this cmdlet returns a string.

SecureString

When you use AsSecureString parameter, this cmdlet returns a SecureString.

Notes
This cmdlet only reads from the stdin stream of the host process. Usually, the stdin
stream is
connected to the keyboard of the host console.

Related Links
Clear-Host
Get-Host
Write-Host
ConvertFrom-SecureString
Register-EngineEvent
Reference
Module: Microsoft.PowerShell.Utility

Subscribes to events that are generated by the PowerShell engine and by the New-Event
cmdlet.

Syntax
PowerShell

Register-EngineEvent

[-SourceIdentifier] <String>

[[-Action] <ScriptBlock>]
[-MessageData <PSObject>]
[-SupportEvent]

[-Forward]

[-MaxTriggerCount <Int32>]

[<CommonParameters>]

Description
The Register-EngineEvent cmdlet subscribes to events that are generated by the
PowerShell engine
and the New-Event cmdlet. Use the SourceIdentifier parameter to
specify the event.

You can use this cmdlet to subscribe to the OnIdle or Exiting engine events and events
generated by the New-Event cmdlet. These events are automatically added to the 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 you subscribe to a 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.

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.

Examples
Example 1: Register a PowerShell engine event on remote
computers
This example registers for a PowerShell engine event on two remote computers.

PowerShell

$S = New-PSSession -ComputerName "Server01, Server02"

Invoke-Command -Session $S {

Register-EngineEvent -SourceIdentifier
([System.Management.Automation.PsEngineEvent]::Exiting) -Forward

New-PSSession creates a user-managed session (PSSession) on each of the remote

computers.The
Invoke-Command cmdlet runs the Register-EngineEvent command in the
remote sessions.
Register-EngineEvent uses the SourceIdentifier parameter to identify
the event. The
Forward parameter tell the engine to forward the events from the remote
session to the local
session.

Example 2: Take a specified action when the Exiting event


occurs
This example shows how to run Register-EngineEvent to take a specific action when the
PowerShell.Exiting event occurs.

PowerShell

Register-EngineEvent -SourceIdentifier PowerShell.Exiting -SupportEvent -


Action {

Get-History | Export-Clixml $HOME\history.clixml

The SupportEvent parameter is added to hide the event subscription. When PowerShell
exits, in
this case, the command history from the exiting session is exported an XML file
in the user's
$HOME directory.

Example 3: Create and subscribe to a user-defined event


This example creates a subscription for events from the source MyEventSource. This is
an
arbitrary source that we are going to use to monitor the progress of a job. Register-
EngineEvent
is used to create the subscription. The script block for the Action parameter

logs the event


data to a text file.
PowerShell

Register-EngineEvent -SourceIdentifier MyEventSource -Action {

"Event: {0}" -f $event.messagedata | Out-File c:\temp\MyEvents.txt -


Append

Start-Job -Name TestJob -ScriptBlock {

While ($True) {

Register-EngineEvent -SourceIdentifier MyEventSource -Forward

Start-Sleep -seconds 2

"Doing some work..."

New-Event -SourceIdentifier MyEventSource -Message ("{0} - Work


done..." -f (Get-Date))

Start-Sleep -seconds 4

Get-EventSubscriber

Get-Job

SubscriptionId : 12

SourceObject :

EventName :

SourceIdentifier : MyEventSource

Action : System.Management.Automation.PSEventJob

HandlerDelegate :

SupportEvent : False

ForwardEvent : False

Id Name PSJobTypeName State HasMoreData


Location Command

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


- -------

18 MyEventSource Running True


19 TestJob BackgroundJob Running True


localhost …

Register-EngineEvent created Job Id 18. Start-Job created Job Id 19. In Example #4, we

remove
the event subscription and the jobs, then inspect the log file.

Example 4: Unregister events and clean up jobs


This is a continuation of Example 3. In this example we wait for 10 seconds to let several
events
occur. Then we unregister the event subscription.

PowerShell

PS> Start-Sleep -seconds 10

PS> Get-EventSubscriber | Unregister-Event

PS> Get-Job

Id Name PSJobTypeName State HasMoreData


Location Command

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


- -------

18 MyEventSource Stopped False


19 TestJob BackgroundJob Running True


localhost …

PS> Stop-Job -Id 19

PS> Get-Job | Remove-Job

PS> Get-Content C:\temp\MyEvents.txt

Event: 2/18/2020 2:36:19 PM - Work done...

Event: 2/18/2020 2:36:21 PM - Work done...

Event: 2/18/2020 2:36:23 PM - Work done...

Event: 2/18/2020 2:36:25 PM - Work done...

Event: 2/18/2020 2:36:27 PM - Work done...

Event: 2/18/2020 2:36:29 PM - Work done...

Event: 2/18/2020 2:36:31 PM - Work done...

The Unregister-Event cmdlet stops the job associated with the event subscription (Job
Id 18). Job
Id 19 is still running and creating new events. We use the Job cmdlets stop
the job and remove
the unneeded job objects. Get-Content displays the contents of the
log file.

Parameters
-Action

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 ,
$EventArgs , and $Args 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.

Type: ScriptBlock

Position: 101
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Forward

Indicates that the cmdlet 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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-MaxTriggerCount

Specifies the maximum number of times that the action is executed for the event
subscription.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-MessageData

Specifies additional data associated with the event. The value of this parameter
appears in the
MessageData property of the event object.

Type: PSObject

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-SourceIdentifier

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.

The value is specific to the source of the event. This can be an arbitrary value you
created to use
with the New-Event cmdlet. The PowerShell engine supports the
PSEngineEvent values
PowerShell.Exiting and PowerShell.OnIdle.

Type: String

Position: 100

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SupportEvent

Indicates that the cmdlet hides the event subscription. Add 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,
add the
Force parameter to the Get-EventSubscriber or Unregister-Event cmdlets.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

PSEventJob

When you use the Action parameter, this cmdlet returns a PSEventJob object.

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.

When subscribing to the Exiting event, the cmdlets that can be executed by the Action
parameter are limited to the cmdlets in the Microsoft.PowerShell.Core and
Microsoft.PowerShell.Utility modules. The Exiting event is only fired when the session is
exited under the control of PowerShell. The event is not fired when the host application
or terminal
window is closed.

The engine is considered to be idle if it is not running a pipeline. The OnIdle event is
fired
when PowerShell has been idle for 300 milliseconds (ms).

7 Note

When PSReadLine is in use, the OnIdle event is fired when ReadKey() times out (no
typing in
300ms). The event could be signaled while the user is in the middle of
editing a command line, for
example, the user is reading help to decide which
parameter to use. Beginning in PSReadLine
2.2.0-beta4, OnIdle behavior changed
to signal the event only if there is a ReadKey()
timeout and the current editing
buffer is empty.

Related Links
Get-Event
New-Event
Register-ObjectEvent
Remove-Event
Unregister-Event
Wait-Event
Register-ObjectEvent
Reference
Module: Microsoft.PowerShell.Utility

Subscribes to the events that are generated by a Microsoft .NET Framework object.

Syntax
PowerShell

Register-ObjectEvent

[-InputObject] <PSObject>
[-EventName] <String>

[[-SourceIdentifier] <String>]

[[-Action] <ScriptBlock>]
[-MessageData <PSObject>]
[-SupportEvent]

[-Forward]

[-MaxTriggerCount <Int32>]

[<CommonParameters>]

Description
The Register-ObjectEvent cmdlet subscribes to events that are generated by .NET
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 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.

Examples
Example 1: Subscribe to events when a new process starts
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.

PowerShell

$queryParameters = '__InstanceCreationEvent', (New-Object TimeSpan 0,0,1),

"TargetInstance isa 'Win32_Process'"

$Query = New-Object System.Management.WqlEventQuery -ArgumentList


$queryParameters

$ProcessWatcher = New-Object System.Management.ManagementEventWatcher $Query

Register-ObjectEvent -InputObject $ProcessWatcher -EventName "EventArrived"

Example 2: 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.

PowerShell

$queryParameters = '__InstanceCreationEvent', (New-Object TimeSpan 0,0,1),

"TargetInstance isa 'Win32_Process'"

$Query = New-Object System.Management.WqlEventQuery -ArgumentList


$queryParameters

$ProcessWatcher = New-Object System.Management.ManagementEventWatcher $query

$newEventArgs = @{

SourceIdentifier = 'PowerShell.ProcessCreated'

Sender = $Sender

EventArguments = $EventArgs.NewEvent.TargetInstance

$Action = { New-Event @newEventArgs }

Register-ObjectEvent -InputObject $ProcessWatcher -EventName "EventArrived"


-Action $Action

Id Name PSJobTypeName State HasMoreData Location


Command

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


-------

5 3db2d67a-efff-... NotStarted False


New-Event @newEventArgs
The action uses the $Sender and $EventArgs 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: Subscribe to object events on remote


computers
This example shows how to subscribe to object events on remote computers. This
example uses the
Enable-ProcessCreationEvent function that is defined in the
ProcessCreationEvent.ps1 script
file. This script is available to all computers in the

example.

PowerShell

# ProcessCreationEvent.ps1

function Enable-ProcessCreationEvent {

$queryParameters = "__InstanceCreationEvent", (New-Object TimeSpan


0,0,1),

"TargetInstance isa 'Win32_Process'"

$Query = New-Object System.Management.WqlEventQuery -ArgumentList


$queryParameters

$objectEventArgs = @{

Input = New-Object System.Management.ManagementEventWatcher $Query

EventName = 'EventArrived'

SourceIdentifier = 'WMI.ProcessCreated'

MessageData = 'Test'

Forward = $True

Register-ObjectEvent @objectEventArgs

$S = New-PSSession -ComputerName "Server01, Server02"

Invoke-Command -Session $S -FilePath ProcessCreationEvent.ps1

Invoke-Command -Session $S { Enable-ProcessCreationEvent }

The first we create PSSessions on two remote computers and save them in the $S
variable. Next,
the Invoke-Command cmdlet run the ProcessCreationEvent.ps1 script in
the each of the PSSessions
in $S . This action creates the Enable-ProcessCreationEvent
function in the remote sessions.
Finally, we run the Enable-ProcessCreationEvent
function in the remote sessions.
The function 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: Use the dynamic module in the PSEventJob


object
This example shows how to use the dynamic module in the PSEventJob object that is
created when
you include an Action in an event registration. First we createand and
enable a timer object,
then set the interval of the timer to 500 (milliseconds). The
Register-ObjectEvent cmdlet
registers the Elapsed event of the timer object. The

PSEventJob object is saved in the


$Job variable and is also available in the Action
property of the event subscriber. For more
information, see Get-EventSubscriber.

Whenever the timer interval elapses, an event is raised and the action is executed. In this
case,
the Get-Random cmdlet generates a random number between 0 and 100 and saves
it in the $Random
variable.

PowerShell

$Timer = New-Object Timers.Timer

$Timer.Interval = 500

$Timer.Enabled = $True

$objectEventArgs = @{

InputObject = $Timer

EventName = 'Elapsed'

SourceIdentifier = 'Timer.Random'

Action = {$Random = Get-Random -Min 0 -Max 100}

$Job = Register-ObjectEvent @objectEventArgs

$Job | Format-List -Property *

& $Job.module {$Random}


& $Job.module {$Random}

State : Running

Module : __DynamicModule_53113769-31f2-42dc-830b-8749325e28d6

StatusMessage :

HasMoreData : True

Location :

Command : $Random = Get-Random -Min 0 -Max 100

JobStateInfo : Running

Finished : System.Threading.ManualResetEvent

InstanceId : 47b5ec9f-bfe3-4605-860a-4674e5d44ca8

Id : 7

Name : Timer.Random

ChildJobs : {}

PSBeginTime : 6/27/2019 10:19:06 AM

PSEndTime :

PSJobTypeName :

Output : {}

Error : {}

Progress : {}

Verbose : {}

Debug : {}

Warning : {}

Information : {}

60

47

The PSEventJob has a Module property that contains a dynamic script module that
implements the
action. Using the call operator ( & ), we invoke the command in the
module to display the
value of the $Random variable.

For more information about modules, see about_Modules.

Parameters
-Action

Specifies the commands to handle the event. 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 ,
$EventArgs , and $Args automatic variables. These variables 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.

Type: ScriptBlock

Position: 101

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-EventName
Specifies the event to which you are subscribing.

The value of this parameter must be the name of the event that the .NET 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.

Type: String

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Forward

Indicates that the cmdlet 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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies the .NET object that generates the events. Enter a variable that contains the
object, or
type a command or expression that gets the object.

Type: PSObject

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-MaxTriggerCount

Specifies the maximum number of times an event can be triggered.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-MessageData

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.

Type: PSObject

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SourceIdentifier

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

The value of this parameter appears in the value of the SourceIdentifier property of
the
subscriber object and all event objects associated with this subscription.

Type: String

Position: 100

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-SupportEvent

Indicates that the cmdlet hides the event subscription. Use this parameter when the
current
subscription is part of a more complex event registration mechanism and
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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

PSEventJob

When you use the Action parameter, this cmdlet returns a PSEventJob object.

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.

Related Links
Get-Event
New-Event
Register-EngineEvent
Remove-Event
Unregister-Event
Wait-Event
Remove-Event
Reference
Module: Microsoft.PowerShell.Utility

Deletes events from the event queue.

Syntax
PowerShell

Remove-Event

[-SourceIdentifier] <String>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-Event

[-EventIdentifier] <Int32>

[-WhatIf]

[-Confirm]

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

Examples

Example 1: Remove an event by source identifier


PowerShell

PS C:\> Remove-Event -SourceIdentifier "ProcessStarted"


This command deletes events with a source identifier of Process Started from the event
queue.

Example 2: Remove an event by event identifier


PowerShell

PS C:\> Remove-Event -EventIdentifier 30

This command deletes the event with an event ID of 30 from the event queue.

Example 3: Remove all events


PowerShell

PS C:\> Get-Event | Remove-Event

This command deletes all events from the event queue.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-EventIdentifier

Specifies the event identifier for which the cmdlet deletes. An EventIdentifier or
SourceIdentifier parameter is required in every command.

Type: Int32
Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-SourceIdentifier

Specifies the source identifier for which this cmdlet deletes events from. Wildcards
are not
permitted. An EventIdentifier or SourceIdentifier parameter is required in
every command.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSEventArgs

You can pipe events from Get-Event to this cmdlet.


Outputs
None

This cmdlet returns no 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.

Related Links
Get-Event
New-Event
Register-EngineEvent
Register-ObjectEvent
Remove-Event
Unregister-Event
Wait-Event
Remove-PSBreakpoint
Reference
Module: Microsoft.PowerShell.Utility

Deletes breakpoints from the current console.

Syntax
PowerShell

Remove-PSBreakpoint

[-Breakpoint] <Breakpoint[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-PSBreakpoint

[-Id] <Int32[]>

[-WhatIf]

[-Confirm]

[<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 PowerShell


scripts. For more
information about the PowerShell debugger, see
about_Debuggers.

Examples

Example 1: Remove all breakpoints


This command deletes all of the breakpoints in the current console.

PowerShell

Get-PSBreakpoint | Remove-PSBreakpoint

Example 2: Remove a specified breakpoint


This command deletes a breakpoint.

PowerShell

$B = Set-PSBreakpoint -Script "sample.ps1" -Variable "Name"

$B | Remove-PSBreakpoint

The Set-PSBreakpoint cmdlet creates a breakpoint on the $Name variable in the


Sample.ps1
script and saves the breakpoint object in the $B variable. The Remove-
PSBreakpoint cmdlet
deletes 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: Remove a breakpoint by ID


This command deletes the breakpoint with breakpoint ID 2.

PowerShell

Remove-PSBreakpoint -Id 2

Example 4: Use a function to remove all breakpoints


This simple function deletes all of the breakpoints in the current console.

PowerShell

function del-psb { Get-PSBreakpoint | Remove-PSBreakpoint }

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.

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

Type: Breakpoint[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Id

Specifies breakpoint IDs for which this cmdlet deletes breakpoints.

Type: Int32[]

Position: 0

Default value: None

Accept pipeline input: True


Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs.


The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
Breakpoint[]

You can pipe breakpoint objects to this cmdlet.

Int32[]

Runspace

Outputs
None

This cmdlet returns no output.

Notes
Windows PowerShell includes the following aliases for Remove-PSBreakpoint :

rbp

Related Links
Disable-PSBreakpoint
Enable-PSBreakpoint
Get-PSBreakpoint
Get-PSCallStack
Set-PSBreakpoint
Remove-TypeData
Reference
Module: Microsoft.PowerShell.Utility

Deletes extended types from the current session.

Syntax
PowerShell

Remove-TypeData

-TypeData <TypeData>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-TypeData

[-TypeName] <String>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Remove-TypeData

-Path <String[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Remove-TypeData cmdlet deletes extended type data from the current session. This
cmdlet
affects only the current session and sessions that are created in the current
session.

You can add properties and methods to objects in PowerShell by defining them in
Update-TypeData
commands and Types.ps1xml files. Remove-TypeData deletes those

extended properties and methods


from the current session. Remove-TypeData does not
delete the Types.ps1xml files or delete any
extended type definitions from the
Types.ps1xml files. For more information about Types.ps1xml
files, see
about_Types.ps1xml.

This cmdlet was introduced in Windows PowerShell 3.0.

Examples

Example 1: Remove type data for a specified type


This example deletes all type data for the System.Array type from the session, including
type
data that was added by a Types.ps1xml file and dynamic type data that was added
to the session by
using the Update-TypeData cmdlet.

PowerShell

Remove-TypeData -TypeName System.Array

Example 2: Remove an extended data type from a session


This example shows the effect of removing extended type data from a session. The first
Get-TypeData gets extended type data for the System.DateTime type. The output shows

that a
DateTime property has been added to all System.DateTime objects in PowerShell.
The
Get-Date cmdlet returns a System.DateTime object. The command uses dot
notation to get the
value of the DateTime property of the System.DateTime object that
Get-Date returns.

PowerShell

Get-TypeData System.DateTime

(Get-Date).DateTime

Get-TypeData System.DateTime | Remove-TypeData

(Get-Date).DateTime

TypeName Members

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

System.DateTime {[DateTime,
System.Management.Automation.Runspaces.ScriptPropertyData]}

Friday, January 20, 2012 9:01:00 PM


The next Get-TypeData cmdlet to get all extended type data for the System.DateTime
type and
pipes that to the Remove-TypeData cmdlet to delete the extended type data.
The last Get-Date
cmdlet shows the effect of deleting the extended type data for the
System.DateTime type. Because
the System.DateTime property no longer exists, a
command to get its value returns nothing.

Example 3: Remove extended types for modules


This example removes all extended type data for module objects. When you pipe an
object to
Remove-TypeData , Remove-TypeData gets the name of the object type and
removes all type data for
all objects of that type.

PowerShell

Get-Module | Remove-TypeData

Example 4: Remove extended types from specified


modules
This example uses the Path parameter of the Remove-TypeData cmdlet to remove the
extended
types that are defined in the Types.ps1xml files that are added by the
PSScheduledJob and
PSWorkflow modules. This command does not affect dynamic
type data that is added by using the
Update-TypeData cmdlet. The command succeeds
only when the modules have been imported into the
current session.

PowerShell

Remove-TypeData -Path "$PSHOME\Modules\PSScheduledJob",


"$PSHOME\Modules\PSWorkflow\PSWorkflow.types.ps1xml"

For more information about modules, see about_Modules.

Example 5: Remove extended types from a remote


session
This example removes extended types from a remote session. The command uses the
Invoke-Command
cmdlet to remove extended type data for all CIM types in the sessions

in the $S variable.

PowerShell
Invoke-Command -Session $S {Get-TypeData -TypeName *CIM* | Remove-TypeData}

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Path

Specifies an array of files that this cmdlet deletes from the session extended type
data. This
parameter is required.

Enter the paths and file names of one or more Types.ps1xml files. Wildcards are not
supported. If
you omit the path, the default location is the current directory.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-TypeData

Specifies the type data that this cmdlet deletes from the session. This parameter is
required. Enter
a variable that contains TypeData objects
(System.Management.Automation.Runspaces.TypeData)
or a command that gets
TypeData objects, such as a Get-TypeData command. You can also pipe
TypeData
objects to Remove-TypeData .
Type: TypeData

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-TypeName

Specifies the types that this cmdlet deletes all extended type data for. For types in
the System
namespace, enter the short name. Otherwise, the full type name is
required. Wildcards are not
supported.

You can pipe type names to Remove-TypeData . When you pipe an object to Remove-
TypeData ,
Remove-TypeData gets the type name of the object and removes all type

data for the object type.

Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
TypeData

You can pipe a TypeData object, such as the ones that the Get-TypeData cmdlet returns,
to
this cmdlet.

String

You can pipe a string containing the type name to this cmdlet. When you pipe an object
to this
cmdlet, it gets the type name of the object and removes all type data for the
object type.

Outputs
None

This cmdlet returns no output.

Notes
Remove-TypeData can remove only the extended type data in the current session. It

cannot remove
extended type data that is on the computer, but has not been added to
the current session, such as
extended types that are defined in modules that have not
been imported into the current session.

Related Links
Get-TypeData
Update-TypeData
Remove-Variable
Reference
Module: Microsoft.PowerShell.Utility

Deletes a variable and its value.

Syntax
PowerShell

Remove-Variable

[-Name] <String[]>

[-Include <String[]>]

[-Exclude <String[]>]

[-Force]

[-Scope <String>]

[-WhatIf]

[-Confirm]

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

Examples

Example 1: Remove a variable


PowerShell

Remove-Variable Smp

This command deletes the $Smp variable.

Parameters
-Confirm
Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Exclude

Specifies an array of items that this cmdlet omits from the operation. The value of
this parameter
qualifies the Name parameter. Enter a name element or pattern, such
as "s*". Wildcards are
permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Force

Indicates that the cmdlet removes a variable even if it is read-only. Even using the
Force
parameter, the cmdlet cannot remove a constant.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Include
Specifies an array of items that this cmdlet deletes in the operation. The value of this
parameter
qualifies the Name parameter. Enter a name element or pattern, such as
s*. Wildcards are
permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Name

Specifies the name of the variable to be removed. The parameter name (Name) is
optional.
Wildcards are permitted

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-Scope

Gets only the variables in the specified scope. The acceptable values for this
parameter are:

Global
Local
Script
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.

Type: String

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSVariable

You can pipe a variable object to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
Windows PowerShell includes the following aliases for Remove-Variable :

rv

Changes affect only the current scope, such as a session. To delete a variable from
all sessions,
add a Remove-Variable command to your PowerShell profile.

Related Links
Clear-Variable
Get-Variable
New-Variable
Set-Variable
Select-Object
Reference
Module: Microsoft.PowerShell.Utility

Selects objects or object properties.

Syntax
PowerShell

Select-Object

[[-Property] <Object[]>]

[-InputObject <psobject>]

[-ExcludeProperty <string[]>]

[-ExpandProperty <string>]

[-Unique]

[-Last <int>]

[-First <int>]

[-Skip <int>]

[-Wait]

[<CommonParameters>]

PowerShell

Select-Object

[[-Property] <Object[]>]

[-InputObject <psobject>]

[-ExcludeProperty <string[]>]

[-ExpandProperty <string>]

[-Unique]

[-SkipLast <int>]

[<CommonParameters>]

PowerShell

Select-Object

[-InputObject <psobject>]

[-Unique]

[-Wait]

[-Index <int[]>]

[<CommonParameters>]

Description
The Select-Object cmdlet selects specified properties of an object or set of objects. It
can also
select unique objects, a specified number of objects, or objects in a specified
position in an
array.

To select objects from a collection, use the First, Last, Unique, Skip, and
Index
parameters. To select object properties, use the Property parameter. When you select
properties, Select-Object returns new objects that have only the specified properties.

Beginning in Windows PowerShell 3.0, Select-Object includes an optimization feature


that prevents
commands from creating and processing objects that aren't used.

When you use Select-Object with the First or Index parameters in a command pipeline,
PowerShell stops the command that generates the objects as soon as the selected
number of objects is
reached. To turn off this optimizing behavior, use the Wait
parameter.

Examples

Example 1: Select objects by property


This example creates objects that have the Name, ID, and working set (WS) properties
of
process objects.

PowerShell

Get-Process | Select-Object -Property ProcessName, Id, WS

Example 2: Select objects by property and format the


results
This example gets information about the modules used by the processes on the
computer. It uses
Get-Process cmdlet to get the process on the computer.

It uses the Select-Object cmdlet to output an array of


[System.Diagnostics.ProcessModule]
instances as contained in the Modules property of

each System.Diagnostics.Process instance


output by Get-Process .

The Property parameter of the Select-Object cmdlet selects the process names. This
adds a
ProcessName NoteProperty to every [System.Diagnostics.ProcessModule]
instance and populates
it with the value of current process's ProcessName property.
Finally, Format-List cmdlet is used to display the name and modules of each process in
a list.

PowerShell

Get-Process Explorer |

Select-Object -Property ProcessName -ExpandProperty Modules |

Format-List

ProcessName : explorer

ModuleName : explorer.exe

FileName : C:\WINDOWS\explorer.exe

BaseAddress : 140697278152704

ModuleMemorySize : 3919872

EntryPointAddress : 140697278841168

FileVersionInfo : File: C:\WINDOWS\explorer.exe

InternalName: explorer

OriginalFilename: EXPLORER.EXE.MUI

FileVersion: 10.0.17134.1 (WinBuild.160101.0800)

FileDescription: Windows Explorer

Product: Microsoft Windows Operating System

ProductVersion: 10.0.17134.1

...

Example 3: Select processes using the most memory


This example gets the five processes that are using the most memory. The Get-Process
cmdlet gets
the processes on the computer. The Sort-Object cmdlet sorts the processes
according to memory
(working set) usage, and the Select-Object cmdlet selects only
the last five members of the
resulting array of objects.

The Wait parameter isn't required in commands that include the Sort-Object cmdlet
because
Sort-Object processes all objects and then returns a collection. The Select-
Object optimization
is available only for commands that return objects individually as

they're processed.

PowerShell

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


Example 4: Select unique characters from an array
This example uses the Unique parameter of Select-Object to get unique characters
from an array
of characters.

PowerShell

"a","b","c","a","a","a" | Select-Object -Unique

Example 5: Using `-Unique` with other parameters


The Unique parameter filters values after other Select-Object parameters are applied.
For
example, if you use the First parameter to select the first number of items in an
array,
Unique is only applied to the selected values and not the entire array.

PowerShell

"a","a","b","c" | Select-Object -First 2 -Unique

In this example, First selects "a","a" as the first 2 items in the array. Unique is
applied
to "a","a" and returns a as the unique value.

Example 6: Select newest and oldest events in the event


log
This example gets the first (newest) and last (oldest) events in the Windows PowerShell
event log.

Get-EventLog gets all events in the Windows PowerShell log and saves them in the $a
variable.
Then, $a is piped to the Select-Object cmdlet. The Select-Object command
uses the Index
parameter to select events from the array of events in the $a variable.
The index of the first
event is 0. The index of the last event is the number of items in $a
minus 1.

PowerShell
$a = Get-EventLog -LogName "Windows PowerShell"

$a | Select-Object -Index 0, ($A.count - 1)

Example 7: Select all but the first object


This example creates a new PSSession on each of the computers listed in the Servers.txt
files,
except for the first one.

Select-Object selects 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.

PowerShell

New-PSSession -ComputerName (Get-Content Servers.txt | Select-Object -Skip


1)

Example 8: Rename files and select several to review


This example adds a "-ro" suffix to the base names of text files that have the read-only
attribute
and then displays the first five files so the user can see a sample of the effect.

Get-ChildItem uses the ReadOnly dynamic parameter to get read-only files. The
resulting files
are piped to the Rename-Item cmdlet, which renames the file. It uses the
PassThru parameter of
Rename-Item to send the renamed files to the Select-Object
cmdlet, which selects the first 5 for
display.

The Wait parameter of Select-Object prevents PowerShell from stopping the Get-
ChildItem
cmdlet after it gets the first five read-only text files. Without this parameter,
only the first
five read-only files would be renamed.

PowerShell

Get-ChildItem *.txt -ReadOnly |

Rename-Item -NewName {$_.BaseName + "-ro.txt"} -PassThru |

Select-Object -First 5 -Wait

Example 9: Show the intricacies of the -ExpandProperty


parameter
This example shows the intricacies of the ExpandProperty parameter.
Note that the output generated was an array of [System.Int32] instances. The instances
conform to
standard formatting rules of the Output View. This is true for any Expanded
properties. If the
outputted objects have a specific standard format, the expanded
property might not be visible.

PowerShell

# Create a custom object to use for the Select-Object example.

$object = [pscustomobject]@{Name="CustomObject";Expand=@(1,2,3,4,5)}

# Use the ExpandProperty parameter to Expand the property.

$object | Select-Object -ExpandProperty Expand -Property Name

# The output did not contain the Name property, but it was added
successfully.

# Use Get-Member to confirm the Name property was added and populated.

$object | Select-Object -ExpandProperty Expand -Property Name | Get-Member

TypeName: System.Int32

Name MemberType Definition

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

CompareTo Method int CompareTo(System.Object value), int


CompareTo(int value), ...

Equals Method bool Equals(System.Object obj), bool Equals(int


obj), bool IEq...

GetHashCode Method int GetHashCode()

GetType Method type GetType()

GetTypeCode Method System.TypeCode GetTypeCode(), System.TypeCode


IConvertible.Ge...

ToBoolean Method bool IConvertible.ToBoolean(System.IFormatProvider


provider)

ToByte Method byte IConvertible.ToByte(System.IFormatProvider


provider)

ToChar Method char IConvertible.ToChar(System.IFormatProvider


provider)

ToDateTime Method datetime


IConvertible.ToDateTime(System.IFormatProvider provider)

ToDecimal Method decimal


IConvertible.ToDecimal(System.IFormatProvider provider)

ToDouble Method double IConvertible.ToDouble(System.IFormatProvider


provider)

ToInt16 Method int16 IConvertible.ToInt16(System.IFormatProvider


provider)

ToInt32 Method int IConvertible.ToInt32(System.IFormatProvider


provider)

ToInt64 Method long IConvertible.ToInt64(System.IFormatProvider


provider)

ToSByte Method sbyte IConvertible.ToSByte(System.IFormatProvider


provider)

ToSingle Method float IConvertible.ToSingle(System.IFormatProvider


provider)

ToString Method string ToString(), string ToString(string format),


string ToS...

ToType Method System.Object IConvertible.ToType(type


conversionType, System...

ToUInt16 Method uint16 IConvertible.ToUInt16(System.IFormatProvider


provider)

ToUInt32 Method uint32 IConvertible.ToUInt32(System.IFormatProvider


provider)

ToUInt64 Method uint64 IConvertible.ToUInt64(System.IFormatProvider


provider)

Name NoteProperty string Name=CustomObject

Example 10: Create custom properties on objects


The following example demonstrates using Select-Object to add a custom property to
any object.
When you specify a property name that doesn't exist, Select-Object creates
that property as a
NoteProperty on each object passed.

PowerShell

$customObject = 1 | Select-Object -Property MyCustomProperty

$customObject.MyCustomProperty = "New Custom Property"

$customObject

MyCustomProperty

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

New Custom Property

Example 11: Create calculated properties for each


InputObject
This example demonstrates using Select-Object to add calculated properties to your
input. Passing
a ScriptBlock to the Property parameter causes Select-Object to
evaluate the expression on
each object passed and add the results to the output. Within
the ScriptBlock, you can use the
$_ variable to reference the current object in the
pipeline.

By default, Select-Object uses the ScriptBlock string as the name of the property. Using
a
Hashtable, you can label the output of your ScriptBlock as a custom property added
to each
object. You can add multiple calculated properties to each object passed to
Select-Object .
PowerShell

# Create a calculated property called $_.StartTime.DayOfWeek

Get-Process | Select-Object -Property ProcessName,{$_.StartTime.DayOfWeek}

ProcessName $_.StartTime.DayOfWeek

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

alg Wednesday

ati2evxx Wednesday

ati2evxx Thursday

...

# Add a custom property to calculate the size in KiloBytes of each FileInfo

# object you pass in. Use the pipeline variable to divide each file's length
by

# 1 KiloBytes

$size = @{label="Size(KB)";expression={$_.length/1KB}}

# Create an additional calculated property with the number of Days since the

# file was last accessed. You can also shorten the key names to be 'l', and
'e',

# or use Name instead of Label.

$days = @{l="Days";e={((Get-Date) - $_.LastAccessTime).Days}}

# You can also shorten the name of your label key to 'l' and your expression
key

# to 'e'.

Get-ChildItem $PSHOME -File | Select-Object Name, $size, $days

Name Size(KB) Days

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

Certificate.format.ps1xml 12.5244140625 223

Diagnostics.Format.ps1xml 4.955078125 223

DotNetTypes.format.ps1xml 134.9833984375 223

Example 12: Selecting the keys of a hashtable with


calculated properties
This example shows how you can use Select-Object to display the key-value pairs of a
hashtable object with calculated properties. Each calculated property hashtable
specifies
the label of the new property as the display name for the key and an
expression that retrieves the
value for that key.

PowerShell

@{ name = 'a' ; weight = 7 } | Select-Object -Property @(

@{ label = 'Name' ; expression = { $_.name } }

@{ label = 'Weight' ; expression = { $_.weight } }

Name Weight

---- ------

a 7

Parameters
-ExcludeProperty

Specifies the properties that this cmdlet excludes from the operation. Wildcards are
permitted. This
parameter is effective only when the command also includes the
Property parameter.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-ExpandProperty

Specifies a property to select, and indicates that an attempt should be made to


expand that
property. If the input object pipeline doesn't have the property named,
Select-Object returns an
error.

If the specified property is an array, each value of the array is included in the
output.
If the specified property is an object, the objects properties are expanded for
every
InputObject

In either case, the output objects' Type matches the expanded property's Type.

If the Property parameter is specified, Select-Object attempts to add each selected


property
as a NoteProperty to every outputted object.

2 Warning

If you receive an error that a property can't be processed because a property


with that name
already exists, consider the following. Note that when using
ExpandProperty, Select-Object
can not replace an existing property. This
means:
If the expanded object has a property of the same name, the command
returns an error.
If the Selected object has a property of the same name as an Expanded
object's property, the
command returns an error.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-First

Specifies the number of objects to select from the beginning of an array of input
objects.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Index

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.

Type: Int32[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-InputObject

Specifies objects to send to the cmdlet through the pipeline. This parameter enables
you to pipe
objects to Select-Object .

When you pass objects to the InputObject parameter, instead of using the pipeline,
Select-Object treats the InputObject as a single object, even if the value is a
collection. It
is recommended that you use the pipeline when passing collections to
Select-Object .

Type: PSObject

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Last

Specifies the number of objects to select from the end of an array of input objects.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Property

Specifies the properties to select. These properties are added as NoteProperty


members to the
output objects. Wildcards are permitted. If the input object doesn't
have the property named, the
value of the new NoteProperty is set to $null .

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>
For more information, see
about_Calculated_Properties.

Type: Object[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Skip

Skips (doesn't select) the specified number of items. By default, the Skip parameter
counts from
the beginning of the collection of objects. If the command uses the Last
parameter, it counts
from the end of the collection.

Unlike the Index parameter, which starts counting at 0, the Skip parameter begins at
1.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SkipLast

Skips (doesn't select) the specified number of items from the end of the list or array.
Works in
the same way as using Skip together with Last parameter.

Unlike the Index parameter, which starts counting at 0, the SkipLast parameter
begins at 1.

Type: Int32

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 should be selected.

Unique selects values after other filtering parameters are applied.

This parameter is case-sensitive. As a result, strings that differ only in character


casing are
considered to be unique.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Wait

Indicates that the cmdlet turns off optimization. PowerShell runs commands in the
order that they
appear in the command pipeline and lets them generate all objects.
By default, if you include a
Select-Object command with the First or Index
parameters in a command pipeline, PowerShell
stops the command that generates
the objects as soon as the selected number of objects is generated.

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSObject

You can pipe objects to this cmdlet.


Outputs
PSObject

This cmdlet returns the input objects with only the selected properties.

Notes
Windows PowerShell includes the following aliases for Select-Object :

select

The optimization feature of Select-Object is available only for commands that write
objects to
the pipeline as they're processed. It has no effect on commands that buffer
processed objects and
write them as a collection. Writing objects immediately is a
cmdlet design best practice. For more
information, see Write Single Records to the
Pipeline in
Strongly Encouraged Development Guidelines.

Related Links
about_Calculated_Properties
Group-Object
Sort-Object
Where-Object
Select-String
Reference
Module: Microsoft.PowerShell.Utility

Finds text in strings and files.

Syntax
PowerShell

Select-String

[-Pattern] <String[]>

[-Path] <String[]>

[-SimpleMatch]

[-CaseSensitive]

[-Quiet]

[-List]

[-Include <String[]>]

[-Exclude <String[]>]

[-NotMatch]

[-AllMatches]

[-Encoding <String>]

[-Context <Int32[]>]

[<CommonParameters>]

PowerShell

Select-String

-InputObject <PSObject>

[-Pattern] <String[]>

[-SimpleMatch]

[-CaseSensitive]

[-Quiet]

[-List]

[-Include <String[]>]

[-Exclude <String[]>]

[-NotMatch]

[-AllMatches]

[-Encoding <String>]

[-Context <Int32[]>]

[<CommonParameters>]

PowerShell

Select-String

[-Pattern] <String[]>

-LiteralPath <String[]>

[-SimpleMatch]

[-CaseSensitive]

[-Quiet]

[-List]

[-Include <String[]>]

[-Exclude <String[]>]

[-NotMatch]

[-AllMatches]

[-Encoding <String>]

[-Context <Int32[]>]

[<CommonParameters>]

Description
The Select-String cmdlet uses regular expression matching to search for text patterns
in input
strings and files. You can use Select-String similar to grep in UNIX or
findstr.exe 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. You can direct Select-String to find multiple matches per
line, display text
before and after the match, or display a Boolean value (True or False)
that indicates whether a
match is found.

Select-String can display all the text matches or stop after the first match in each input

file.
Select-String can be used to display all text that doesn't match the specified
pattern.

You can also specify that Select-String should expect a particular character encoding,
such as
when you're searching files of Unicode text. Select-String uses the byte-order-
mark (BOM) to
detect the encoding format of the file. If the file has no BOM, it assumes
the encoding is UTF8.

Examples

Example 1: Find a case-sensitive match


This example does a case-sensitive match of the text that was sent down the pipeline to
the
Select-String cmdlet.

PowerShell
'Hello', 'HELLO' | Select-String -Pattern 'HELLO' -CaseSensitive -
SimpleMatch

The text strings Hello and HELLO are sent down the pipeline to the Select-String
cmdlet.
Select-String uses the Pattern parameter to specify HELLO. The CaseSensitive
parameter
specifies that the case must match only the upper-case pattern. SimpleMatch
is an optional
parameter and specifies that the string in the pattern isn't interpreted as a
regular expression.
Select-String displays HELLO in the PowerShell console.

Example 2: Find matches in text files


This command searches all files with the .txt file name extension in the current
directory. The
output displays the lines in those files that include the specified string.

PowerShell

Get-Alias | Out-File -FilePath .\Alias.txt

Get-Command | Out-File -FilePath .\Command.txt

Select-String -Path .\*.txt -Pattern 'Get-'

Alias.txt:8:Alias cat -> Get-Content

Alias.txt:28:Alias dir -> Get-ChildItem

Alias.txt:43:Alias gal -> Get-Alias

Command.txt:966:Cmdlet Get-Acl

Command.txt:967:Cmdlet Get-Alias

In this example, Get-Alias and Get-Command are used with the Out-File cmdlet to
create two
text files in the current directory, Alias.txt and Command.txt.

Select-String uses the Path parameter with the asterisk ( * ) wildcard to search all files

in
the current directory with the file name extension .txt . The Pattern parameter
specifies the
text to match Get-. Select-String displays the output in the PowerShell
console. The file name
and line number precede each line of content that contains a
match for the Pattern parameter.

Example 3: Find a pattern match


In this example, multiple files are searched to find matches for the specified pattern. The
pattern
uses a regular expression quantifier. For more information, see
about_Regular_Expressions.

PowerShell
Select-String -Path "$PSHOME\en-US\*.txt" -Pattern '\?'

C:\Program Files\PowerShell\6\en-US\default.help.txt:27: beginning at


https://go.microsoft.com/fwlink/?LinkID=108518.

C:\Program Files\PowerShell\6\en-US\default.help.txt:50: or go to:


https://go.microsoft.com/fwlink/?LinkID=210614

The Select-String cmdlet uses two parameters, Path and Pattern. The Path parameter
uses the variable $PSHOME that specifies the PowerShell directory. The remainder of the
path
includes the subdirectory en-US and specifies each *.txt file in the directory. The
Pattern parameter specifies to match a question mark ( ? ) in each file. A backslash ( \ ) is
used as an escape character and is necessary because the question mark ( ? ) is a regular
expression
quantifier. Select-String displays the output in the PowerShell console. The
file name and line
number precede each line of content that contains a match for the
Pattern parameter.

Example 4: Use Select-String in a function


This example creates a function to search for a pattern in the PowerShell help files. For
this
example, the function only exists in the PowerShell session. When the PowerShell
session is closed,
the function is deleted. For more information, see
about_Functions.

PowerShell

function Search-Help

$PSHelp = "$PSHOME\en-US\*.txt"

Select-String -Path $PSHelp -Pattern 'About_'

Search-Help

C:\Windows\System32\WindowsPowerShell\v1.0\en-
US\about_ActivityCommonParameters.help.txt:2:
about_ActivityCommonParameters

C:\Windows\System32\WindowsPowerShell\v1.0\en-
US\about_ActivityCommonParameters.help.txt:31: see
about_WorkflowCommonParameters.

C:\Windows\System32\WindowsPowerShell\v1.0\en-
US\about_ActivityCommonParameters.help.txt:33: about_CommonParameters.

The function is created on the PowerShell command line. The Function command uses
the name
Search-Help . Press Enter to begin adding statements to the function. From
the >> prompt,
add each statement and press Enter as shown in the example. After the
closing bracket is added,
you're returned to a PowerShell prompt.
The function contains two commands. The $PSHelp variable stores the path to the
PowerShell help
files. $PSHOME is the PowerShell installation directory with the
subdirectory en-US that
specifies each *.txt file in the directory.

The Select-String command in the function uses the Path and Pattern parameters. The
Path parameter uses the $PSHelp variable to get the path. The Pattern parameter uses
the
string About_ as the search criteria.

To run the function, type Search-Help . The function's Select-String command displays
the output
in the PowerShell console.

Example 5: Search for a string in a Windows event log


This example searches for a string in a Windows event log. The variable $_ represents
the current
object in the pipeline. For more information, see about_Automatic_Variables.

PowerShell

$Events = Get-WinEvent -LogName Application -MaxEvents 50

$Events | Select-String -InputObject {$_.message} -Pattern 'Failed'

The Get-WinEvent cmdlet uses the LogName parameter to specify the Application log.
The
MaxEvents parameter gets the 50 most recent events from the log. The log content
is stored in
the variable named $Events .

The $Events variable is sent down the pipeline to the Select-String cmdlet. Select-
String uses
the InputObject parameter. The $_ variable represents the current object

and message is a
property of the event. The Pattern parameter species the string Failed
and searches for
matches in $_.message . Select-String displays the output in the
PowerShell console.

Example 6: Find a string in subdirectories


This example searches a directory and all of its subdirectories for a specific text string.

PowerShell

Get-ChildItem -Path C:\Windows\System32\*.txt -Recurse | Select-String -


Pattern 'Microsoft' -CaseSensitive

Get-ChildItem uses the Path parameter to specify C:\Windows\System32*.txt. The

Recurse parameter includes the subdirectories. The objects are sent down the pipeline
to
Select-String .

Select-String uses the Pattern parameter and specifies the string Microsoft. The
CaseSensitive parameter is used to match the exact case of the string. Select-String
displays
the output in the PowerShell console.

7 Note

Dependent upon your permissions, you might see Access denied messages in the
output.

Example 7: Find strings that do not match a pattern


This example shows how to exclude lines of data that don't match a pattern.

PowerShell

Get-Command | Out-File -FilePath .\Command.txt

Select-String -Path .\Command.txt -Pattern 'Get', 'Set' -NotMatch

The Get-Command cmdlet sends objects down the pipeline to the Out-File to create the
Command.txt file in the current directory. Select-String uses the Path parameter to
specify the Command.txt file. The Pattern parameter specifies Get and Set as the
search
pattern. The NotMatch parameter excludes Get and Set from the results.
Select-String
displays the output in the PowerShell console that doesn't include Get or
Set.

Example 8: Find lines before and after a match


This example shows how to get the lines before and after the matched pattern.

PowerShell

Get-Command | Out-File -FilePath .\Command.txt

Select-String -Path .\Command.txt -Pattern 'Get-Computer' -Context 2, 3

Command.txt:1186:Cmdlet Get-CmsMessage 3.0.0.0


Microsoft.PowerShell.Security

Command.txt:1187:Cmdlet Get-Command 3.0.0.0


Microsoft.PowerShell.Core

> Command.txt:1188:Cmdlet Get-ComputerInfo 3.1.0.0


Microsoft.PowerShell.Management

> Command.txt:1189:Cmdlet Get-ComputerRestorePoint 3.1.0.0


Microsoft.PowerShell.Management

Command.txt:1190:Cmdlet Get-Content 3.1.0.0


Microsoft.PowerShell.Management

Command.txt:1191:Cmdlet Get-ControlPanelItem 3.1.0.0


Microsoft.PowerShell.Management

Command.txt:1192:Cmdlet Get-Counter 3.0.0.0


Microsoft.PowerShell.Diagnostics

The Get-Command cmdlet sends objects down the pipeline to the Out-File to create the
Command.txt file in the current directory. Select-String uses the Path parameter to
specify the Command.txt file. The Pattern parameter specifies Get-Computer as the
search
pattern. The Context parameter uses two values, before and after, and marks
pattern matches in
the output with an angle bracket ( > ). The Context parameter
outputs the two lines before the
first pattern match and three lines after the last pattern
match.

Example 9: Find all pattern matches


This example shows how the AllMatches parameter finds each pattern match in a line of
text. By
default, Select-String only finds the first occurrence of a pattern in a line of
text. This
example uses object properties that are found with the Get-Member cmdlet.

PowerShell

$A = Get-ChildItem -Path "$PSHOME\en-US\*.txt" | Select-String -Pattern


'PowerShell'

$A

C:\Windows\System32\WindowsPowerShell\v1.0\en-
US\about_ActivityCommonParameters.help.txt:5: Describes the parameters
that Windows PowerShell

C:\Windows\System32\WindowsPowerShell\v1.0\en-
US\about_ActivityCommonParameters.help.txt:9: Windows PowerShell Workflow
adds the activity common

$A.Matches

Groups : {0}

Success : True

Name : 0

Captures : {0}

Index : 4

Length : 10

Value : PowerShell

$A.Matches.Length

2073

$B = Get-ChildItem -Path "$PSHOME\en-US\*.txt" | Select-String -Pattern


'PowerShell' -AllMatches

$B.Matches.Length

2200

The Get-ChildItem cmdlet uses the Path parameter. The Path parameter uses the
variable
$PSHOME that specifies the PowerShell directory. The remainder of the path
includes the
subdirectory en-US and specifies each *.txt file in the directory. The Get-
ChildItem objects
are stored in the $A variable. The $A variable is sent down the
pipeline to the Select-String
cmdlet. Select-String uses the Pattern parameter to
search each file for the string
PowerShell.

From the PowerShell command line, the $A variable contents are displayed. There's a
line that
contains two occurrences of the string PowerShell.

The $A.Matches property lists the first occurrence of the pattern PowerShell on each
line.

The $A.Matches.Length property counts the first occurrence of the pattern PowerShell
on each
line.

The $B variable uses the same Get-ChildItem and Select-String cmdlets, but adds the
AllMatches parameter. AllMatches finds each occurrence of the pattern PowerShell on
each
line. The objects stored in the $A and $B variables are identical.

The $B.Matches.Length property increases because for each line, every occurrence of the
pattern
PowerShell is counted.

Example 10 - Convert pipeline objects to strings using


`Out-String`
The ToString() result of the piped object isn't the same rich string representation
produced by
PowerShell's formatting system. So, you may need to pipe the objects to
Out-String first.

Piping to Out-String converts the formatted output into a single multi-line string
object. This
means that when Select-String finds a match it outputs the whole multiline
string.

PowerShell

PS> $hash = @{

Name = 'foo'

Category = 'bar'

# !! NO output, due to .ToString() conversion

$hash | Select-String -Pattern 'foo'

# Out-String converts the output to a single multi-line string object

PS> $hash | Out-String | Select-String -Pattern 'foo'

Name Value

---- -----

Name foo

Category bar

# Out-String -Stream converts the output to a multiple single-line string


objects

PS> $hash | Out-String -Stream | Select-String -Pattern 'foo'

Name foo

Piping to Out-String -Stream converts the formatted output into a multiple single-line
string
objects. This means that when Select-String finds a match it outputs only the
matching line.

Parameters
-AllMatches

Indicates that the cmdlet 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 the
matches.

7 Note

This parameter is ignored when used in combination with the SimpleMatch


parameter. If you wish
to return all matches and the pattern that you are
searching for contains regular expression
characters, you must escape those
characters rather than using SimpleMatch. See
about_Regular_Expressions for
more information about escaping regular expressions.

Type: SwitchParameter
Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-CaseSensitive

Indicates that the cmdlet matches are case-sensitive. By default, matches aren't case-
sensitive.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Context

Captures the specified number of lines before and after the line that matches the
pattern.

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. For example, -
Context 2,3 .

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.

The Context parameter doesn't change the number of objects generated by Select-
String .
Select-String generates one MatchInfo
object for each match. The context

is stored as an array of strings in the Context property of


the object.

When the output of a Select-String command is sent down the pipeline to another
Select-String
command, the receiving command searches only the text in the
matched line. The matched line is the
value of the Line property of the MatchInfo
object, not the text in the context lines. As a
result, the Context parameter isn't valid
on the receiving Select-String command.

When the context includes a match, the MatchInfo object for each match includes all
the context
lines, but the overlapping lines appear only once in the display.

Type: Int32[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Encoding

Specifies the type of encoding for the target file. The default value is default .

The acceptable values for this parameter are as follows:

ascii Uses ASCII (7-bit) character set.

bigendianunicode Uses UTF-16 with the big-endian byte order.

default Uses the encoding that corresponds to the system's active code page
(usually ANSI).
oem Uses the encoding that corresponds to the system's current OEM code
page.
unicode Uses UTF-16 with the little-endian byte order.

utf7 Uses UTF-7.


utf8 Uses UTF-8.

utf32 Uses UTF-32 with the little-endian byte order.

Type: String

Accepted values: ASCII, BigEndianUnicode, Default, OEM, Unicode, UTF7, UTF8,


UTF32

Position: Named

Default value: Default

Accept pipeline input: False

Accept wildcard characters: False


-Exclude

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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Include

Includes the specified items. The value of this parameter qualifies the Path
parameter. Enter a
path element or pattern, such as *.txt . Wildcards are permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-InputObject

Specifies the text to be searched. Enter a variable that contains the text, or type a
command or
expression that gets the text.

Using the InputObject parameter isn't the same as sending strings down the pipeline
to
Select-String .

When you pipe more than one string to the Select-String cmdlet, it searches for
the specified text
in each string and returns each string that contains the search text.

When you use the InputObject parameter to submit a collection of strings, Select-
String treats
the collection as a single combined string. Select-String returns the

strings as a unit if it
finds the search text in any string.

Type: PSObject
Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-List

Only the first instance of matching text is returned from each input file. This is the
most
efficient way to retrieve a list of files that have contents matching the regular
expression.

By default, Select-String returns a MatchInfo object for each match it finds.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-LiteralPath

Specifies the path to the files to be searched. The value of the LiteralPath parameter
is used
exactly as it's typed. No characters are interpreted as wildcards. If the path
includes escape
characters, enclose it in single quotation marks. Single quotation
marks tell PowerShell not to
interpret any characters as escape sequences. For more
information, see
about_Quoting_Rules.

Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-NotMatch
The NotMatch parameter finds text that doesn't match the specified pattern.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Path

Specifies the path to the files to search. 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.

Type: String[]

Position: 1

Default value: Local directory

Accept pipeline input: True

Accept wildcard characters: True

-Pattern

Specifies the text to find on each line. The pattern value is treated as a regular
expression.

To learn about regular expressions, see


about_Regular_Expressions.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Quiet
Indicates that the cmdlet 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.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-SimpleMatch

Indicates that the cmdlet 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 doesn't
interpret the value of the Pattern parameter as a
regular expression statement.

Also, when SimpleMatch is used, the Matches property of the MatchInfo object
returned is
empty.

7 Note

When this parameter is used with the AllMatches parameter, the AllMatches is
ignored.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSObject

You can pipe any object that has a ToString() method to this cmdlet.
Outputs
MatchInfo

By default, this cmdlet returns a MatchInfo object for each match found.

Boolean

When you use the Quiet parameter, this cmdlet returns a Boolean value indicating
whether
the pattern was found.

Notes
Windows PowerShell includes the following aliases for Select-String :

sls

Select-String is similar to grep in UNIX or findstr.exe in Windows.

7 Note

According to
Approved Verbs for PowerShell Commands,
the official alias prefix
for Select-* cmdlets is sc , not sl . Therefore, the proper alias
for Select-String
should be scs , not sls . This is an exception to this rule.

When piping objects to Select-String :

FileInfo objects are treated as a path to a file. When file paths are specified,
Select-String searches the contents of the file, not the ToString() representation

of the
object.
The ToString() result of the piped object isn't the same rich string representation
produced by
PowerShell's formatting system. So, you may need to pipe the objects
to Out-String first. For
more information, see Example 10.

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, use the following criteria:

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. 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're
searching for text in files,
because MatchInfo objects have properties such as Filename
and Line. When the input
isn't from the file, the value of these parameters is
InputStream.

If you don't need the information in the MatchInfo object, use the Quiet parameter. The
Quiet parameter 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 culture 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 command:

Select-String -Path test.txt -Pattern 'test' | Get-Member | Format-List -Property

Related Links
about_Automatic_Variables
about_Comparison_Operators
about_Functions
about_Quoting_Rules
about_Regular_Expressions
Get-Alias
Get-ChildItem
Get-Command
Get-Member
Get-WinEvent
Out-File
Select-Xml
Reference
Module: Microsoft.PowerShell.Utility

Finds text in an XML string or document.

Syntax
PowerShell

Select-Xml

[-XPath] <string>

[-Xml] <XmlNode[]>

[-Namespace <hashtable>]

[<CommonParameters>]

PowerShell

Select-Xml

[-XPath] <string>

[-Path] <string[]>

[-Namespace <hashtable>]

[<CommonParameters>]

PowerShell

Select-Xml

[-XPath] <string>

-LiteralPath <string[]>

[-Namespace <hashtable>]

[<CommonParameters>]

PowerShell

Select-Xml

[-XPath] <string>

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

Examples

Example 1: Select AliasProperty nodes


This example gets the alias properties in the Types.ps1xml . For information about this
file, see
about_Types.ps1xml.

The first command saves the path to the Types.ps1xml file in the $Path variable.

The second command saves the XML path to the AliasProperty node in the $XPath
variable.

The Select-Xml cmdlet gets the AliasProperty nodes that are identified by
the XPath
statement from the Types.ps1xml file. The command uses a pipeline operator ( | ) to
send the
AliasProperty nodes to the Select-Object cmdlet. The ExpandProperty
parameter expands the
Node object and returns its Name and
ReferencedMemberName properties.

PowerShell

$Path = "$Pshome\Types.ps1xml"

$XPath = "/Types/Type/Members/AliasProperty"

Select-Xml -Path $Path -XPath $Xpath | Select-Object -ExpandProperty Node

Name ReferencedMemberName

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

Count Length

Name Key

Name ServiceName

RequiredServices ServicesDependedOn

ProcessName Name

Handles Handlecount

VM VirtualSize

WS WorkingSetSize

Name ProcessName

Handles Handlecount

VM VirtualMemorySize

WS WorkingSet

PM PagedMemorySize

NPM NonpagedSystemMemorySize

Name __Class

Namespace ModuleName
The result shows the Name and ReferencedMemberName of each alias property in the
Types.ps1xml
file. For example, there is a Count property that is an alias of the Length
property.

Example 2: Input an XML document


This example shows how to use the XML parameter to provide an XML document to the
Select-Xml
cmdlet.

The Get-Content cmdlet gets the content of the Types.ps1xml file and saves it in the
$Types
variable. The [xml] casts the variable as an XML object.

The Select-Xml cmdlet gets the MethodName nodes in the Types.ps1xml file. The
command uses
the Xml parameter to specify the XML content in the $Types variable
and the XPath
parameter to specify the path to the MethodName node.

PowerShell

[xml]$Types = Get-Content $Pshome\Types.ps1xml

Select-Xml -Xml $Types -XPath "//MethodName"

Example 3: Search PowerShell Help files


This example shows how to use the Select-Xml cmdlet to search the PowerShell XML-
based cmdlet help
files. In this example, we'll search for the cmdlet name that serves as
a title for each help file
and the path to the help file.

The $Namespace variable contains a hash table that represents the XML namespace that
is used for
the help files.

The $Path variable contains the path to the PowerShell help files. If there are no help
files in
this path on your computer, use the Update-Help cmdlet to download the help
files. For more
information about Updatable Help, see
about_Updatable_Help.

The Select-Xml cmdlet searches the XML files for cmdlet names by finding
Command:Name element
anywhere in the files. The results are stored in the $Xml variable.

Select-Xml returns a
SelectXmlInfo object that has a Node property, which is a
System.Xml.XmlElement object.
The Node property has an InnerXML property that
contains the actual XML that is retrieved.

The $Xml variable is piped to the Format-Table cmdlet. The Format-Table command
uses a
calculated property to get the Node.InnerXML property of each object in the
$Xml variable,
trim the white space before and after the text, and display it in the table,

along with the Path


to the source file.

PowerShell

$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"

$Path = "$Pshome\en-us\*dll-Help.xml"

$Xml = Select-Xml -Path $Path -Namespace $Namespace -XPath "//command:name"

$Xml | Format-Table @{Label="Name"; Expression=


{($_.node.innerxml).trim()}}, Path -AutoSize

Name Path

---- ----

Export-Counter C:\Windows\system32\WindowsPowerShell\v1.0\en-
us\Microsoft.PowerShell.Commands.Diagnostics.dll-Help.xml

Get-Counter C:\Windows\system32\WindowsPowerShell\v1.0\en-
us\Microsoft.PowerShell.Commands.Diagnostics.dll-Help.xml

Get-WinEvent C:\Windows\system32\WindowsPowerShell\v1.0\en-
us\Microsoft.PowerShell.Commands.Diagnostics.dll-Help.xml

Import-Counter C:\Windows\system32\WindowsPowerShell\v1.0\en-
us\Microsoft.PowerShell.Commands.Diagnostics.dll-Help.xml

Add-Computer C:\Windows\system32\WindowsPowerShell\v1.0\en-
us\Microsoft.PowerShell.Commands.Management.dll-Help.xml

Add-Content C:\Windows\system32\WindowsPowerShell\v1.0\en-
us\Microsoft.PowerShell.Commands.Management.dll-Help.xml

Checkpoint-Computer C:\Windows\system32\WindowsPowerShell\v1.0\en-
us\Microsoft.PowerShell.Commands.Management.dll-Help.xml

...

Example 4: Different ways to input XML


This example shows two different ways to send XML to the Select-Xml cmdlet.

The first command saves a here-string that contains XML in the $Xml variable. For more
information
about here-strings, see
about_Quoting_Rules.

Select-Xml uses the Content parameter to specify the XML in the $Xml variable.

The third command is the same as the second, except that tt uses a pipeline operator
( | ) to send
the XML in the $Xml variable to the Select-Xml cmdlet.

PowerShell
$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>

"@

Select-Xml -Content $Xml -XPath "//edition" | foreach {$_.node.InnerXML}

En.Book1.com

Ge.Book1.Com

Fr.Book1.com

Pl.Book1.com

$Xml | Select-Xml -XPath "//edition" | foreach {$_.node.InnerXML}

En.Book1.com

Ge.Book1.Com

Fr.Book1.com

Pl.Book1.com

Example 5: Use the default xmlns namespace


This example shows how to use the Select-Xml cmdlet with XML documents that use
the default xmlns
namespace. The example gets the titles of Windows PowerShell ISE
user-created snippet files. For
information about snippets, see New-IseSnippet.

The $SnippetNamespace variable contains a hash table for the default namespace that
snippet XML
files use. The hash table value is the XMLNS schema URI in the snippet
XML. The hash table key name,
snip, is arbitrary. You can use any name that is not
reserved, but you cannot use xmlns.

The Select-Xml cmdlet gets the content of the Title element of each snippet. It uses the
Path parameter to specify the Snippets directory and the Namespace parameter to
specify the
namespace in the $SnippetNamespace variable. The value of the XPath
parameter is the
snip:Title . The results are piped to the ForEach-Object cmdlet, which
gets the title from the
value of the InnerXml property of the node.
PowerShell

$SnippetNamespace = @{snip =
"http://schemas.microsoft.com/PowerShell/Snippets"}

Select-Xml -Path $HOME\Documents\WindowsPowerShell\Snippets -Namespace


$SnippetNamespace -XPath "//snip:Title" |

ForEach-Object {$_.Node.Innerxml}

Parameters
-Content

Specifies a string that contains the XML to search. You can also pipe strings to
Select-Xml .

Type: String[]

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-LiteralPath

Specifies the paths and file names of the XML files to search. 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 PowerShell not to interpret any
characters as escape sequences.

Type: String[]

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False


-Namespace

Specifies a hash table of the namespaces used in the XML. Use the
format @{<namespaceName> = <namespaceValue>} .

When the XML uses the default namespace, which begins with xmlns, use an
arbitrary key for the
namespace name. You cannot use xmlns. In the XPath statement,
prefix each node name with the
namespace name and a colon, such as
//namespaceName:Node .

Type: Hashtable

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Path

Specifies the path and file names of the XML files to search. Wildcard characters are
permitted.

Type: String[]

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-Xml

Specifies one or more XML nodes.

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.

Type: XmlNode[]

Aliases: Node

Position: 1
Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-XPath

Specifies an XPath search query. The query language is case-sensitive. This


parameter is required.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
System.String or System.Xml.XmlNode

You can pipe a path or XML node to this cmdlet.

Outputs
SelectXmlInfo

Notes
XPath is a standard language that is designed to identify parts of an XML document. For
more
information about the XPath language, see
XPath Reference and the Selection
Filters section of Event Selection .

Related Links
ConvertTo-Xml
Send-MailMessage
Reference
Module: Microsoft.PowerShell.Utility

Sends an email message.

Syntax
PowerShell

Send-MailMessage

[-To] <string[]>

[-Subject] <string>

[[-Body] <string>]

[[-SmtpServer] <string>]

-From <string>

[-Attachments <string[]>]

[-Bcc <string[]>]

[-BodyAsHtml]

[-Encoding <Encoding>]

[-Cc <string[]>]

[-DeliveryNotificationOption <DeliveryNotificationOptions>]

[-Priority <MailPriority>]

[-Credential <pscredential>]

[-UseSsl]

[-Port <int>]

[<CommonParameters>]

Description
The Send-MailMessage cmdlet sends an email message from within PowerShell.

You must specify a Simple Mail Transfer Protocol (SMTP) server or the Send-MailMessage
command
fails. Use the SmtpServer parameter or set the $PSEmailServer variable to a
valid SMTP server.
The value assigned to $PSEmailServer is the default SMTP setting for
PowerShell. For more
information, see about_Preference_Variables.

2 Warning

The Send-MailMessage cmdlet is obsolete. This cmdlet does not guarantee secure
connections to
SMTP servers. While there is no immediate replacement available in
PowerShell, we recommend you do
not use Send-MailMessage . For more
information, see
Platform Compatibility note DE0005 .

Examples

Example 1: Send an email from one person to another


person
This example sends an email message from one person to another person.

The From, To, and Subject parameters are required by Send-MailMessage . This example
uses the default $PSEmailServer variable for the SMTP server, so the SmtpServer
parameter is
not needed.

PowerShell

Send-MailMessage -From 'User01 <user01@fabrikam.com>' -To 'User02


<user02@fabrikam.com>' -Subject 'Test mail'

The Send-MailMessage cmdlet uses the From parameter to specify the message's sender.
The
To parameter specifies the message's recipient. The Subject parameter uses the text
string
Test mail as the message because the optional Body parameter is not included.

Example 2: Send an attachment


This example sends an email message with an attachment.

PowerShell

Send-MailMessage -From 'User01 <user01@fabrikam.com>' -To 'User02


<user02@fabrikam.com>', 'User03 <user03@fabrikam.com>' -Subject 'Sending the
Attachment' -Body "Forgot to send the attachment. Sending now." -Attachments
.\data.csv -Priority High -DeliveryNotificationOption OnSuccess, OnFailure -
SmtpServer 'smtp.fabrikam.com'

The Send-MailMessage cmdlet uses the From parameter to specify the message's sender.
The
To parameter specifies the message's recipients. The Subject parameter describes
the content
of the message. The Body parameter is the content of the message.

The Attachments parameter specifies the file in the current directory that is attached to
the
email message. The Priority parameter sets the message to High priority. The
-
DeliveryNotificationOption parameter specifies two values, OnSuccess and OnFailure.
The
sender will receive email notifications to confirm the success or failure of the
message delivery.
The SmtpServer parameter sets the SMTP server to
smtp.fabrikam.com.

Example 3: Send email to a mailing list


This example sends an email message to a mailing list.

PowerShell

Send-MailMessage -From 'User01 <user01@fabrikam.com>' -To 'ITGroup


<itdept@fabrikam.com>' -Cc 'User02 <user02@fabrikam.com>' -Bcc 'ITMgr
<itmgr@fabrikam.com>' -Subject "Don't forget today's meeting!" -Credential
domain01\admin01 -UseSsl

The Send-MailMessage cmdlet uses the From parameter to specify the message's sender.
The
To parameter specifies the message's recipients. The Cc parameter sends a copy of
the
message to the specified recipient. The Bcc parameter sends a blind copy of the
message. A blind
copy is an email address that is hidden from the other recipients. The
Subject parameter is the
message because the optional Body parameter is not included.

The Credential parameter specifies a domain administrator's credentials are used to


send the
message. The UseSsl parameter specifies that Secure Socket Layer (SSL) creates
a secure
connection.

Parameters
-Attachments

Specifies the path and file names of files to be attached to the email message. You
can use this
parameter or pipe the paths and file names to Send-MailMessage .

Type: String[]

Aliases: PsPath

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False


-Bcc

Specifies the email addresses that receive a copy of the mail but are not listed as
recipients of
the message. Enter names (optional) and the email address, such as
Name <someone@fabrikam.com> .

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Body

Specifies the content of the email message.

Type: String

Position: 2

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-BodyAsHtml

Specifies that the value of the Body parameter contains HTML.

Type: SwitchParameter

Aliases: BAH

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Cc
Specifies the email addresses to which a carbon copy (CC) of the email message is
sent. Enter names
(optional) and the email address, such as Name
<someone@fabrikam.com> .

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Credential

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.

Credentials are stored in a PSCredential


object and the password is stored as a
SecureString.

7 Note

For more information about SecureString data protection, see


How secure is
SecureString?.

Type: PSCredential

Position: Named

Default value: Current user

Accept pipeline input: False

Accept wildcard characters: False

-DeliveryNotificationOption

Specifies the delivery notification options for the email message. You can specify
multiple values.
None is the default value. The alias for this parameter is DNO.

The delivery notifications are sent to the address in the From parameter.
The acceptable values for this parameter are as follows:

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.

These values are defined as a flag-based enumeration. You can combine multiple
values together to
set multiple flags using this parameter. The values can be passed
to the DeliveryNotification
parameter as an array of values or as a comma-
separated string of those values. The cmdlet will
combine the values using a binary-
OR operation. Passing values as an array is the simplest option
and also allows you
to use tab-completion on the values.

Type: DeliveryNotificationOptions

Aliases: DNO

Accepted values: None, OnSuccess, OnFailure, Delay, Never

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Encoding

Specifies the type of encoding for the target file. The default value is Default .

The acceptable values for this parameter are as follows:

ASCII Uses ASCII (7-bit) character set.

BigEndianUnicode Uses UTF-16 with the big-endian byte order.


Default Uses the encoding that corresponds to the system's active code page

(usually ANSI).
OEM Uses the encoding that corresponds to the system's current OEM code

page.
Unicode Uses UTF-16 with the little-endian byte order.
UTF7 Uses UTF-7.

UTF8 Uses UTF-8.


UTF32 Uses UTF-32 with the little-endian byte order.

Type: Encoding

Aliases: BE

Accepted values: ASCII, BigEndianUnicode, Default, OEM, Unicode, UTF7, UTF8,


UTF32

Position: Named

Default value: Default

Accept pipeline input: False

Accept wildcard characters: False

-From

The From parameter is required. This parameter specifies the sender's email address.
Enter a
name (optional) and email address, such as Name <someone@fabrikam.com> .

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Port

Specifies an alternate port on the SMTP server. The default value is 25, which is the
default SMTP
port.

Type: Int32

Position: Named

Default value: 25

Accept pipeline input: False

Accept wildcard characters: False

-Priority
Specifies the priority of the email message. Normal is the default. The acceptable
values for this
parameter are Normal, High, and Low.

Type: MailPriority

Accepted values: Normal, High, Low

Position: Named

Default value: Normal

Accept pipeline input: False

Accept wildcard characters: False

-SmtpServer

Specifies the name of the SMTP server that sends the email message.

The default value is the value of the $PSEmailServer preference variable. If the
preference
variable is not set and this parameter is not used, the Send-MailMessage
command fails.

Type: String

Aliases: ComputerName

Position: 3

Default value: $PSEmailServer

Accept pipeline input: False

Accept wildcard characters: False

-Subject

The Subject parameter is required. This parameter specifies the subject of the email
message.

Type: String

Aliases: sub

Position: 1

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-To

The To parameter is required. This parameter specifies the recipient's email address.
Enter
names (optional) and the email address, such as Name <someone@fabrikam.com> .

Type: String[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-UseSsl

The Secure Sockets Layer (SSL) protocol is used to establish a secure connection to
the remote
computer to send mail. By default, SSL is not used.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe the path and file names of attachments to this cmdlet.

Outputs
None

This cmdlet returns no output.


Related Links
about_Preference_Variables
Get-Credential
Set-Alias
Reference
Module: Microsoft.PowerShell.Utility

Creates or changes an alias for a cmdlet or other command in the current PowerShell
session.

Syntax
PowerShell

Set-Alias

[-Name] <string>

[-Value] <string>

[-Description <string>]

[-Option <ScopedItemOptions>]

[-PassThru]

[-Scope <string>]

[-Force]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Set-Alias cmdlet creates or changes an alias for a cmdlet or a command, such as a
function,
script, file, or other executable. An alias is an alternate name that refers to a
cmdlet or command.
For example, sal is the alias for the Set-Alias cmdlet. For more
information, see about_Aliases.

A cmdlet can have multiple aliases, but an alias can only be associated with one cmdlet.
You can use
Set-Alias to reassign an existing alias to another cmdlet, or change an
alias's properties, such
as the description.

An alias that is created or changed by Set-Alias is not permanent and is only available
during the
current PowerShell session. When the PowerShell session is closed, the alias is
removed.

Examples
Example 1: Create an alias for a cmdlet
This command creates an alias to a cmdlet in the current PowerShell session.

PowerShell

PS> Set-Alias -Name list -Value Get-ChildItem

PS> Get-Alias -Name list

CommandType Name

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

Alias list -> Get-ChildItem

The Set-Alias cmdlet creates an alias in the current PowerShell session. The Name
parameter
specifies the alias's name, list . The Value parameter specifies the cmdlet
that the alias
runs.

To run the alias, type list on the PowerShell command line.

Example 2: Reassign an existing alias to a different cmdlet


This command reassigns an existing alias to run a different cmdlet.

PowerShell

PS> Get-Alias -Name list

CommandType Name

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

Alias list -> Get-ChildItem

PS> Set-Alias -Name list -Value Get-Location

PS> Get-Alias -Name list

CommandType Name

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

Alias list -> Get-Location

The Get-Alias cmdlet uses the Name parameter to display the list alias. The list
alias is
associated with the Get-ChildItem cmdlet. When the list alias is run, the items
in the current
directory are displayed.

The Set-Alias cmdlet uses the Name parameter to specify the list alias. The Value
parameter associates the alias to the Get-Location cmdlet.
The Get-Alias cmdlet uses the Name parameter to display the list alias. The list
alias is
associated with the Get-Location cmdlet. When the list alias is run, the current
directory's
location is displayed.

Example 3: Create and change a read-only alias


This command creates a read-only alias. The read-only option prevents unintended
changes to an
alias. To change or delete a read-only alias, use the Force parameter.

PowerShell

PS> Set-Alias -Name loc -Value Get-Location -Option ReadOnly -PassThru |


Format-List -Property *

DisplayName : loc -> Get-Location

Definition : Get-Location

Options : ReadOnly

Description :

Name : loc

CommandType : Alias

PS> Set-Alias -Name loc -Value Get-Location -Option ReadOnly -Description


'Displays the current directory' -Force -PassThru | Format-List -Property *

DisplayName : loc -> Get-Location

Definition : Get-Location

Options : ReadOnly

Description : Displays the current directory

Name : loc

CommandType : Alias

The Set-Alias cmdlet creates an alias in the current PowerShell session. The Name
parameter
specifies the alias's name, loc . The Value parameter specifies the Get-
Location cmdlet that
the alias runs. The Option parameter specifies the ReadOnly value.
The PassThru
parameter represents the alias object and sends the object down the
pipeline to the Format-List
cmdlet. Format-List uses the Property parameter with an
asterisk ( * ) so that all of the
properties are displayed. The example output shows a
partial list of those properties.

The loc alias is changed with the addition of two parameters. Description adds text to
explain
the alias's purpose. The Force parameter is needed because the loc alias is
read-only. If the
Force parameter is not used, the change fails.

Example 4: Create an alias to an executable file


This example creates an alias to an executable file on the local computer.

PowerShell

PS> Set-Alias -Name np -Value C:\Windows\notepad.exe

PS> Get-Alias -Name np

CommandType Name

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

Alias np -> notepad.exe

The Set-Alias cmdlet creates an alias in the current PowerShell session. The Name
parameter
specifies the alias's name, np . The Value parameter specifies the path and
application name
C:\Windows\notepad.exe. The Get-Alias cmdlet uses the Name
parameter to show that the np
alias is associated with notepad.exe.

To run the alias, type np on the PowerShell command line to open notepad.exe.

Example 5: Create an alias for a command with


parameters
This example shows how to assign an alias to a command with parameters.

You can create an alias for a cmdlet, such as Set-Location . You cannot create an alias for
a
command with parameters and values, such as Set-Location -Path
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. For more information, see
about_Functions.

PowerShell

Function CD32 {Set-Location -Path C:\Windows\System32}

Set-Alias -Name Go -Value CD32

A function named CD32 is created. The function uses the Set-Location cmdlet with the
Path
parameter to specify the directory, C:\Windows\System32 .

The Set-Alias cmdlet creates an alias to the function in the current PowerShell session.
The
Name parameter specifies the alias's name, Go . The Value parameter specifies the
function's name, CD32 .
To run the alias, type Go on the PowerShell command line. The CD32 function runs and
changes to
the directory C:\Windows\System32 .

Example 6: Update options for an existing alias


This example shows how to assign multiple options using the Option parameter.

Using the example above we will set the alias Go as ReadOnly and Private .

PowerShell

Set-Alias -Name Go -Option ReadOnly, Private

The alias Go should already exist. After running the command above, the alias is not be
able to
be changed without using the Force parameter and is only available in the
current scope.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Description

Specifies a description of the alias. You can type any string. If the description includes
spaces,
enclose it single quotation marks.

Type: String

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-Force

Use the Force parameter to change or delete an alias that has the Option parameter
set to
ReadOnly.

The Force parameter cannot change or delete an alias with the Option parameter set
to
Constant.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Name

Specifies the name of a new alias. An alias name can contain alphanumeric
characters and hyphens. Alias names
cannot be numeric, such as 123.

Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Option

Sets the Option property value of the alias. Values such as ReadOnly and Constant
protect an alias from unintended changes. To see the Option property of all aliases in
the
session, type Get-Alias | Format-Table -Property Name, Options -Autosize .

The acceptable values for this parameter are as follows:

AllScope - The alias is copied to any new scopes that are created.
Constant - Cannot be changed or deleted.

None - Sets no options and is the default.


Private - The alias is available only in the current scope.

ReadOnly - Cannot be changed or deleted unless the Force parameter is used.


Unspecified

These values are defined as a flag-based enumeration. You can combine multiple
values together to
set multiple flags using this parameter. The values can be passed
to the Option parameter as an
array of values or as a comma-separated string of
those values. The cmdlet will combine the values
using a binary-OR operation.
Passing values as an array is the simplest option and also allows you
to use tab-
completion on the values.

Type: ScopedItemOptions

Accepted values: AllScope, Constant, None, Private, ReadOnly, Unspecified

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-PassThru

Returns an object that represents the alias. Use a format cmdlet such as Format-List
to display
the object. By default, Set-Alias does not generate any output.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Scope

Specifies the scope in which this alias is valid. The default value is Local. For more
information, see about_Scopes.

The acceptable values are as follows:


Global
Local
Private
Numbered scopes
Script

Type: String

Accepted values: Global, Local, Private, Numbered scopes, Script

Position: Named

Default value: Local

Accept pipeline input: False

Accept wildcard characters: False

-Value

Specifies the name of the cmdlet or command that the alias runs. The Value
parameter is the
alias's Definition property.

Type: String

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

AliasInfo

When you use the PassThru parameter, this cmdlet returns a AliasInfo object
representing
the alias.

Notes
Windows PowerShell includes the following aliases for Set-Alias :

sal

PowerShell includes built-in aliases that are available in each PowerShell session. The
Get-Alias
cmdlet displays the aliases available in a PowerShell session.

To create a new alias, use Set-Alias or New-Alias . To remove an alias use the Remove-
Item
cmdlet. For example, Remove-Item -Path Alias:aliasname .

To create an alias that is available in each PowerShell session, add it to your PowerShell
profile.
For more information, see about_Profiles.

An alias can be saved and reused in another PowerShell session by doing an export and
import. To
save an alias to a file, use Export-Alias . To add a saved alias to a new
PowerShell session, use
Import-Alias .

Related Links
about_Aliases
about_Functions
about_Profiles
about_Scopes
Export-Alias
Get-Alias
Import-Alias
New-Alias
Remove-Item
Set-Date
Reference
Module: Microsoft.PowerShell.Utility

Changes the system time on the computer to a time that you specify.

Syntax
PowerShell

Set-Date

[-Date] <DateTime>

[-DisplayHint <DisplayHintType>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Set-Date

[-Adjust] <TimeSpan>

[-DisplayHint <DisplayHintType>]

[-WhatIf]

[-Confirm]

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

Examples

Example 1: Add three days to the system date


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.

The Get-Date cmdlet returns the current date as a DateTime object. The DateTime
object's
AddDays method adds a specified number of days ( 3 ) to the current DateTime
object.

PowerShell

Set-Date -Date (Get-Date).AddDays(3)

Example 2: Set the system clock back 10 minutes


This example sets the current system time back by 10 minutes.

The Adjust parameter allows you to specify an interval of change (minus ten minutes) in
the
standard time format for the locale.

The DisplayHint parameter tells PowerShell to display only the time, but it does not
affect the DateTime object that Set-Date returns.

PowerShell

Set-Date -Adjust -0:10:0 -DisplayHint Time

Example 3: Set the date and time to a variable value


These commands change the system date and time on local 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.

PowerShell

$T = Get-Date

Set-Date -Date $T

Example 4: Add 90 minutes to the system clock


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

PowerShell

$90mins = New-TimeSpan -Minutes 90

Set-Date -Adjust $90mins

Parameters
-Adjust

Specifies the value for which this cmdlet adds or subtracts from the current date and
time.
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 .

Type: TimeSpan

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


-Date

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

Type: DateTime

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-DisplayHint

Specifies which elements of the date and time are displayed.The acceptable values
for this parameter
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.

Type: DisplayHintType

Accepted values: Date, Time, DateTime

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs.


The cmdlet is not run.
Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
DateTime

You can pipe a date to this cmdlet.

Outputs
DateTime

This cmdlet returns an object that represents the date that it set.

Notes
Use this cmdlet cautiously when 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 in the .NET SDK.

Related Links
Get-Date
New-TimeSpan
Set-PSBreakpoint
Reference
Module: Microsoft.PowerShell.Utility

Sets a breakpoint on a line, command, or variable.

Syntax
PowerShell

Set-PSBreakpoint

[-Action <ScriptBlock>]

[[-Column] <Int32>]

[-Line] <Int32[]>

[-Script] <String[]>

[<CommonParameters>]

PowerShell

Set-PSBreakpoint

[-Action <ScriptBlock>]

-Command <String[]>

[[-Script] <String[]>]

[<CommonParameters>]

PowerShell

Set-PSBreakpoint

[-Action <ScriptBlock>]

[[-Script] <String[]>]

-Variable <String[]>

[-Mode <VariableAccessMode>]

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


PowerShell scripts.
For more information about the PowerShell debugger, see
about_Debuggers.

Examples

Example 1: Set a breakpoint on a line


This example sets a breakpoint at line 5 in the Sample.ps1 script. When the script runs,
execution
stops immediately before line 5 would execute.

PowerShell

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

Example 2: Set a breakpoint on a function


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

PowerShell

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

The result is a command breakpoint object. Before the script runs, the value of the
HitCount
property is 0.

Example 3: Set a breakpoint on a variable


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

PowerShell

Set-PSBreakpoint -Script "sample.ps1" -Variable "Server" -Mode ReadWrite

Example 4: Set a breakpoint on every command that


begins with specified text
This example sets a breakpoint on every command in the Sample.ps1 script that begins
with "write",
such as Write-Host .

PowerShell
Set-PSBreakpoint -Script Sample.ps1 -Command "write*"

Example 5: Set a breakpoint depending on the value of a


variable
This example stops execution at the DiskTest function in the Test.ps1 script only when
the value
of the $Disk variable is greater than 2.

PowerShell

Set-PSBreakpoint -Script "test.ps1" -Command "DiskTest" -Action { if ($Disk


-gt 2) { break } }

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: Set a breakpoint on a function


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

PowerShell

PS> Set-PSBreakpoint -Command "checklog"

Id : 0

Command : checklog

Enabled : True

HitCount : 0

Action :

function CheckLog {

>> get-eventlog -log Application |

>> where {($_.source -like "TestApp") -and ($_.Message -like "*failed*")}

>>}

>>

PS> Checklog

DEBUG: Hit breakpoint(s)

DEBUG: Function breakpoint on 'prompt:Checklog'


Example 7: Set breakpoints on multiple lines
This example 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.

PowerShell

PS C:\> 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

Parameters
-Action

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.

Type: ScriptBlock

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Column

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

Type: Int32

Position: 2

Default value: 1

Accept pipeline input: False

Accept wildcard characters: False

-Command
Sets a command breakpoint. Enter cmdlet 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.

Type: String[]

Aliases: C

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Line

Sets a line breakpoint in a script. Enter one or more line numbers, separated by
commas. 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.

Type: Int32[]

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Mode

Specifies 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. The acceptable values for
this parameter 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.

Type: VariableAccessMode

Accepted values: Read, Write, ReadWrite

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Script

Specifies an array of script files that this cmdlet sets a breakpoint in. 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.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Variable

Specifies an array of variables that this cmdlet sets breakpoints on. Enter a comma-
separated list
of variables without dollar signs ( $ ).

Use the Mode parameter 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.

Type: String[]

Aliases: V

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
CommandBreakpoint

LineBreakpoint

VariableBreakpoint

Set-PSBreakpoint returns an object that represents each breakpoint that it sets.

Notes
Windows PowerShell includes the following aliases for Set-PSBreakpoint :

sbp

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.
Related Links
Disable-PSBreakpoint
Enable-PSBreakpoint
Get-PSBreakpoint
Get-PSCallStack
Remove-PSBreakpoint
Set-TraceSource
Reference
Module: Microsoft.PowerShell.Utility

Configures, starts, and stops a trace of PowerShell components.

Syntax
PowerShell

Set-TraceSource

[-Name] <String[]>

[[-Option] <PSTraceSourceOptions>]

[-ListenerOption <TraceOptions>]

[-FilePath <String>]

[-Force]

[-Debugger]

[-PSHost]

[-PassThru]

[<CommonParameters>]

PowerShell

Set-TraceSource

[-Name] <String[]>

[-RemoveListener <String[]>]

[<CommonParameters>]

PowerShell

Set-TraceSource

[-Name] <String[]>

[-RemoveFileListener <String[]>]

[<CommonParameters>]

Description
The Set-TraceSource cmdlet configures, starts, and stops a trace of a PowerShell
component. You
can use it to specify which components will be traced and where the
tracing output is sent.
Examples

Example 1: Trace the ParameterBinding component


PowerShell

Set-TraceSource -Name "ParameterBinding" -Option ExecutionFlow -PSHost -


ListenerOption "ProcessId,TimeStamp"

This command starts tracing for the ParameterBinding component of 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 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: Stop a trace


PowerShell

Set-TraceSource -Name "ParameterBinding" -RemoveListener "Host"

This command stops the trace of the ParameterBinding component of PowerShell. It


uses the
Name parameter to identify the component that was being traced and the
RemoveListener
parameter to identify the trace listener.

Parameters
-Debugger

Indicates that the cmdlet 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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-FilePath

Specifies a file that this cmdlet sends the trace output to. 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.

Type: String

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Force

Indicates that the cmdlet overwrites a read-only file. Use with the FilePath
parameter.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ListenerOption

Specifies optional data to the prefix of each trace message in the output. The
acceptable values for
this parameter are:

None
LogicalOperationStack

DateTime
Timestamp

ProcessId

ThreadId
Callstack
None is the default.

These values are defined as a flag-based enumeration. You can combine multiple
values together to
set multiple flags using this parameter. The values can be passed
to the ListenerOption
parameter as an array of values or as a comma-separated
string of those values. The cmdlet will
combine the values using a binary-OR
operation. Passing values as an array is the simplest option
and also allows you to
use tab-completion on the values.

Type: TraceOptions

Accepted values: None, LogicalOperationStack, DateTime, Timestamp,


ProcessId, ThreadId, Callstack

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Name

Specifies which components are traced. Enter the name of the trace source of each
component.
Wildcards are permitted.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: True

-Option

Specifies the type of events that are traced. The acceptable values for this parameter
are:

None

Constructor
Dispose

Finalizer
Method

Property
Delegates

Events
Exception

Lock

Error
Errors

Warning
Verbose

WriteLine

Data
Scope

ExecutionFlow
Assert

All

All is the default.

The following values are combinations of other values:

ExecutionFlow : Constructor , Dispose , Finalizer , Method , Delegates , Events ,


Scope

Data : Constructor , Dispose , Finalizer , Property , Verbose , WriteLine


Errors : Error , Exception

These values are defined as a flag-based enumeration. You can combine multiple
values together to
set multiple flags using this parameter. The values can be passed
to the Option parameter as an
array of values or as a comma-separated string of
those values. The cmdlet will combine the values
using a binary-OR operation.
Passing values as an array is the simplest option and also allows you
to use tab-
completion on the values.

Type: PSTraceSourceOptions

Accepted values: None, Constructor, Dispose, Finalizer, Method, Property,


Delegates, Events, Exception, Lock, Error, Errors, Warning,
Verbose, WriteLine, Data, Scope, ExecutionFlow, Assert, All

Position: 1

Default value: None


Accept pipeline input: True

Accept wildcard characters: False

-PassThru

Returns an object representing the item with which you are working. By default, this
cmdlet does not
generate any output.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-PSHost

Indicates that this cmdlet sends the trace output to the PowerShell host. This
parameter also
selects the PSHost trace listener.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RemoveFileListener

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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-RemoveListener

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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a string that contains a name to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

PSTraceSource

When you use the PassThru parameter, this cmdlet returns a PSTraceSource object
representing the trace session.

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 PowerShell tracing cmdlets are designed to help PowerShell developers, but
they are available
to all users. They let you monitor nearly every aspect of the
functionality of PowerShell.

A trace source is the part of each 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 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
ListenerOption 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. 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 .

Related Links
Get-TraceSource
Trace-Command
Set-Variable
Reference
Module: Microsoft.PowerShell.Utility

Sets the value of a variable. Creates the variable if one with the requested name does
not exist.

Syntax
PowerShell

Set-Variable

[-Name] <String[]>

[[-Value] <Object>]

[-Include <String[]>]

[-Exclude <String[]>]

[-Description <String>]

[-Option <ScopedItemOptions>]

[-Force]

[-Visibility <SessionStateEntryVisibility>]

[-PassThru]

[-Scope <String>]

[-WhatIf]

[-Confirm]

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

Examples

Example 1: Set a variable and get its value


These commands set the value of the $desc variable to A description , and then gets
the value of
the variable.

PowerShell

Set-Variable -Name "desc" -Value "A description"

Get-Variable -Name "desc"

Name Value

---- -----

desc A description

Example 2: Set a global, read-only variable


This example creates a global, read-only variable that contains all processes on the
system, and
then it displays all properties of the variable.

PowerShell

Set-Variable -Name "processes" -Value (Get-Process) -Option constant -Scope


global -Description "All processes" -PassThru |

Format-List -Property *

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: Understand public vs. private variables


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

PowerShell

New-Variable -Name "counter" -Visibility Public -Value 26

$Counter

26

Get-Variable c*

Name Value

---- -----

Culture en-US

ConsoleFileName

ConfirmPreference High

CommandLineParameters {}

Counter 26

Set-Variable -Name "counter" -Visibility Private

Get-Variable c*

Name Value

---- -----

Culture en-US

ConsoleFileName

ConfirmPreference High

CommandLineParameters {}

$counter

"Cannot access the variable '$counter' because it is a private variable"

.\use-counter.ps1

#Commands completed successfully.

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.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Description

Specifies the description of the variable.

Type: String
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Exclude

Specifies an array of items that this cmdlet excludes from the operation. The value of
this
parameter qualifies the Path parameter. Enter a path element or pattern, such as
*.txt .
Wildcards are permitted.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

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

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Include

Specifies an array of items that this cmdlet includes in the operation. The value of
this parameter
qualifies the Name parameter. Enter a name or name pattern, such as
c* . Wildcards are
permitted.
Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Name

Specifies the variable name.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Option

Specifies the value of the Options property of the variable.

Valid values are:

None : Sets no options. ( None is the default.)

ReadOnly : Can be deleted. Cannot be changed, except by using the Force

parameter.
Constant : Cannot be deleted or changed. Constant is valid only when you are

creating a
variable. You cannot change the options of an existing variable to
Constant .

Private : The variable is available only in the current scope.

AllScope : The variable is copied to any new scopes that are created.

These values are defined as a flag-based enumeration. You can combine multiple
values together to
set multiple flags using this parameter. The values can be passed
to the Option parameter as an
array of values or as a comma-separated string of
those values. The cmdlet will combine the values
using a binary-OR operation.
Passing values as an array is the simplest option and also allows you
to use tab-
completion on the values.
Type: ScopedItemOptions

Accepted values: None, ReadOnly, Constant, Private, AllScope, Unspecified

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.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Scope

Specifies the scope of the variable.The acceptable values for this parameter are:

Global

Local
Script

Private

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.

Type: String

Position: Named

Default value: Local


Accept pipeline input: False

Accept wildcard characters: False

-Value

Specifies the value of the variable.

Type: Object

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Visibility

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.

Type: SessionStateEntryVisibility

Accepted values: Public, Private

Position: Named

Default value: Public

Accept pipeline input: False

Accept wildcard characters: False


-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
Object

You can pipe an object representing the value of the variable to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

PSVariable

When you use the PassThru parameter, this cmdlet returns a PSVariable object
representing
the new or changed variable.

Notes
Windows PowerShell includes the following aliases for Set-Variable :

set
sv

Related Links
Clear-Variable
Get-Variable
New-Variable
Remove-Variable
Show-Command
Reference
Module: Microsoft.PowerShell.Utility

Displays PowerShell command information in a graphical window.

Syntax
PowerShell

Show-Command

[[-Name] <String>]

[-Height <Double>]

[-Width <Double>]

[-NoCommonParameter]

[-ErrorPopup]

[-PassThru]

[<CommonParameters>]

Description
The Show-Command cmdlet lets you create a PowerShell command in a command window.
You can use the
features of the command window to run the command or have it return
the command to you.

Show-Command is a very useful teaching and learning tool. Show-Command works on all
command
types, including cmdlets, functions, workflows and CIM commands.

Without parameters, Show-Command displays a command window that lists all available
commands in
all installed modules. To find the commands in a module, select the
module from the Modules
drop-down list. To select a command, click the command
name.

To use the command window, select a command, either by using the Name or by
clicking the command
name in the Commands list. Each parameter set is displayed on a
separate tab. Asterisks indicate
the mandatory parameters. To enter values for a
parameter, type the value in the text box or select
the value from the drop-down box. To
add a switch parameter, click to select the parameter check
box.

When you're ready, you can click Copy to copy the command that you've created to the
clipboard
or click Run to run the command. You can also use the PassThru parameter to
return the
command to the host program, such as the PowerShell console. To cancel the
command selection and
return to the view that displays all commands, press Ctrl and
click the selected command.

In the PowerShell Integrated Scripting Environment (ISE), a variation of the Show-Command


window
is displayed by default. For information about using this command window, see
the PowerShell ISE
Help topics.

This cmdlet was introduced in PowerShell 3.0.

Because this cmdlet requires a user interface, it does not work on Windows Server Core
or Windows
Nano Server. This cmdlet is only available on Windows systems that support
the Windows Desktop.

Examples

Example 1: Open the Commands window


This example displays the default view of the Show-Command window. The Commands
window
displays a list of all commands in all modules that are installed on the
computer.

PowerShell

Show-Command

Example 2: Open a cmdlet in the Commands window


This example display the Invoke-Command cmdlet in the Command window. You can use
this display
to run Invoke-Command commands.

PowerShell

Show-Command -Name "Invoke-Command"

Example 3: Open a cmdlet with specified parameters


This command opens a Show-Command window for the Connect-PSSession cmdlet.

PowerShell
Show-Command -Name "Connect-PSSession" -Height 700 -Width 1000 -ErrorPopup

The Height and Width parameters specify the dimension of the command window. The
ErrorPopup parameter displays the error command window.

When you click Run, the Connect-PSSession command runs, just as would if you typed
the
Connect-PSSession command at the command line.

Example 4: Specify new default parameter values for a


cmdlet
This example uses the $PSDefaultParameterValues automatic variable to set new default
values for
the Height, Width, and ErrorPopup parameters of the Show-Command cmdlet.

PowerShell

$PSDefaultParameterValues = @{

"Show-Command:Height" = 700

"Show-Command:Width" = 1000

"Show-Command:ErrorPopup" = $True

Now when you run a Show-Command command, the new defaults are applied
automatically. To use these
default values in every PowerShell session, add the
$PSDefaultParameterValues variable to your
PowerShell profile. For more information,

see about_Profiles
and about_Parameters_Default_Values.

Example 5: Send output to a grid view


This command shows how to use the Show-Command and Out-GridView cmdlets together.

PowerShell

Show-Command Get-ChildItem | Out-GridView

The command uses the Show-Command cmdlet to open a command window for the Get-
ChildItem cmdlet.
When you click the Run button, the Get-ChildItem command runs
and generates output. The
pipeline operator ( | ) sends the output of the Get-ChildItem
command to the Out-GridView
cmdlet, which displays the Get-ChildItem output in an
interactive window.
Example 6: Display a command that you create in the
Commands window
This example shows the command that you created in the Show-Command window. The
command uses the
PassThru parameter, which returns the Show-Command results in a
string.

PowerShell

Show-Command -PassThru

Get-EventLog -LogName "Windows PowerShell" -Newest 5

For example, if you use the Show-Command window to create a Get-EventLog command
that gets the
five newest events in the Windows PowerShell event log, and then click OK,
the command returns
the output shown above. Viewing the command string helps you
learn PowerShell.

Example 7: Save a command to a variable


This example shows how to run the command string that you get when you use the
PassThru
parameter of the Show-Command cmdlet. This strategy lets you see the
command and use it.

PowerShell

$C = Show-Command -PassThru

$C

Invoke-Expression $C

Get-EventLog -LogName "PowerShell" -Newest 5

Index Time EntryType Source InstanceID Message

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

11520 Dec 16 16:37 Information Windows PowerShell 400 Engine


state is changed from None to Available...

11519 Dec 16 16:37 Information Windows PowerShell 600 Provider


"Variable" is Started. ...

11518 Dec 16 16:37 Information Windows PowerShell 600 Provider


"Registry" is Started. ...

11517 Dec 16 16:37 Information Windows PowerShell 600 Provider


"Function" is Started. ...

11516 Dec 16 16:37 Information Windows PowerShell 600 Provider


"FileSystem" is Started. ...
The first command uses the PassThru parameter of the Show-Command cmdlet and saves
the results
of the command in the $C variable. In this case, we use the Show-Command
window to create a
Get-EventLog command that gets the five newest events in the
Windows PowerShell event log. When
you click OK, Show-Command returns the command
string, which is saved in the $C variable.

Example 8: Save the output of a command to a variable


This example uses the ErrorPopup parameter to save the output of a command in a
variable.

PowerShell

$P = Show-Command Get-Process -ErrorPopup

$P

Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName

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

473 33 94096 112532 709 2.06 4492 powershell

In addition to displaying errors in a window, ErrorPopup returns command output to


the current
command, instead of creating a new command. When you run this
command, the Show-Command window
opens. You can use the window features to set
parameter values. To run the command, click the
Run button in the Show-Command
window.

Parameters
-ErrorPopup

Indicates that the cmdlet displays errors in a pop-up window, in addition to


displaying them at the
command line. By default, when a command that is run in a
Show-Command window generates an error,
the error is displayed only at the command

line.

Also, when you run the command (by using the Run button in the Show-Command
window), the
ErrorPopup parameter returns the command results to the current
command, instead of running the
command and returning its output to a new
command. You can use this feature to save the command
results in a variable.

Type: SwitchParameter
Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Height

Specifies the height of the Show-Command window in pixels. Enter a value between 300
and the
number of pixels in the screen resolution. If the value is too large to display
the command window
on the screen, Show-Command generates an error. The default
height is 600 pixels. For a
Show-Command command that includes the Name
parameter, the default height is 300 pixels.

Type: Double

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Name

Displays a command window for the specified command. Enter the name of one
command, such as the name
of a cmdlet, function, or CIM command. If you omit this
parameter, Show-Command displays a command
window that lists all of the PowerShell
commands in all modules installed on the computer.

Type: String

Aliases: CommandName

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-NoCommonParameter
Indicates that this cmdlet omits the Common Parameters section of the command
display. By default,
the Common Parameters appear in an expandable section at the
bottom of the command window.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-PassThru

Returns an object representing the item with which you are working. By default, this
cmdlet does not
generate any output. To run the command string, copy and paste it
at the command prompt or save it
in a variable and use the Invoke-Expression
cmdlet to run the string in the variable.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Width

Specifies the width of the Show-Command window in pixels. Enter a value between 300
and the number
of pixels in the screen resolution. If the value is too large to display
the command window on the
screen, Show-Command generates an error. The default
width is 300 pixels.

Type: Double

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

String

When you use the PassThru parameter, this cmdlet returns a command string.

Object

When you use the ErrorPopup parameter, this cmdlet returns the command output (any
object).

Notes
Windows PowerShell includes the following aliases for Show-Command :

shcm

Show-Command does not work in remote sessions.


Sort-Object
Reference
Module: Microsoft.PowerShell.Utility

Sorts objects by property values.

Syntax
PowerShell

Sort-Object

[[-Property] <Object[]>]

[-Descending]

[-Unique]

[-InputObject <psobject>]

[-Culture <string>]

[-CaseSensitive]

[<CommonParameters>]

Description
The Sort-Object cmdlet sorts objects in ascending or descending order based on object
property
values. If sort properties aren't included in a command, PowerShell uses default
sort properties of
the first input object. If the input object's type has no default sort
properties, PowerShell
attempts to compare the objects themselves. For more
information, see the Notes section.

You can sort objects by a single property or multiple properties. Multiple properties use
hash
tables to sort in ascending order, descending order, or a combination of sort
orders. Properties are
sorted as case-sensitive or case-insensitive. Use the Unique
parameter to remove duplicates
from the output.

Examples

Example 1: Sort the current directory by name


This example sorts the files and subdirectories in a directory.

PowerShell
Get-ChildItem -Path C:\Test | Sort-Object

Directory: C:\Test

Mode LastWriteTime Length Name

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

-a---- 2/13/2019 08:55 26 anotherfile.txt

-a---- 2/13/2019 13:26 20 Bfile.txt

-a---- 2/12/2019 15:40 118014 Command.txt

-a---- 2/1/2019 08:43 183 CreateTestFile.ps1

d----- 2/25/2019 18:25 Files

d----- 2/25/2019 18:24 Logs

-ar--- 2/12/2019 14:31 27 ReadOnlyFile.txt

-a---- 2/12/2019 16:24 23 Zsystemlog.log

The Get-ChildItem cmdlet gets the files and subdirectories from the directory specified
by the
Path parameter, C:\Test . The objects are sent down the pipeline to the Sort-
Object cmdlet.
Sort-Object doesn't specify a property so the output is sorted by the

default sort property,


Name.

Example 2: Sort the current directory by file length


This command displays the files in the current directory by length in ascending order.

PowerShell

Get-ChildItem -Path C:\Test -File | Sort-Object -Property Length

Directory: C:\Test

Mode LastWriteTime Length Name

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

-a---- 2/13/2019 13:26 20 Bfile.txt

-a---- 2/12/2019 16:24 23 Zsystemlog.log

-a---- 2/13/2019 08:55 26 anotherfile.txt

-ar--- 2/12/2019 14:31 27 ReadOnlyFile.txt

-a---- 2/1/2019 08:43 183 CreateTestFile.ps1

-a---- 2/12/2019 15:40 118014 Command.txt

The Get-ChildItem cmdlet gets the files from the directory specified by the Path
parameter.
The File parameter specifies that Get-ChildItem only gets file objects. The
objects are sent
down the pipeline to the Sort-Object cmdlet. Sort-Object uses the
Length parameter to sort
the files by length in ascending order.

Example 3: Sort processes by memory usage


This example displays processes with the highest memory usage based on their working
set (WS) size.

PowerShell

Get-Process | Sort-Object -Property WS | Select-Object -Last 5

NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName

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

136 193.92 217.11 889.16 87492 8 OUTLOOK

112 347.73 297.02 95.19 106908 8 Teams

206 266.54 323.71 37.17 60620 8 MicrosoftEdgeCP

35 552.19 549.94 131.66 6552 8 Code

0 1.43 595.12 0.00 2780 0 Memory Compression

The Get-Process cmdlet gets the list of processes running on the computer. The process
objects are
sent down the pipeline to the Sort-Object cmdlet. Sort-Object uses the
Property parameter to
sort the objects by WS. The objects are sent down the pipeline to
the Select-Object cmdlet.
Select-Object uses the Last parameter to specify the last five
objects, which are the objects
with the highest WS usage.

Example 4: Sort HistoryInfo objects by Id


This command sorts the PowerShell session's HistoryInfo objects using the Id property.
Each
PowerShell session has its own command history.

PowerShell

Get-History | Sort-Object -Property Id -Descending

Id CommandLine

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

10 Get-Command Sort-Object -Syntax

9 $PSVersionTable

8 Get-Command Sort-Object -Syntax

7 Get-Command Sort-Object -ShowCommandInfo

6 Get-ChildItem -Path C:\Test | Sort-Object -Property Length

5 Get-Help Clear-History -online

4 Get-Help Clear-History -full

3 Get-ChildItem | Get-Member

2 Get-Command Sort-Object -Syntax

1 Set-Location C:\Test\

The Get-History cmdlet gets the history objects from the current PowerShell session.
The objects
are sent down the pipeline to the Sort-Object cmdlet. Sort-Object uses the
Property
parameter to sort the objects by Id. The Descending parameter sorts the
command history from
newest to oldest.

Example 5: Use a hash table to sort properties in


ascending and descending order
This example uses two properties to sort the objects, Status and DisplayName. Status is
sorted in descending order and DisplayName is sorted in ascending order.

A hash table is used to specify the Property parameter's value. The hash table uses an
expression to specify the property names and sort orders. For more information about
hash tables,
see about_Hash_Tables.

The Status property used in the hash table is an enumerated property. For more
information, see
ServiceControllerStatus.

PowerShell

Get-Service |

Sort-Object -Property @{Expression = "Status"; Descending = $true},

@{Expression = "DisplayName"; Descending = $false}

Status Name DisplayName

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

Running Appinfo Application Information

Running BthAvctpSvc AVCTP service

Running BrokerInfrastru... Background Tasks Infrastructure Ser...

Running BDESVC BitLocker Drive Encryption Service

Running CoreMessagingRe... CoreMessaging

Running VaultSvc Credential Manager

Running DsSvc Data Sharing Service

Running Dhcp DHCP Client

...

Stopped ALG Application Layer Gateway Service

Stopped AppMgmt Application Management

Stopped BITS Background Intelligent Transfer Ser...

Stopped wbengine Block Level Backup Engine Service

Stopped BluetoothUserSe... Bluetooth User Support Service_14fb...

Stopped COMSysApp COM+ System Application

Stopped smstsmgr ConfigMgr Task Sequence Agent

Stopped DeviceInstall Device Install Service

Stopped MSDTC Distributed Transaction Coordinator

The Get-Service cmdlet gets the list of services on the computer. The service objects
are sent
down the pipeline to the Sort-Object cmdlet. Sort-Object uses the Property
parameter with a
hash table to specify the property names and sort orders. The
Property parameter is sorted by
two properties, Status in descending order and
DisplayName in ascending order.

Status is an enumerated property. Stopped has a value of 1 and Running has a value
of
4. The Descending parameter is set to $True so that Running processes are displayed
before Stopped processes. DisplayName sets the Descending parameter to $False to
sort
the display names in alphabetical order.

Example 6: Sort text files by time span


This command sorts text files in descending order by the time span between
CreationTime and
LastWriteTime.

PowerShell

Get-ChildItem -Path C:\Test\*.txt |

Sort-Object -Property {$_.CreationTime - $_.LastWriteTime} |

Format-Table CreationTime, LastWriteTime, FullName

CreationTime LastWriteTime FullName

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

11/21/2018 12:39:01 2/26/2019 08:59:36 C:\Test\test2.txt

12/4/2018 08:29:41 2/26/2019 08:57:05 C:\Test\powershell_list.txt

2/20/2019 08:15:59 2/26/2019 12:09:43 C:\Test\CreateTestFile.txt

2/20/2019 08:15:59 2/26/2019 12:07:41 C:\Test\Command.txt

2/20/2019 08:15:59 2/26/2019 08:57:52 C:\Test\ReadOnlyFile.txt

11/29/2018 15:16:50 12/4/2018 16:16:24 C:\Test\LogData.txt

2/25/2019 18:25:11 2/26/2019 12:08:47 C:\Test\Zsystemlog.txt

2/25/2019 18:25:11 2/26/2019 08:55:33 C:\Test\Bfile.txt

2/26/2019 08:46:59 2/26/2019 12:12:19 C:\Test\LogFile3.txt

The Get-ChildItem cmdlet uses the Path parameter to specify the directory C:\Test and
all
of the *.txt files. The objects are sent down the pipeline to the Sort-Object cmdlet.
Sort-Object uses the Property parameter with a scriptblock to determine each files time
span
between CreationTime and LastWriteTime.

Example 7: Sort names in a text file


This example shows how to sort a list from a text file. The original file is displayed as an
unsorted list. Sort-Object sorts the contents and then sorts the contents with the
Unique
parameter that removes duplicates.

PowerShell
# All items unsorted

Get-Content -Path C:\Test\ServerNames.txt

localhost

server01

server25

LOCALHOST

Server19

server3

localhost

# All items sorted

Get-Content -Path C:\Test\ServerNames.txt | Sort-Object

localhost

LOCALHOST

localhost

server01

Server19

server25

server3

# Unique filtered items sorted

Get-Content -Path C:\Test\ServerNames.txt | Sort-Object -Unique

localhost

server01

Server19

server25

server3

The Get-Content cmdlet uses the Path parameter to specify the directory and filename.
The
file ServerNames.txt contains an unsorted list of computer names.

The Get-Content cmdlet uses the Path parameter to specify the directory and filename.
The
file ServerNames.txt contains an unsorted list of computer names. The objects are
sent down the
pipeline to the Sort-Object cmdlet. Sort-Object sorts the list in the
default order, ascending.

The Get-Content cmdlet uses the Path parameter to specify the directory and filename.
The
file ServerNames.txt contains an unsorted list of computer names. The objects are
sent down the
pipeline to the Sort-Object cmdlet. Sort-Object uses the Unique
parameter to remove
duplicate computer names. The list is sorted in the default order,
ascending.

Example 8: Sort a string as an integer


This example shows how to sort a text file that contains string objects as integers. You
can send
each command down the pipeline to Get-Member and verify that the objects
are strings instead of
integers. For these examples, the ProductId.txt file contains an
unsorted list of product numbers.

In the first example, Get-Content gets the contents of the file and pipes lines to the
Sort-Object cmdlet. Sort-Object sorts the string objects in ascending order.

PowerShell

# String sorted

Get-Content -Path C:\Test\ProductId.txt | Sort-Object

12345

1500

2800

3500

4100

500

6200

77

88

99999

# Integer sorted

Get-Content -Path C:\Test\ProductId.txt | Sort-Object {[int]$_}

77

88

500

1500

2800

3500

4100

6200

12345

99999

In the second example, Get-Content gets the contents of the file and pipes lines to the
Sort-Object cmdlet. Sort-Object uses a script block to convert the strings to integers.
In the
sample code, [int] converts the string to an integer and $_ represents each
string as it comes
down the pipeline. The integer objects are sent down the pipeline to
the Sort-Object cmdlet.
Sort-Object sorts the integer objects in numeric order.
Example 9: Sort by multiple properties
If you want to sort by multiple properties, separate the properties by commas.

PowerShell

Get-ChildItem -Path C:\Test | Sort-Object Length,Name

Directory: C:\Test

Mode LastWriteTime Length Name

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

-a--- 13/10/2021 22:16 2 File01.txt

-a--- 13/10/2021 22:16 2 File03.txt

-a--- 13/10/2021 22:18 64 File02.txt

-a--- 13/10/2021 22:18 64 File04.txt

The Get-ChildItem cmdlet gets the files from the directory specified by the Path
parameter.
The objects are sent down the pipeline to the Sort-Object cmdlet. Sort-
Object uses the
Length and Name parameter to sort the files by length in ascending
order. Since
File01.txt and File03.txt have the same length, they're further sorted by
their property
Name.

Example 10: Sort hashtables by their key values with


calculated properties
This example shows how you can sort hashtable objects by the value of their keys. You
can
specify one or more scriptblocks for the Property parameter. The expressions in
these
scriptblocks are used to determine the sorting order for the input like the values
for named
properties.

PowerShell

@(

@{ name = 'a' ; weight = 7 }

@{ name = 'b' ; weight = 1 }

@{ name = 'c' ; weight = 3 }

@{ name = 'd' ; weight = 7 }

) | Sort-Object -Property { $_.weight }, { $_.name } -OutVariable Sorted

$Sorted | ForEach-Object -Process { "{0}: {1}" -f $_.name, $_.weight }

The { $_.weight } and { $_.name } expressions sort the input hashtables first by the
value of
their weight key and then by the value of their name key. The Sort-Object
command uses the
OutVariable parameter to store the result to a variable and display
the result in the same call.

The last command iterates over the sorted hashtables to display their name and weight
as a string.

Parameters
-CaseSensitive

Indicates that the sort is case-sensitive. By default, sorts aren't case-sensitive.

Type: SwitchParameter

Position: Named

Default value: Case-insensitive

Accept pipeline input: False

Accept wildcard characters: False

-Culture

Specifies the cultural configuration to use for sorts. Use Get-Culture to display the
system's
culture configuration.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Descending

Indicates that Sort-Object sorts the objects in descending order. The default is
ascending order.

To sort multiple properties with different sort orders, use a hash table. For example,
with a hash
table you can sort one property in ascending order and another property
in descending order.
Type: SwitchParameter

Position: Named

Default value: Ascending

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

To sort objects, send them down the pipeline to Sort-Object . If you use the
InputObject
parameter to submit a collection of items, Sort-Object receives one
object that represents the
collection. Because one object can't be sorted, Sort-
Object returns the entire collection
unchanged.

Type: PSObject

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Property

Specifies the property names that Sort-Object uses to sort the objects. Wildcards
are permitted.
Objects are sorted based on the property values. If you don't specify a
property, Sort-Object
sorts based on default properties for the object type or the
objects themselves.

Use commas to separate multiple properties. Multiple properties can be sorted in


ascending order,
descending order, or a combination of sort orders. When you
specify multiple properties, the
objects are sorted by the first property. If multiple
objects have 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.

The Property parameter's value can be a calculated property. To create a calculated


property,
use a scriptblock or a hashtable.

Valid keys for a hash table are as follows:


expression - <string> or <script block>

ascending or descending - <boolean>

For more information, see


about_Calculated_Properties.

Type: Object[]

Position: 0

Default value: Default properties

Accept pipeline input: False

Accept wildcard characters: True

-Unique

Indicates that Sort-Object eliminates duplicates and returns only the unique
members of the
collection. The first instance of a unique value is included in the
sorted output.

Unique is case-insensitive. Strings that only differ by character case are considered
the same.
For example, character and CHARACTER.

Type: SwitchParameter

Position: Named

Default value: All

Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSObject

You can pipe the objects to be sorted to this cmdlet.

Outputs
PSObject

This cmdlet returns the sorted objects.


Notes
Windows PowerShell includes the following aliases for Sort-Object :

sort

The Sort-Object cmdlet sorts objects based on properties specified in the command or
the default
sort properties for the object type. Default sort properties are defined using
the PropertySet
named DefaultKeyPropertySet in a types.ps1xml file. For more
information, see
about_Types.ps1xml.

If an object doesn't have one of the specified properties, the property value for that
object is
interpreted by Sort-Object as Null and placed at the end of the sort order.

When no sort properties are available, PowerShell attempts to compare the objects
themselves.
Sort-Object uses the Compare method for each property. If a property
doesn't implement
IComparable, the cmdlet converts the property value to a string and
uses the Compare method
for System.String. For more information, see
PSObject.CompareTo(Object) Method.

If you sort on an enumerated property such as Status, Sort-Object sorts by the


enumeration
values. For Windows services, Stopped has a value of 1 and Running has a
value of 4.
Stopped is sorted before Running because of the enumerated values. For
more information,
see ServiceControllerStatus.

Related Links
about_Calculated_Properties
about_Hash_Tables
about_Types.ps1xml
Compare-Object
ForEach-Object
Group-Object
Measure-Object
New-Object
Select-Object
Tee-Object
Start-Sleep
Reference
Module: Microsoft.PowerShell.Utility

Suspends the activity in a script or session for the specified period of time.

Syntax
PowerShell

Start-Sleep

[-Seconds] <Int32>

[<CommonParameters>]

PowerShell

Start-Sleep

-Milliseconds <Int32>

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

Examples

Example 1: Pause execution for 1.5 seconds


In this example, the execution of commands pauses for one and one-half seconds.

PowerShell

Start-Sleep -Seconds 1.5

Example 2: Pause execution at the command line


This example shows that execution is paused for 5 seconds when run from the
command line.

PowerShell

PS> Get-Date; Start-Sleep -Seconds 5; Get-Date

Friday, May 13, 2022 9:38:15 AM

Friday, May 13, 2022 9:38:20 AM

PowerShell cannot execute the second Get-Date command until the sleep timer expires.

Parameters
-Milliseconds

Specifies how long the resource sleeps in milliseconds. The parameter can be
abbreviated as m.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Seconds

Specifies how long the resource sleeps in seconds. You can omit the parameter name
or you can
abbreviate it as s.

Type: Int32

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

Inputs
Int32

You can pipe the number of seconds to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
Windows PowerShell includes the following aliases for Start-Sleep :

sleep

Ctrl+C breaks out of Start-Sleep .

Ctrl+C does not break out of [Threading.Thread]::Sleep . For more information,

see
Thread.Sleep Method.
Tee-Object
Reference
Module: Microsoft.PowerShell.Utility

Saves command output in a file or variable and also sends it down the pipeline.

Syntax
PowerShell

Tee-Object

[-InputObject <PSObject>]

[-FilePath] <String>

[-Append]

[<CommonParameters>]

PowerShell

Tee-Object

[-InputObject <PSObject>]

-LiteralPath <String>

[<CommonParameters>]

PowerShell

Tee-Object

[-InputObject <PSObject>]

-Variable <String>

[<CommonParameters>]

Description
The Tee-Object cmdlet redirects output, that is, it 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
at the prompt.

Examples

Example 1: Output processes to a file and to the console


This example 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 processes are also displayed in the
console.

PowerShell

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

...

Example 2: Output processes to a variable and `Select-


Object`
This example gets a list of the processes running on the computer, saves them to the
$proc
variable, and pipes them to Select-Object .

PowerShell

Get-Process notepad | Tee-Object -Variable proc | Select-Object


processname,handles

ProcessName Handles

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

notepad 43

notepad 37

notepad 38

notepad 38

The Select-Object cmdlet selects the ProcessName and Handles properties. Note that
the
$proc variable includes the default information returned by Get-Process .

Example 3: Output system files to two log files


This example saves a list of system files in a two log files, a cumulative file and a current
file.

PowerShell
Get-ChildItem -Path D: -File -System -Recurse |

Tee-Object -FilePath "c:\test\AllSystemFiles.txt" -Append |

Out-File c:\test\NewSystemFiles.txt

The command uses the Get-ChildItem cmdlet to do a recursive search for system files
on the D:
drive. A pipeline operator ( | ) sends the list to Tee-Object , which appends the
list to the
AllSystemFiles.txt file and passes the list down the pipeline to the Out-File
cmdlet, which saves
the list in the NewSystemFiles.txt file .

Parameters
-Append

Indicates that the cmdlet appends the output to the specified file. Without this
parameter, the new
content replaces any existing content in the file without warning.

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-FilePath

Specifies a file that this cmdlet saves the object to Wildcard characters are permitted,
but must
resolve to a single file.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-InputObject
Specifies the object to be saved and displayed. Enter a variable that contains the
objects or type a
command or expression that gets the objects. You can also pipe an
object to Tee-Object .

When you use the InputObject parameter with Tee-Object , instead of piping
command results to
Tee-Object , the InputObject value is treated as a single object
even if the value is a
collection.

Type: PSObject

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-LiteralPath

Specifies a file that this cmdlet saves the object to. Unlike FilePath, 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 PowerShell not to interpret any characters as escape
sequences.

Type: String

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Variable

Specifies a variable that the cmdlet saves the object to. Enter a variable name
without the
preceding dollar sign ( $ ).

Type: String

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSObject

You can pipe objects to this cmdlet.

Outputs
PSObject

This cmdlet returns the object that it redirects.

Notes
Windows PowerShell includes the following aliases for Tee-Object :

tee

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" (UTF-16LE) encoding when it writes to files. If you need a
different
encoding, use the Out-File cmdlet with the Encoding parameter.

Related Links
Compare-Object
ForEach-Object
Group-Object
Measure-Object
New-Object
Select-Object
Sort-Object
Where-Object
about_Redirection
Trace-Command
Reference
Module: Microsoft.PowerShell.Utility

Configures and starts a trace of the specified expression or command.

Syntax
PowerShell

Trace-Command

[-InputObject <PSObject>]

[-Name] <String[]>

[[-Option] <PSTraceSourceOptions>]

[-Expression] <ScriptBlock>

[-ListenerOption <TraceOptions>]

[-FilePath <String>]

[-Force]

[-Debugger]

[-PSHost]

[<CommonParameters>]

PowerShell

Trace-Command

[-InputObject <PSObject>]

[-Name] <String[]>

[[-Option] <PSTraceSourceOptions>]

[-Command] <String>

[-ArgumentList <Object[]>]

[-ListenerOption <TraceOptions>]

[-FilePath <String>]

[-Force]

[-Debugger]

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

Example 1: Trace metadata processing, parameter


binding, and an expression
This example starts a trace of metadata processing, parameter binding, and cmdlet
creation and
destruction of the Get-Process Notepad expression.

PowerShell

Trace-Command -Name metadata,parameterbinding,cmdlet -Expression {Get-


Process Notepad} -PSHost

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 doesn't
specify any tracing options or listener options, the command uses the
defaults:

All for the tracing options


None for the listener options

Example 2: Trace the actions of ParameterBinding


operations
This example traces the actions of the ParameterBinding operations of PowerShell while
it
processes a Get-Alias expression that takes input from the pipeline.

PowerShell

$A = "i*"

Trace-Command ParameterBinding {Get-Alias $Input} -PSHost -InputObject $A

In Trace-Command , the InputObject parameter passes an object to the expression that's


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 .

Parameters
-ArgumentList

Specifies the parameters and parameter values for the command being traced. The
alias for
ArgumentList is Args. This feature is useful for debugging dynamic
parameters.

For more information about the behavior of ArgumentList, see


about_Splatting.

Type: Object[]

Aliases: Args

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Command

Specifies a command that's being processed during the trace.

When you use this parameter, PowerShell processes the command just as it would
be processed in a
pipeline. For example, command discovery isn't repeated for each
incoming object.

Type: String

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Debugger
Indicates that the cmdlet 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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Expression

Specifies the expression that's being processed during the trace. Enclose the
expression in braces
( {} ).

Type: ScriptBlock

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-FilePath

Specifies a file that the cmdlet sends the trace output to. This parameter also selects
the file
trace listener.

Type: String

Aliases: PSPath

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Force
Forces the command to run without asking for user confirmation. Used with the
FilePath
parameter. Even using the Force parameter, the cmdlet can't override
security restrictions.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies input to the expression that's 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.

Type: PSObject

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-ListenerOption

Specifies optional data to the prefix of each trace message in the output. The
acceptable values for
this parameter are:

None

LogicalOperationStack

DateTime
Timestamp

ProcessId
ThreadId

Callstack

None is the default.


These values are defined as a flag-based enumeration. You can combine multiple
values together to
set multiple flags using this parameter. The values can be passed
to the ListenerOption
parameter as an array of values or as a comma-separated
string of those values. The cmdlet will
combine the values using a binary-OR
operation. Passing values as an array is the simplest option
and also allows you to
use tab-completion on the values.

Type: TraceOptions

Accepted values: None, LogicalOperationStack, DateTime, Timestamp,


ProcessId, ThreadId, Callstack

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Name

Specifies an array of PowerShell components that 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 .

Type: String[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Option

Determines the type of events that are traced. The acceptable values for this
parameter are:

None

Constructor
Dispose

Finalizer

Method
Property

Delegates
Events

Exception
Lock

Error

Errors
Warning

Verbose
WriteLine

Data

Scope
ExecutionFlow

Assert
All

All is the default.

The following values are combinations of other values:

ExecutionFlow : Constructor , Dispose , Finalizer , Method , Delegates , Events ,

Scope
Data : Constructor , Dispose , Finalizer , Property , Verbose , WriteLine

Errors : Error , Exception

These values are defined as a flag-based enumeration. You can combine multiple
values together to
set multiple flags using this parameter. The values can be passed
to the Option parameter as an
array of values or as a comma-separated string of
those values. The cmdlet will combine the values
using a binary-OR operation.
Passing values as an array is the simplest option and also allows you
to use tab-
completion on the values.

Type: PSTraceSourceOptions

Accepted values: None, Constructor, Dispose, Finalizer, Method, Property,


Delegates, Events, Exception, Lock, Error, Errors, Warning,
Verbose, WriteLine, Data, Scope, ExecutionFlow, Assert, All

Position: 2

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-PSHost

Indicates that the cmdlet sends the trace output to the PowerShell host. This
parameter also selects
the PSHost trace listener.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSObject

You can pipe objects that represent input to the expression to this cmdlet.

Outputs
PSObject

This cmdlet returns no output of its own. The traced command may return output.
This
cmdlet writes the command trace to the debug stream.

Notes
Windows PowerShell includes the following aliases for Trace-Command :

trcm

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
PowerShell tracing
cmdlets are designed to help PowerShell developers, but they're
available to all users. They let
you monitor nearly every aspect of the functionality of the
shell.
A trace source is the part of each PowerShell component that manages tracing and
generates trace
messages for the component. To trace a component, you identify its
trace source.

Use Get-TraceSource to see a list of PowerShell components that are enabled for
tracing.

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.

Related Links
Get-TraceSource
Measure-Command
Set-TraceSource
Show-Command
Unblock-File
Reference
Module: Microsoft.PowerShell.Utility

Unblocks files that were downloaded from the internet.

Syntax
PowerShell

Unblock-File

[-Path] <String[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Unblock-File

-LiteralPath <String[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Unblock-File cmdlet lets you open files that were downloaded from the internet. It
unblocks
PowerShell script files that were downloaded from the internet so you can run
them, even when the
PowerShell execution policy is RemoteSigned. By default, these
files are blocked to protect the
computer from untrusted files.

Before using the Unblock-File cmdlet, review the file and its source and verify that it is
safe to
open.

Internally, the Unblock-File cmdlet removes the Zone.Identifier alternate data stream,
which
has a value of 3 to indicate that it was downloaded from the internet.

For more information about PowerShell execution policies, see


about_Execution_Policies.

This cmdlet was introduced in Windows PowerShell 3.0.


Examples

Example 1: Unblock a file


This command unblocks the PowerShellTips.chm file.

PowerShell

PS C:\> Unblock-File -Path


C:\Users\User01\Documents\Downloads\PowerShellTips.chm

Example 2: Unblock multiple files


This command unblocks all of the files in the C:\Downloads directory whose names
include
"PowerShell". Do not run a command like this one until you have verified that all
files are safe.

PowerShell

PS C:\> dir C:\Downloads\*PowerShell* | Unblock-File

Example 3: Find and unblock scripts


This command shows how to find and unblock PowerShell scripts.

The first command uses the Stream parameter of the Get-Item cmdlet get files with the
Zone.Identifier stream.

The second command shows what happens when you run a blocked script in a
PowerShell session in which
the execution policy is RemoteSigned. The RemoteSigned
policy prevents you from running
scripts that are downloaded from the internet unless
they are digitally signed.

The third command uses the Unblock-File cmdlet to unblock the script so it can run in
the session.

PowerShell

PS C:\> Get-Item * -Stream "Zone.Identifier" -ErrorAction SilentlyContinue

FileName: C:\ps-test\Start-ActivityTracker.ps1

Stream Length

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

Zone.Identifier 26

PS C:\> C:\ps-test\Start-ActivityTracker.ps1

c:\ps-test\Start-ActivityTracker.ps1 : File c:\ps-test\Start-


ActivityTracker.ps1 cannot

be loaded. The file c:\ps-test\Start-ActivityTracker.ps1 is not digitally


signed. The script

will not execute on the system. For more information, see


about_Execution_Policies.

At line:1 char:1

+ c:\ps-test\Start-ActivityTracker.ps1

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : SecurityError: (:) [], PSSecurityException

+ FullyQualifiedErrorId : UnauthorizedAccess

PS C:\> Get-Item C:\ps-test\Start-ActivityTracker.ps1 | Unblock-File

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-LiteralPath

Specifies the files to unblock. 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 PowerShell not
to interpret any characters as escape sequences.

Type: String[]

Aliases: PSPath, LP

Position: Named
Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Path

Specifies the files to unblock. Wildcard characters are supported.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a file path to this cmdlet.

Outputs
None

This cmdlet returns no output.


Notes
The Unblock-File cmdlet works only in file system drives.
Unblock-File performs the same operation as the Unblock button on the

Properties dialog
box in File Explorer.
If you use the Unblock-File cmdlet on a file that is not blocked, the command has
no effect on
the unblocked file and the cmdlet does not generate errors.

Related Links
about_Execution_Policies
Get-Item
Out-File
FileSystem Provider
Unregister-Event
Reference
Module: Microsoft.PowerShell.Utility

Cancels an event subscription.

Syntax
PowerShell

Unregister-Event

[-SourceIdentifier] <String>

[-Force]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Unregister-Event

[-SubscriptionId] <Int32>

[-Force]

[-WhatIf]

[-Confirm]

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

Examples
Example 1: Cancel an event subscription by source
identifier
PowerShell

PS C:\> 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: Cancel an event subscription by subscription


identifier
PowerShell

PS C:\> 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: Cancel all event subscriptions


PowerShell

PS C:\> 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 .
Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Force

Cancels all event subscriptions, including subscriptions that were hidden by using the
SupportEvent parameter of Register-ObjectEvent , Register-WmiEvent , and
Register-EngineEvent .

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SourceIdentifier

Specifies a source identifier that this cmdlet cancels event subscriptions.

A SourceIdentifier or SubscriptionId parameter must be included in every


command.

Type: String

Position: 0

Default value: None

Accept pipeline input: True


Accept wildcard characters: False

-SubscriptionId

Specifies a source identifier ID that this cmdlet cancels event subscriptions.

A SourceIdentifier or SubscriptionId parameter must be included in every


command.

Type: Int32

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSEventSubscriber

You can pipe the output from Get-EventSubscriber to this cmdlet.

Outputs
None

This cmdlet returns no 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.

Related Links
Get-Event
Get-EventSubscriber
New-Event
Register-EngineEvent
Register-ObjectEvent
Remove-Event
Unregister-Event
Wait-Event
Update-FormatData
Reference
Module: Microsoft.PowerShell.Utility

Updates the formatting data in the current session.

Syntax
PowerShell

Update-FormatData

[[-AppendPath] <String[]>]

[-PrependPath <String[]>]

[-WhatIf]

[-Confirm]

[<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
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 PowerShell
installation directory ( $pshome ) into the session. You can use Update-
FormatData to reload the
formatting data into the current session without restarting

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 PowerShell, see about_Format.ps1xml.

Examples
Example 1: Reload previously loaded formatting files
PowerShell

Update-FormatData

This command reloads the formatting files that it loaded previously.

Example 2: Reload formatting files and trace and log


formatting files
PowerShell

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: Edit a formatting file and reload it


PowerShell

Update-FormatData -PrependPath "c:\test\NewFiles.format.ps1xml"

# Edit the NewFiles.format.ps1 file.

Update-FormatData

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

Parameters
-AppendPath

Specifies formatting files that this cmdlet adds to the session. The files are loaded
after
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.

Type: String[]

Aliases: PSPath, Path

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


-PrependPath

Specifies formatting files that this cmdlet adds to the session. The files are loaded
before
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.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs.


The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a string that contains the append path to this cmdlet.

Outputs
None

This cmdlet returns no 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.

Related Links
Get-FormatData
Export-FormatData
Update-List
Reference
Module: Microsoft.PowerShell.Utility

Adds items to and removes items from a property value that contains a collection of
objects.

Syntax
PowerShell

Update-List

[-Add <Object[]>]

[-Remove <Object[]>]

[-InputObject <PSObject>]

[[-Property] <String>]

[<CommonParameters>]

PowerShell

Update-List

-Replace <Object[]>

[-InputObject <PSObject>]

[[-Property] <String>]

[<CommonParameters>]

Description
The Update-List cmdlet adds, removes, or replaces items in a property value of an
object and
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 PowerShell do not support this interface. To
determine whether a cmdlet supports Update-List , see the cmdlet Help topic.

Examples

Example 1: Add items to a property value


In this example we create a class that represents a deck of cards where the cards are
stored as a
List collection object. The NewDeck() method uses Update-List to add a
complete deck of
card values to the cards collection.

PowerShell

class Cards {

[System.Collections.Generic.List[string]]$cards

[string]$name

Cards([string]$_name) {

$this.name = $_name

$this.cards = [System.Collections.Generic.List[string]]::new()

NewDeck() {

$_suits = [char]0x2663,[char]0x2666,[char]0x2665,[char]0x2660

$_values = 'A',2,3,4,5,6,7,8,9,10,'J','Q','K'

$_deck = foreach ($s in $_suits){ foreach ($v in $_values){ "$v$s"}


}

$this | Update-List -Property cards -Add $_deck | Out-Null

Show() {

Write-Host

Write-Host $this.name ": " $this.cards[0..12]

if ($this.cards.count -gt 13) {

Write-Host (' ' * ($this.name.length+3)) $this.cards[13..25]

if ($this.cards.count -gt 26) {

Write-Host (' ' * ($this.name.length+3)) $this.cards[26..38]

if ($this.cards.count -gt 39) {

Write-Host (' ' * ($this.name.length+3)) $this.cards[39..51]

Shuffle() { $this.cards = Get-Random -InputObject $this.cards -Count 52


}

Sort() { $this.cards.Sort() }
}

7 Note

The Update-List cmdlet outputs the updated object to the pipeline. We pipe the
output to
Out-Null to suppress the unwanted display.

Example 2: Add and remove items of a collection


property
Continuing with the code in Example 1, we will create instances of the Cards class to
represent
a deck of cards and the cards held by two players. We use the Update-List
cmdlet to add cards to
the players' hands and to remove cards from the deck.

PowerShell

$player1 = [Cards]::new('Player 1')

$player2 = [Cards]::new('Player 2')

$deck = [Cards]::new('Deck')

$deck.NewDeck()

$deck.Shuffle()

$deck.Show()

# Deal two hands

$player1 | Update-List -Property cards -Add $deck.cards[0,2,4,6,8] | Out-


Null

$player2 | Update-List -Property cards -Add $deck.cards[1,3,5,7,9] | Out-


Null

$deck | Update-List -Property cards -Remove $player1.cards | Out-Null

$deck | Update-List -Property cards -Remove $player2.cards | Out-Null

$player1.Show()

$player2.Show()

$deck.Show()

Deck : 4♦ 7♥ J♦ 5♣ A♣ 8♦ J♣ Q♥ 6♦ 3♦ 9♦ 6♣ 2♣

K♥ 4♠ 10♥ 8♠ 10♦ 9♠ 6♠ K♦ 7♣ 3♣ Q♣ A♥ Q♠

3♥ 5♥ 2♦ 5♠ J♥ J♠ 10♣ 4♥ Q♦ 10♠ 4♣ 2♠ 2♥

6♥ 7♦ A♠ 5♦ 8♣ 9♥ K♠ 7♠ 3♠ 9♣ A♦ K♣ 8♥

Player 1 : 4♦ J♦ A♣ J♣ 6♦

Player 2 : 7♥ 5♣ 8♦ Q♥ 3♦

Deck : 9♦ 6♣ 2♣ K♥ 4♠ 10♥ 8♠ 10♦ 9♠ 6♠ K♦ 7♣ 3♣

Q♣ A♥ Q♠ 3♥ 5♥ 2♦ 5♠ J♥ J♠ 10♣ 4♥ Q♦ 10♠

4♣ 2♠ 2♥ 6♥ 7♦ A♠ 5♦ 8♣ 9♥ K♠ 7♠ 3♠ 9♣

A♦ K♣ 8♥

The output shows the state of the deck before the cards were dealt to the players. You
can see that
each player received five cards from the deck. The final output shows the
state of the deck after
dealing the cards to the players. Update-List was used to select
the cards from the deck and add
them to the players' collection. Then the players' cards
were removed from the deck using
Update-List .

Example 3: Add and remove items in a single command


Update-List allows you to use the Add and Remove parameters in a single command.
In this
example, Player 1 wants to discard the 4♦ and 6♦ and get two new cards.

PowerShell

# Player 1 wants two new cards - remove 2 cards & add 2 cards

$player1 | Update-List -Property cards -Remove $player1.cards[0,4] -Add


$deck.cards[0..1] | Out-Null

$player1.Show()

# remove dealt cards from deck

$deck | Update-List -Property cards -Remove $deck.cards[0..1] | Out-Null

$deck.Show()

Player 1 : J♦ A♣ J♣ 9♦ 6♣

Deck : 2♣ K♥ 4♠ 10♥ 8♠ 10♦ 9♠ 6♠ K♦ 7♣ 3♣ Q♣ A♥

Q♠ 3♥ 5♥ 2♦ 5♠ J♥ J♠ 10♣ 4♥ Q♦ 10♠ 4♣ 2♠

2♥ 6♥ 7♦ A♠ 5♦ 8♣ 9♥ K♠ 7♠ 3♠ 9♣ A♦ K♣

8♥

Parameters
-Add

Specifies the property values to be added to the collection. Enter the values in the
order that they
should appear in the collection.

Type: Object[]

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies the objects to be updated. You can also pipe the object to be updated to
Update-List .

Type: PSObject

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Property

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

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Remove

Specifies the property values to be removed from the collection.

Type: Object[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-Replace

Specifies a new collection. This parameter replaces all items in the original collection
with the
items specified by this parameter.

Type: Object[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSObject

You can pipe the object to be updated to this cmdlet.

Outputs
PSListModifier

By default, this cmdlet returns an object representing the update action.

Object

When you specify the Property parameter, this cmdlet returns the updated object.

Related Links
Select-Object
Update-TypeData
Reference
Module: Microsoft.PowerShell.Utility

Updates the extended type data in the session.

Syntax
PowerShell

Update-TypeData

[[-AppendPath] <String[]>]

[-PrependPath <String[]>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Update-TypeData

[-MemberType <PSMemberTypes>]

[-MemberName <String>]

[-Value <Object>]

[-SecondValue <Object>]

[-TypeConverter <Type>]

[-TypeAdapter <Type>]

[-SerializationMethod <String>]

[-TargetTypeForDeserialization <Type>]

[-SerializationDepth <Int32>]

[-DefaultDisplayProperty <String>]

[-InheritPropertySerializationSet <Nullable`1>]

[-StringSerializationSource <String>]

[-DefaultDisplayPropertySet <String[]>]

[-DefaultKeyPropertySet <String[]>]

[-PropertySerializationSet <String[]>]

-TypeName <String>

[-Force]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Update-TypeData

[-Force]

[-TypeData] <TypeData[]>

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Update-TypeData cmdlet updates the extended type data in the session by reloading
the
Types.ps1xml files into memory and adding new extended type data.

By default, PowerShell loads extended type data as it is needed. Without parameters,


Update-TypeData reloads all of the Types.ps1xml files that it has loaded in the session,

including any type files that you added. You can use the parameters of Update-TypeData
to add new
type files and add and replace extended type data.

The Update-TypeData cmdlet can be used to preload all type data. This feature is
particularly
useful when you are developing types and want to load those new types for
testing purposes.

Beginning in Windows PowerShell 3.0, you can use Update-TypeData to add and replace
extended type
data in the session without using a Types.ps1xml file. Type data that is
added dynamically, that
is, without a file, is added only to the current session. To add
the type data to all sessions, add
an Update-TypeData command to your PowerShell
profile. For more information, see
about_Profiles.

Also, beginning in Windows PowerShell 3.0, you can use the Get-TypeData cmdlet to get
the extended
types in the current session and the Remove-TypeData cmdlet to delete
extended types from the
current session.

Exceptions that occur in properties, or from adding properties to an Update-TypeData


command, do
not report errors. This is to suppress exceptions that would occur in many
common types during
formatting and outputting. If you are getting .NET properties, you
can work around the suppression
of exceptions by using method syntax instead, as
shown in the following example:

"hello".get_Length()

Note that method syntax can only be used with .NET properties. Properties that are
added by running
the Update-TypeData cmdlet cannot use method syntax.

For more information about the Types.ps1xml files in PowerShell, see


about_Types.ps1xml.
Examples

Example 1: Update extended types


PowerShell

Update-TypeData

This command updates the extended type configuration from the Types.ps1xml files
that have already
been used in the session.

Example 2: Update types multiple times


This example shows how to update the types in a type file multiple times in the same
session.

The first command updates the extended type configuration from the Types.ps1xml
files, processing
the TypesA.types.ps1xml and TypesB.types.ps1xml files first.

The second command shows how to update the TypesA.types.ps1xml again, such as you
might do if you
added or changed a type in the file. You can either repeat the previous
command for the
TypesA.types.ps1xml file, or run an Update-TypeData command
without parameters, because
TypesA.types.ps1xml is already in the type file list for the
current session.

PowerShell

Update-TypeData -PrependPath TypesA.types.ps1xml, TypesB.types.ps1xml

Update-TypeData -PrependPath TypesA.types.ps1xml

Example 3: Add a script property to DateTime objects


This example uses Update-TypeData to add the Quarter script property to
System.DateTime
objects in the current session, such as those returned by the Get-Date
cmdlet.

PowerShell

Update-TypeData -TypeName "System.DateTime" -MemberType ScriptProperty -


MemberName "Quarter" -Value {

if ($this.Month -in @(1,2,3)) {"Q1"}

elseif ($this.Month -in @(4,5,6)) {"Q2"}

elseif ($this.Month -in @(7,8,9)) {"Q3"}

else {"Q4"}

(Get-Date).Quarter

Q1

The Update-TypeData command uses the TypeName parameter to specify the


System.DateTime
type, the MemberName parameter to specify a name for the new
property, the MemberType
property to specify the ScriptProperty type, and the Value
parameter to specify the script
that determines the annual quarter.

The value of the Value property is a script that calculates the current annual quarter. The
script block uses the $this automatic variable to represent the current instance of the
object and
the In operator to determine whether the month value appears in each
integer array. For more
information about the -in operator, see
about_Comparison_Operators.

The second command gets the new Quarter property of the current date.

Example 4: Update a type that displays in lists by default


This example shows how to set the properties of a type that displays in lists by default,
that is,
when no properties are specified. Because the type data is not specified in a
Types.ps1xml file, it
is effective only in the current session.

PowerShell

Update-TypeData -TypeName "System.DateTime" -DefaultDisplayPropertySet


"DateTime, DayOfYear, Quarter"

Get-Date | Format-List

Thursday, March 15, 2012 12:00:00 AM

DayOfYear : 75

Quarter : Q1

The first command uses the Update-TypeData cmdlet to set the default list properties for
the
System.DateTime type. The command uses the TypeName parameter to specify the
type and the
DefaultDisplayPropertySet parameter to specify the default properties for
a list. The selected
properties include the new Quarter script property that was added in
a previous example.

The second command uses the Get-Date cmdlet to get a System.DateTime object that
represents
the current date. The command uses a pipeline operator ( | ) to send the
DateTime object to the
Format-List cmdlet. Because the Format-List command does
not specify the properties to display
in the list, PowerShell uses the default values that
were established by the Update-TypeData
command.

Example 5: Update type data for a piped object


PowerShell

Get-Module | Update-TypeData -MemberType ScriptProperty -MemberName


"SupportsUpdatableHelp" -Value {

if ($this.HelpInfoUri) {$True} else {$False}

Get-Module -ListAvailable | Format-Table Name, SupportsUpdatableHelp

Name SupportsUpdatableHelp

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

Microsoft.PowerShell.Diagnostics True

Microsoft.PowerShell.Host True

Microsoft.PowerShell.Management True

Microsoft.PowerShell.Security True

Microsoft.PowerShell.Utility True

Microsoft.WSMan.Management True

PSDiagnostics False

PSScheduledJob True

PSWorkflow True

ServerManager True

TroubleshootingPack False

This example demonstrates that when you pipe an object to Update-TypeData , Update-
TypeData adds
extended type data for the object type.

This technique is quicker than using the Get-Member cmdlet or the Get-Type method to
get the
object type. However, if you pipe a collection of objects to Update-TypeData , it
updates the type
data of the first object type and then returns an error for all other
objects in the collection
because the member is already defined on the type.

The first command uses the Get-Module cmdlet to get the PSScheduledJob module. The
command pipes
the module object to the Update-TypeData cmdlet, which updates the
type data for the
System.Management.Automation.PSModuleInfo type and the types
derived from it, such as the
ModuleInfoGrouping type that Get-Module returns when you
use the ListAvailable parameter in
the command.

The Update-TypeData commands adds the SupportsUpdatableHelp script property to all


imported
modules. The value of the Value parameter is a script that returns $True if the
HelpInfoUri property of the module is populated and $False otherwise.
The second command pipes the module objects from Get-Module to the Format-Table
cmdlet, which
displays the Name and SupportsUpdatableHelp properties of all modules
in a list.

Parameters
-AppendPath

Specifies the path to optional .ps1xml files. The specified files are loaded in the
order that
they are listed after the built-in files are loaded. You can also pipe an
AppendPath value to
Update-TypeData .

Type: String[]

Aliases: PSPath, Path

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-DefaultDisplayProperty

Specifies the property of the type that is displayed by the Format-Wide cmdlet when
no other
properties are specified.
Type the name of a standard or extended property of the type. The value of this
parameter can be the
name of a type that is added in the same command.

This value is effective only when there are no wide views defined for the type in a
Format.ps1xml
file.

This parameter was introduced in Windows PowerShell 3.0.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-DefaultDisplayPropertySet

Specifies one or more properties of the type. These properties are displayed by the
Format-List ,
Format-Table , and Format-Custom cmdlets when no other properties

are specified.

Type the names of standard or extended properties of the type. The value of this
parameter can be
the names of types that are added in the same command.

This value is effective only when there are no list, table, or custom views, respectively,
defined for the type in a Format.ps1xml file.

This parameter was introduced in Windows PowerShell 3.0.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-DefaultKeyPropertySet

Specifies one or more properties of the type. These properties are used by the
Group-Object and
Sort-Object cmdlets when no other properties are specified.
Type the names of standard or extended properties of the type. The value of this
parameter can be
the names of types that are added in the same command.

This parameter was introduced in Windows PowerShell 3.0.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Force

Indicates that the cmdlet uses the specified type data, even if type data has already
been specified
for that type.

This parameter was introduced in Windows PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InheritPropertySerializationSet

Indicates whether the set of properties that are serialized is inherited. The default
value is
$Null . The acceptable values for this parameter are:

$True . The property set is inherited.

$False . The property set is not inherited.

$Null . Inheritance is not defined.

This parameter is valid only when the value of the SerializationMethod parameter is
SpecificProperties . When the value of this parameter is $False , the
PropertySerializationSet
parameter is required.

This parameter was introduced in Windows PowerShell 3.0.


Type: Nullable<T>[Boolean]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-MemberName

Specifies the name of a property or method.

Use this parameter with the TypeName, MemberType, Value and SecondValue
parameters
to add or change a property or method of a type.

This parameter was introduced in Windows PowerShell 3.0.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-MemberType

Specifies the type of the member to add or change.

Use this parameter with the TypeName, MemberType, Value and SecondValue
parameters
to add or change a property or method of a type. The acceptable values
for this parameter are:

AliasProperty
CodeMethod
CodeProperty
Noteproperty
ScriptMethod
ScriptProperty

For information about these values, see


PSMemberTypes Enumeration.

This parameter was introduced in Windows PowerShell 3.0.


Type: PSMemberTypes

Accepted values: NoteProperty, AliasProperty, ScriptProperty, CodeProperty,


ScriptMethod, CodeMethod

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-PrependPath

Specifies the path to the optional .ps1xml files. The specified files are loaded in the
order that
they are listed before the built-in files are loaded.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-PropertySerializationSet

Specifies the names of properties that are serialized. Use this parameter when the
value of the
SerializationMethod parameter is SpecificProperties.

Type: String[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SecondValue

Specifies additional values for AliasProperty, ScriptProperty, CodeProperty, or


CodeMethod members.
Use this parameter with the TypeName, MemberType, Value, and SecondValue
parameters to add
or change a property or method of a type.

When the value of the MemberType parameter is AliasProperty , the value of the
SecondValue
parameter must be a data type. PowerShell converts (that is, casts) the
value of the alias property
to the specified type. For example, if you add an alias
property that provides an alternate name for
a string property, you can also specify a
SecondValue of System.Int32 to convert the aliased
string value to an integer.

When the value of the MemberType parameter is ScriptProperty , you can use the
SecondValue
parameter to specify an additional script block. The script block in the
value of the Value
parameter gets the value of a variable. The script block in the
value of the SecondValue parameter
set the value of the variable.

This parameter was introduced in Windows PowerShell 3.0.

Type: Object

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SerializationDepth

Specifies how many levels of type objects are serialized as strings. The default value
1
serializes the object and its properties. A value of 0 serializes the object, but not
its
properties. A value of 2 serializes the object, its properties, and any objects in
property
values.

This parameter was introduced in Windows PowerShell 3.0.

Type: Int32

Position: Named

Default value: 1

Accept pipeline input: False

Accept wildcard characters: False

-SerializationMethod
Specifies a serialization method for the type. A serialization method determines
which properties of
the type are serialized and the technique that is used to serialize
them. The acceptable values for
this parameter are:

AllPublicProperties . Serialize all public properties of the type. You can use the
SerializationDepth parameter to determine whether child properties are
serialized.
String . Serialize the type as a string. You can use the StringSerializationSource
to specify
a property of the type to use as the serialization result. Otherwise,
the type is serialized by
using the ToString method of the object.
SpecificProperties . Serialize only the specified properties of this type. Use the

PropertySerializationSet parameter to specify the properties of the type that


are serialized.
You can also use the InheritPropertySerializationSet parameter
to determine whether the
property set is inherited and the SerializationDepth
parameter to determine whether child
properties are serialized.

In PowerShell, serialization methods are stored in PSStandardMembers internal


objects.

This parameter was introduced in Windows PowerShell 3.0.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-StringSerializationSource

Specifies the name of a property of the type. The value of specified property is used
as the
serialization result. This parameter is valid only when the value of the
SerializationMethod
parameter is String.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-TargetTypeForDeserialization

Specifies the type to which object of this type are converted when they are
deserialized.

This parameter was introduced in Windows PowerShell 3.0.

Type: Type

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-TypeAdapter

Specifies the type of a type adapter, such as


Microsoft.PowerShell.Cim.CimInstanceAdapter. A
type adapter enables PowerShell
to get the members of a type.

This parameter was introduced in Windows PowerShell 3.0.

Type: Type

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-TypeConverter

Specifies a type converter to convert values between different types. If a type


converter is defined
for a type, an instance of the type converter is used for the
conversion.

Enter a System.Type value that is derived from the


System.ComponentModel.TypeConverter or
System.Management.Automation.PSTypeConverter classes.

This parameter was introduced in Windows PowerShell 3.0.

Type: Type
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-TypeData

Specifies an array of type data that this cmdlet adds to the session. Enter a variable
that contains
a TypeData object or a command that gets a TypeData object, such as
a Get-TypeData
command. You can also pipe a TypeData object to Update-TypeData .

This parameter was introduced in Windows PowerShell 3.0.

Type: TypeData[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-TypeName

Specifies the name of the type to extend.

For types in the System namespace, enter the short name. Otherwise, the full type
name is
required. Wildcards are not supported.

You can pipe type names to Update-TypeData . When you pipe an object to Update-
TypeData ,
Update-TypeData gets the type name of the object and type data to the

object type.

Use this parameter with the MemberName, MemberType, Value and SecondValue
parameters
to add or change a property or method of a type.

This parameter was introduced in Windows PowerShell 3.0.

Type: String

Position: Named

Default value: None


Accept pipeline input: True

Accept wildcard characters: False

-Value

Specifies the value of the property or method.

If you add an AliasProperty , CodeProperty , ScriptProperty , or CodeMethod member,


you can use
the SecondValue parameter to add additional information.

Use this parameter with the MemberName, MemberType, Value and SecondValue
parameters
to add or change a property or method of a type.

This parameter was introduced in Windows PowerShell 3.0.

Type: Object

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String
You can pipe a string that contains the values of the AppendPath, TypeName, or
TypeData
parameters to this cmdlet.

Outputs
None

This cmdlet returns no output.

Related Links
about_Types.ps1xml
Get-TypeData
Remove-TypeData
Wait-Debugger
Reference
Module: Microsoft.PowerShell.Utility

Stops a script in the debugger before running the next statement in the script.

Syntax
PowerShell

Wait-Debugger []

Description
Stops the PowerShell script execution engine at the point immediately after the Wait-
Debugger
cmdlet and waits for a debugger to be attached. This is similar to using

Enable-RunspaceDebug -BreakAll in a DSC resource but breaks at a specific point in the

script.

U Caution

Make sure you remove the Wait-Debugger lines after you are done. A running script
appears to be
hung when it is stopped at a Wait-Debugger .

Examples

Example 1: Insert breakpoint for debugging


PowerShell

[DscResource()]

class FileResource

[DscProperty(Key)]

[string] $Path

[DscProperty(Mandatory)]

[Ensure] $Ensure

[DscProperty(Mandatory)]

[string] $SourcePath

[DscProperty(NotConfigurable)]

[Nullable[datetime]] $CreationTime

[void] Set()

$fileExists = $this.TestFilePath($this.Path)

if ($this.ensure -eq [Ensure]::Present)

if (! $fileExists)

$this.CopyFile()

else

if ($fileExists)

Write-Verbose -Message "Deleting the file $($this.Path)"

Remove-Item -LiteralPath $this.Path -Force

[bool] Test()

$present = Test-Path -LiteralPath $this.Path

if ($this.Ensure -eq [Ensure]::Present)

return $present

else

return (! $present)

[FileResource] Get()

$present = Test-Path -Path $this.Path

if ($present)

$file = Get-ChildItem -LiteralPath $this.Path

$this.CreationTime = $file.CreationTime

$this.Ensure = [Ensure]::Present

else

$this.CreationTime = $null

$this.Ensure = [Ensure]::Absent

return $this

[void] CopyFile()

# Testing only - Remove before deployment!

Wait-Debugger

if (! (Test-Path -LiteralPath $this.SourcePath))

throw "SourcePath $($this.SourcePath) is not found."

if (Test-Path -LiteralPath $this.Path -PathType Container)

throw "Path $($this.Path) is a directory path"

Write-Verbose "Copying $($this.SourcePath) to $($this.Path)"

Copy-Item -LiteralPath $this.SourcePath -Destination $this.Path -


Force

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

This cmdlet returns no output.

Related Links
Enable-DscDebug
Wait-Event
Reference
Module: Microsoft.PowerShell.Utility

Waits until a particular event is raised before continuing to run.

Syntax
PowerShell

Wait-Event

[[-SourceIdentifier] <String>]

[-Timeout <Int32>]

[<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:

using the Action parameter of the event subscription


waiting for an event to return and then respond with an action

Examples

Example 1: Wait for the next event


This example waits for the next event that is raised.

PowerShell

Wait-Event
Example 2: Wait for an event with a specified source
identifier
This example waits for the next event that is raised and that has a source identifier of
ProcessStarted.

PowerShell

Wait-Event -SourceIdentifier "ProcessStarted"

Example 3: Wait for a timer elapsed event


This example uses the Wait-Event cmdlet to wait for a timer event on a timer that is set
for 2000 milliseconds.

PowerShell

$Timer = New-Object Timers.Timer

$objectEventArgs = @{

InputObject = $Timer

EventName = 'Elapsed'

SourceIdentifier = 'Timer.Elapsed'

Register-ObjectEvent @objectEventArgs

$Timer.Interval = 2000

$Timer.Autoreset = $False

$Timer.Enabled = $True

Wait-Event Timer.Elapsed

ComputerName :

RunspaceId : bb560b14-ff43-48d4-b801-5adc31bbc6fb

EventIdentifier : 1

Sender : System.Timers.Timer

SourceEventArgs : System.Timers.ElapsedEventArgs

SourceArgs : {System.Timers.Timer, System.Timers.ElapsedEventArgs}

SourceIdentifier : Timer.Elapsed

TimeGenerated : 4/23/2020 2:30:37 PM

MessageData :

Example 4: Wait for an event after a specified timeout


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

PowerShell
Wait-Event -SourceIdentifier "ProcessStarted" -Timeout 90

Parameters
-SourceIdentifier

Specifies the source identifier that this cmdlet waits for events.
By default, Wait-
Event waits for any event.

Type: String

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Timeout

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

Type: Int32

Aliases: TimeoutSec

Position: Named

Default value: -1

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String
Outputs
PSEventArgs

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.

Related Links
Get-Event
Get-EventSubscriber
New-Event
Register-EngineEvent
Register-ObjectEvent
Remove-Event
Unregister-Event
Wait-Event
Write-Debug
Reference
Module: Microsoft.PowerShell.Utility

Writes a debug message to the console.

Syntax
PowerShell

Write-Debug

[-Message] <String>

[<CommonParameters>]

Description
The Write-Debug cmdlet writes debug messages to the host 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.

Examples

Example 1: Understand $DebugPreference


This example writes a debug message.

PowerShell

Write-Debug "Cannot open file."

The default value of $DebugPreference is SilentlyContinue. Therefore, the message is not


displayed in the console.

Example 2: Change the value of $DebugPreference


This example shows the effect of changing the value of the $DebugPreference variable.
First, we
display the current value of $DebugPreference and attempt to write a debug
message. Then we change
the value of $DebugPreference to Continue, which allows
debug messages to be displayed.

PowerShell

PS> $DebugPreference

SilentlyContinue

PS> Write-Debug "Cannot open file."

PS>

PS> $DebugPreference = "Continue"

PS> Write-Debug "Cannot open file."

DEBUG: Cannot open file.

For more information about $DebugPreference , see


about_Preference_Variables.

Example 3: Use the Debug parameter to override


$DebugPreference
The Test-Debug function writes the value of the $DebugPreference variable to the
PowerShell host
and to the Debug stream. In this example, we use the Debug parameter
to override the
$DebugPreference value.

PowerShell

function Test-Debug {

[CmdletBinding()]

param()

Write-Debug ('$DebugPreference is ' + $DebugPreference)

Write-Host ('$DebugPreference is ' + $DebugPreference)

PS> Test-Debug

$DebugPreference is SilentlyContinue

PS> Test-Debug -Debug

DEBUG: $DebugPreference is Inquire

Confirm

Continue with this operation?

[Y] Yes [A] Yes to All [H] Halt Command [?] Help (default is "Y"):

$DebugPreference is Inquire

PS> $DebugPreference

SilentlyContinue

Notice that the value of $DebugPreference changes when you use the Debug parameter.
This
change only affects the scope of the function. The value is not affected outside the
function.
7 Note

When the value of $DebugPreference is Inquire, PowerShell halts execution to ask if


execution should continue.

For more information about the Debug common parameter, see


about_CommonParameters .

Parameters
-Message

Specifies the debug message to send to the console.

Type: String

Aliases: Msg

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

Inputs
String

You can pipe a string that contains a debug message to this cmdlet.

Outputs
None

This cmdlet returns no output. It only writes to the debug stream.

Related Links
about_Output_Streams
about_Redirection
Write-Error
Write-Host
Write-Output
Write-Progress
Write-Verbose
Write-Warning
Write-Error
Reference
Module: Microsoft.PowerShell.Utility

Writes an object to the error stream.

Syntax
PowerShell

Write-Error

[-Message] <string>

[-Category <ErrorCategory>]

[-ErrorId <string>]

[-TargetObject <Object>]

[-RecommendedAction <string>]

[-CategoryActivity <string>]
[-CategoryReason <string>]

[-CategoryTargetName <string>]

[-CategoryTargetType <string>]

[<CommonParameters>]

PowerShell

Write-Error

-Exception <Exception>

[-Message <string>]

[-Category <ErrorCategory>]

[-ErrorId <string>]

[-TargetObject <Object>]

[-RecommendedAction <string>]

[-CategoryActivity <string>]
[-CategoryReason <string>]

[-CategoryTargetName <string>]

[-CategoryTargetType <string>]

[<CommonParameters>]

PowerShell

Write-Error

-ErrorRecord <ErrorRecord>

[-RecommendedAction <string>]

[-CategoryActivity <string>]
[-CategoryReason <string>]

[-CategoryTargetName <string>]

[-CategoryTargetType <string>]

[<CommonParameters>]

Description
The Write-Error cmdlet declares a non-terminating error. By default, errors are sent in
the error
stream to the host program to be displayed, along with output.

To write a non-terminating error, enter an error message string, an ErrorRecord object,


or an
Exception object. Use the other parameters of Write-Error to populate the error
record.

Non-terminating errors write an error to the error stream, but they don't stop command
processing.
If a non-terminating error is declared on one item in a collection of input
items, the command
continues to process the other items in the collection.

To declare a terminating error, use the Throw keyword.


For more information, see
about_Throw.

Examples

Example 1: Write an error for RegistryKey object


PowerShell

Get-ChildItem | ForEach-Object {

if ($_.GetType().ToString() -eq "Microsoft.Win32.RegistryKey")

Write-Error "Invalid object" -ErrorId B1 -TargetObject $_

else

$_

This command declares a non-terminating error when the Get-ChildItem cmdlet returns
a
Microsoft.Win32.RegistryKey object, such as the objects in the HKLM: or HKCU: drives
of the
PowerShell Registry provider.

Example 2: Write an error message to the console


PowerShell

Write-Error "Access denied."

This command declares a non-terminating error and writes an "Access denied" error.
The command uses
the Message parameter to specify the message, but omits the
optional Message parameter name.

Example 3: Write an error to the console and specify the


category
PowerShell

Write-Error -Message "Error: Too many input values." -Category


InvalidArgument

This command declares a non-terminating error and specifies an error category.

Example 4: Write an error using an Exception object


PowerShell

$E = [System.Exception]@{Source="Get-
ParameterNames.ps1";HelpLink="https://go.microsoft.com/fwlink/?
LinkID=113425"}

Write-Error -Exception $E -Message "Files not found. The $Files location


doesn't contain any XML files."

This command uses an Exception object to declare a non-terminating error.

The first command uses a hash table to create the System.Exception object. It saves the
exception object in the $E variable. You can use a hash table to create any object of a
type that
has a null constructor.

The second command uses the Write-Error cmdlet to declare a non-terminating error.
The value of
the Exception parameter is the Exception object in the $E variable.

Parameters
-Category
Specifies the category of the error. The default value is NotSpecified. The acceptable
values
for this parameter are:

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
ProtocolError
ConnectionError
AuthenticationError
LimitsExceeded
QuotaExceeded
NotEnabled

For information about the error categories, see ErrorCategory Enumeration .

Type: ErrorCategory

Accepted values: 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, ProtocolError, ConnectionError,
AuthenticationError, LimitsExceeded, QuotaExceeded,
NotEnabled

Position: Named

Default value: NotSpecified

Accept pipeline input: False

Accept wildcard characters: False

-CategoryActivity

Specifies the action that caused the error.

Type: String

Aliases: Activity

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-CategoryReason

Specifies how or why the activity caused the error.

Type: String

Aliases: Reason

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-CategoryTargetName

Specifies the name of the object that was being processed when the error occurred.

Type: String

Aliases: TargetName

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-CategoryTargetType

Specifies the type of the object that was being processed when the error occurred.

Type: String

Aliases: TargetType

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ErrorId

Specifies an ID string to identify the error. The string should be unique to the error.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ErrorRecord
Specifies an error record object that represents the error. Use the properties of the
object to
describe the error.

To create an error record object, use the New-Object cmdlet or get an error record
object from the
array in the $Error automatic variable.

Type: ErrorRecord

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Exception

Specifies an exception object that represents the error. Use the properties of the
object to
describe the error.

To create an exception object, use a hash table or use the New-Object cmdlet.

Type: Exception

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Message

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 .

Type: String

Aliases: Msg

Position: 0

Default value: None

Accept pipeline input: True


Accept wildcard characters: False

-RecommendedAction

Specifies the action that the user should take to resolve or prevent the error.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-TargetObject

Specifies the object that was being processed when the error occurred. Enter the
object, a variable
that contains the object, or a command that gets the object.

Type: Object

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
String

You can pipe a string that contains an error message to this cmdlet.

Outputs
None

This cmdlet returns no output. It only writes to the error message stream.

Notes
Write-Error doesn't change the value of the $? automatic variable, therefore it doesn't

signal a
terminating error condition. To signal a terminating error, use the
$PSCmdlet.WriteError() method.

Related Links
about_Automatic_Variables
about_Output_Streams
about_Redirection
Write-Debug
Write-Host
Write-Output
Write-Progress
Write-Verbose
Write-Warning
Write-Host
Reference
Module: Microsoft.PowerShell.Utility

Writes customized output to a host.

Syntax
PowerShell

Write-Host

[[-Object] <Object>]

[-NoNewline]

[-Separator <Object>]

[-ForegroundColor <ConsoleColor>]

[-BackgroundColor <ConsoleColor>]

[<CommonParameters>]

Description
The Write-Host cmdlet's primary purpose is to produce for-(host)-display-only output,
such as
printing colored text like when prompting the user for input in conjunction with
Read-Host.
Write-Host uses the ToString() method to write the
output. By contrast, to
output data to the pipeline, use Write-Output or implicit
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 PowerShell.

7 Note

Starting in Windows PowerShell 5.0, Write-Host is a wrapper for Write-Information


This allows
you to use Write-Host to emit output to the information stream. This
enables the capture or
suppression of data written using Write-Host while
preserving backwards compatibility.

The $InformationPreference preference variable and InformationAction common


parameter do not
affect Write-Host messages. The exception to this rule is -
InformationAction Ignore , which
effectively suppresses Write-Host output. (see

"Example 5")

Examples

Example 1: Write to the console without adding a new


line
PowerShell

Write-Host "no newline test " -NoNewline

Write-Host "second string"

no newline test second string

This command displays the string 'no newline test' with the NoNewline parameter.

A second string is written, but it ends up on the same line as the first due to the absence
of a
newline separating the strings.

Example 2: Write to the console and include a separator


PowerShell

Write-Host (2,4,6,8,10,12) -Separator ", +2= "

2, +2= 4, +2= 6, +2= 8, +2= 10, +2= 12

This command displays the even numbers from two through twelve. The Separator
parameter is used
to add the string , +2= (comma, space, + , 2 , = , space).

Example 3: Write with different text and background


colors
PowerShell

Write-Host (2,4,6,8,10,12) -Separator ", -> " -ForegroundColor DarkGreen -


BackgroundColor White

2, -> 4, -> 6, -> 8, -> 10, -> 12


This command displays the even numbers from two through twelve. It uses the
ForegroundColor
parameter to output dark green text and the BackgroundColor
parameter to display a white
background.

Example 4: Write with different text and background


colors
PowerShell

Write-Host "Red on white text." -ForegroundColor red -BackgroundColor white

Red on white text.

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.

Example 5: Suppress output from Write-Host


PowerShell

# The following two statements can be used to effectively suppress output


from Write-Host

Write-Host "I won't print" -InformationAction Ignore

Write-Host "I won't print" 6> $null

These commands effectively suppress output of the Write-Host cmdlet. The first one
uses the
InformationAction parameter with the Ignore Value to suppress output to the
information stream.
The second example redirects the information stream of the
command to the $null variable and
thereby suppresses it. For more information, see
about_Output_Streams.

Parameters
-BackgroundColor

Specifies the background color. There is no default. The acceptable values for this
parameter are:

Black
DarkBlue
DarkGreen
DarkCyan
DarkRed
DarkMagenta
DarkYellow
Gray
DarkGray
Blue
Green
Cyan
Red
Magenta
Yellow
White

Type: ConsoleColor

Accepted values: Black, DarkBlue, DarkGreen, DarkCyan, DarkRed, DarkMagenta,


DarkYellow, Gray, DarkGray, Blue, Green, Cyan, Red, Magenta,
Yellow, White

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ForegroundColor

Specifies the text color. There is no default. The acceptable values for this parameter
are:

Black
DarkBlue
DarkGreen
DarkCyan
DarkRed
DarkMagenta
DarkYellow
Gray
DarkGray
Blue
Green
Cyan
Red
Magenta
Yellow
White

Type: ConsoleColor

Accepted values: Black, DarkBlue, DarkGreen, DarkCyan, DarkRed, DarkMagenta,


DarkYellow, Gray, DarkGray, Blue, Green, Cyan, Red, Magenta,
Yellow, White

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-NoNewline

The string representations of the input objects are concatenated to form the output.
No spaces or
newlines are inserted between the output strings. No newline is added
after the last output string.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Object

Objects to display in the host.

Type: Object

Position: 0

Default value: None

Accept pipeline input: True


Accept wildcard characters: False

-Separator

Specifies a separator string to insert between objects displayed by the host.

Type: Object

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
Object

You can pipe objects to be written to the host to this cmdlet.

Outputs
None

This cmdlet returns no output. It sends the objects to the host. The host displays the
objects this
cmdlet sends to it.

Notes
When writing a collection to the host, elements of the collection are printed on the
same line
separated by a single space. This can be overridden with the Separator
parameter.

Non-primitive data types such as objects with properties can cause unexpected
results and not
provide meaningful output. For example, Write-Host @{a = 1; b =
2} will print
System.Collections.DictionaryEntry

System.Collections.DictionaryEntry to the host.

Related Links
Clear-Host
Out-Host
Write-Debug
Write-Error
Write-Output
Write-Progress
Write-Verbose
Write-Warning
Write-Information
Reference
Module: Microsoft.PowerShell.Utility

Specifies how PowerShell handles information stream data for a command.

Syntax
PowerShell

Write-Information

[-MessageData] <Object>

[[-Tags] <String[]>]

[<CommonParameters>]

Description
The Write-Information cmdlet specifies how PowerShell handles information stream
data for a
command.

Windows PowerShell 5.0 introduces a new, structured information stream. You can use
this stream to
transmit structured data between a script and its callers or the host
application.
Write-Information lets you add an informational message to the stream,
and specify how PowerShell
handles information stream data for a command.
Information streams also work for
PowerShell.Streams , jobs, and scheduled tasks.

7 Note

The information stream does not follow the standard convention of prefixing its
messages with
"[Stream Name]:". This was intended for brevity and visual
cleanliness.

The $InformationPreference preference variable value determines whether the message


you provide to
Write-Information is displayed at the expected point in a script's
operation. Because the default
value of this variable is SilentlyContinue, by default,
informational messages are not shown.
If you don't want to change the value of
$InformationPreference , you can override its value by
adding the InformationAction
common parameter to your command. For more information, see
about_Preference_Variables and
about_CommonParameters.
7 Note

Starting in Windows PowerShell 5.0, Write-Host is a wrapper for Write-Information


This allows
you to use Write-Host to emit output to the information stream. This
enables the capture or
suppression of data written using Write-Host while
preserving backwards compatibility. For more
information see Write-Host

Write-Information is also a supported workflow activity in Windows PowerShell 5.1.

Examples

Example 1: Write information for Get- results


In this example, you show an informational message, "Processes starting with 'P'", before
running
the Get-Process command to find all processes that have a Name value that
starts with 'p'.
Because the $InformationPreference variable is still set to its default,
SilentlyContinue, you
add the InformationAction parameter to override the
$InformationPreference value, and show the
message. The InformationAction value is

Continue, which means that your message is shown,


but the script or command
continues, if it is not yet finished.

PowerShell

Write-Information -MessageData "Processes starting with 'P'" -


InformationAction Continue

Get-Process -Name p*

Processes starting with 'P'

18 19.76 15.16 0.00 6232 0 PFERemediation

20 8.92 25.15 0.00 24944 0 policyHost

9 1.77 7.64 0.00 1780 0 powercfg

10 26.67 32.18 0.00 7028 0 powercfg

8 26.55 31.59 0.00 13600 0 powercfg

9 1.66 7.55 0.00 22620 0 powercfg

21 6.17 4.54 202.20 12536 1 PowerMgr

42 84.26 12.71 2,488.84 20588 1 powershell

27 47.07 45.38 2.05 25988 1 powershell

27 24.45 5.31 0.00 12364 0 PresentationFontCache

92 112.04 13.36 82.30 13176 1 pwsh

106 163.73 93.21 302.25 14620 1 pwsh

227 764.01 92.16 1,757.22 25328 1 pwsh


Example 2: Write information and tag it
In this example, you use Write-Information to let users know they'll need to run another
command
after they're done running the current command. The example adds the tag
"Instructions" to the
informational message. After running this command, when you

search the information stream for


messages tagged "Instructions" , the message is in
the results.

PowerShell

$message = "To filter your results for PowerShell, pipe your results to the
Where-Object cmdlet."

Get-Process -Name p*

Write-Information -MessageData $message -Tags "Instructions" -


InformationAction Continue

NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName

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

18 19.76 15.16 0.00 6232 0 PFERemediation

20 8.92 25.15 0.00 24944 0 policyHost

9 1.77 7.64 0.00 1780 0 powercfg

10 26.67 32.18 0.00 7028 0 powercfg

8 26.55 31.59 0.00 13600 0 powercfg

9 1.66 7.55 0.00 22620 0 powercfg

21 6.17 4.54 202.20 12536 1 PowerMgr

42 84.26 12.71 2,488.84 20588 1 powershell

27 47.07 45.38 2.05 25988 1 powershell

27 24.45 5.31 0.00 12364 0 PresentationFontCache

92 112.04 13.36 82.30 13176 1 pwsh

106 163.73 93.21 302.25 14620 1 pwsh

227 764.01 92.16 1,757.22 25328 1 pwsh

To filter your results for PowerShell, pipe your results to the Where-Object
cmdlet.

Example 3: Write information to a file


In this example, you redirect the information stream in the function to Info.txt using
the code
6> . When you open the Info.txt file, you see the text "Here you go."

PowerShell

function Test-Info

Get-Process P*

Write-Information "Here you go"

Test-Info 6> Info.txt


Parameters
-MessageData

Specifies an informational message that you want to display to users as they run a
script or
command. For best results, enclose the informational message in quotation
marks.

Type: Object

Aliases: Msg

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Tags

Specifies a simple string that you can use to sort and filter messages that you have
added to the
information stream with Write-Information . This parameter works
similarly to the Tags
parameter in New-ModuleManifest .

Type: String[]

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

This cmdlet returns no output. It only writes to the information message stream.

Related Links
about_Output_Streams
about_Redirection
about_CommonParameters
about_Preference_Variables
about_Redirection
Write-Debug
Write-Host
Write-Information
Write-Progress
Write-Verbose
Write-Warning
Write-Output
Write-Output
Reference
Module: Microsoft.PowerShell.Utility

Writes the specified objects to the pipeline. If Write-Output is the last command in the
pipeline,
the objects are displayed in the console.

Syntax
PowerShell

Write-Output

[-InputObject] <PSObject[]>

[-NoEnumerate]

[<CommonParameters>]

Description
Writes the specified objects to the pipeline. If Write-Output is the last command in the
pipeline,
the objects are displayed in the console.

Write-Output sends objects to the primary pipeline, also known as the "output stream"
or the
"success pipeline." To send error objects to the error pipeline, use Write-Error .

This cmdlet is typically used in scripts to display strings and other objects on the
console. One of
the built-in aliases for Write-Output is echo and similar to other shells
that use echo . The
default behavior is to display the output at the end of a pipeline. In
PowerShell, it is generally
not necessary to use the cmdlet in instances where the output
is displayed by default. For example,
Get-Process | Write-Output is equivalent to Get-
Process . Or, echo "Home directory: $HOME" can
be written, "Home directory: $HOME" .

By default, Write-Output enumerates through collection objects. However, Write-Output


can also
be used to pass collections down the pipeline as a single object with the
NoEnumerate parameter.

Examples

Example 1: Get objects and write them to the console


In this example, the results of the Get-Process cmdlet are stored in the $P variable. The
Write-Output cmdlet displays the process objects in $P to the console.

PowerShell

$P = Get-Process

Write-Output $P

Example 2: Pass output to another cmdlet


This command pipes the "test output" string to the Get-Member cmdlet, which displays
the members
of the System.String class, demonstrating that the string was passed along
the pipeline.

PowerShell

Write-Output "test output" | Get-Member

Example 3: Suppress enumeration in output


This command adds the NoEnumerate parameter to treat a collection or array as a
single object
through the pipeline.

PowerShell

Write-Output 1,2,3 | Measure-Object

Count : 3

...

Write-Output 1,2,3 -NoEnumerate | Measure-Object

Count : 1

...

Parameters
-InputObject

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.
Type: PSObject[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-NoEnumerate

By default, the Write-Output cmdlet always enumerates its output. The


NoEnumerate parameter
suppresses the default behavior, and prevents Write-
Output from enumerating output. The
NoEnumerate parameter has no effect if the

command is wrapped in parentheses, because the


parentheses force enumeration.
For example, (Write-Output 1,2,3) still enumerates the array.

The NoEnumerate parameter is only useful within a pipeline. Trying to see the effects
of
NoEnumerate in the console is problematic because PowerShell adds Out-Default
to the end of
every command line, which results in enumeration. But if you pipe
Write-Output -NoEnumerate to
another cmdlet, the downstream cmdlet receives the
collection object, not the enumerated items of
the collection.

) Important

There is an issue with this switch in Windows PowerShell that is fixed in


PowerShell 6.2 and
above. When using NoEnumerate and explicitly using the
InputObject parameter, the command
still enumerates. To work around this,
pass the InputObject argument(s) positionally.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
PSObject
You can pipe objects to this cmdlet.

Outputs
PSObject

This cmdlet returns the objects that are submitted as input.

Notes
Windows PowerShell includes the following aliases for Write-Output :

echo

write

Related Links
about_Output_Streams
about_Redirection
Tee-Object
Write-Debug
Write-Error
Write-Host
Write-Information
Write-Progress
Write-Verbose
Write-Warning
Write-Progress
Reference
Module: Microsoft.PowerShell.Utility

Displays a progress bar within a PowerShell command window.

Syntax
PowerShell

Write-Progress

[-Activity] <String>

[[-Status] <String>]

[[-Id] <Int32>]

[-PercentComplete <Int32>]

[-SecondsRemaining <Int32>]

[-CurrentOperation <String>]
[-ParentId <Int32>]

[-Completed]

[-SourceId <Int32>]

[<CommonParameters>]

Description
The Write-Progress cmdlet displays a progress bar in a 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.

Examples

Example 1: Display the progress of a For loop


PowerShell

for ($i = 1; $i -le 100; $i++ ) {

Write-Progress -Activity "Search in Progress" -Status "$i% Complete:" -


PercentComplete $i

Start-Sleep -Milliseconds 250

This command displays the progress of a for loop that counts from 1 to 100.
The Write-Progress cmdlet 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: Display the progress of nested For loops


PowerShell

for($I = 0; $I -lt 10; $I++ ) {

$OuterLoopProgressParameters = @{

Activity = 'Updating'

Status = 'Progress->'

PercentComplete = $I * 10

CurrentOperation = 'OuterLoop'

Write-Progress @OuterLoopProgressParameters

for($j = 1; $j -lt 101; $j++ ) {

$InnerLoopProgressParameters = @{

ID = 1

Activity = 'Updating'

Status = 'Progress'

PercentComplete = $j
CurrentOperation = 'InnerLoop'

Write-Progress @InnerLoopProgressParameters

Start-Sleep -Milliseconds 25

Updating

Progress ->

[ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo]

OuterLoop

Updating

Progress

[oooooooooooooooooo ]

InnerLoop

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: Display the progress while searching for a
string
PowerShell

# Use Get-EventLog to get the events in the System log and store them in the
$Events variable.

$Events = Get-EventLog -LogName system

# Pipe the events to the ForEach-Object cmdlet.

$Events | ForEach-Object -Begin {

# In the Begin block, use Clear-Host to clear the screen.

Clear-Host

# Set the $i counter variable to zero.

$i = 0

# Set the $out variable to a empty string.

$out = ""

} -Process {

# In the Process script block search the message property of each


incoming object for "bios".

if($_.message -like "*bios*")

# Append the matching message to the out variable.

$out=$out + $_.Message

# Increment the $i counter variable which is used to create the progress


bar.

$i = $i+1

# Determine the completion percentage

$Completed = ($i/$Events.count) * 100

# Use Write-Progress to output a progress bar.

# The Activity and Status parameters create the first and second lines
of the progress bar

# heading, respectively.

Write-Progress -Activity "Searching Events" -Status "Progress:" -


PercentComplete $Completed

} -End {

# Display the matching messages using the out variable.

$out

This command displays the progress of a command to find the string "bios" in the
System event log.

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.

Example 4: Display progress for each level of a nested


process
PowerShell

foreach ( $i in 1..10 ) {

Write-Progress -Id 0 "Step $i"

foreach ( $j in 1..10 ) {

Write-Progress -Id 1 -ParentId 0 "Step $i - Substep $j"

foreach ( $k in 1..10 ) {

Write-Progress -Id 2 -ParentId 1 "Step $i - Substep $j - iteration


$k"

Start-Sleep -Milliseconds 150

Step 1

Processing

Step 1 - Substep 2

Processing

Step 1 - Substep 2 - Iteration 3

Processing

In this example you can use the ParentId parameter to have indented output to show
parent-child
relationships in the progress of each step.

Parameters
-Activity

Specifies the first line of text in the heading above the status bar. This text describes
the
activity whose progress is being reported.

Type: String

Position: 0

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.

Type: SwitchParameter
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-CurrentOperation

Specifies the line of text below the progress bar. This text describes the operation
that's
currently taking place.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Id

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 don't have
different IDs, they're superimposed instead of being
displayed in a series. Negative values aren't
allowed.

Type: Int32

Position: 2

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ParentId

Specifies the parent activity of the current activity. Use the value -1 if the current
activity has
no parent activity.

Type: Int32

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-PercentComplete

Specifies the percentage of the activity that's completed. Use the value -1 if the
percentage
complete is unknown or not applicable.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SecondsRemaining

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.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SourceId

Specifies the source of the record. You can use this in place of Id but can't be used
with
other parameters like ParentId.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-Status

Specifies the second line of text in the heading above the status bar. This text
describes current
state of the activity.

Type: String

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
If the progress bar doesn't appear, check the value of the $ProgressPreference variable.
If the
value is set to SilentlyContinue , the progress bar isn't displayed. For more
information about
PowerShell preferences, see
about_Preference_Variables.

The parameters of the cmdlet correspond to the properties of the


System.Management.Automation.ProgressRecord class. For more information, see
ProgressRecord Class.

Related Links
Write-Debug
Write-Error
Write-Host
Write-Output
Write-Progress
Write-Verbose
Write-Warning
Write-Verbose
Reference
Module: Microsoft.PowerShell.Utility

Writes text to the verbose message stream.

Syntax
PowerShell

Write-Verbose

[-Message] <String>

[<CommonParameters>]

Description
The Write-Verbose cmdlet writes text to the verbose message stream in PowerShell.
Typically, the
verbose message stream is used to deliver more in depth information
about command processing.

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.

Examples

Example 1: Write a status message


PowerShell

Write-Verbose -Message "Searching the Application Event Log."

Write-Verbose -Message "Searching the Application Event Log." -Verbose

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: Set $VerbosePreference and write a status
message
PowerShell

$VerbosePreference = "Continue"

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.

Parameters
-Message

Specifies the message to display. This parameter is required. You can also pipe a
message string to
Write-Verbose .

Type: String

Aliases: Msg

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

Inputs
String

You can pipe a string that contains the message to this cmdlet.

Outputs
None
This cmdlet returns no output. It only writes to the verbose message stream.

Notes
Verbose messages are returned only when the command uses the Verbose
common parameter. For
more information, see about_CommonParameters .
In Windows PowerShell background jobs and remote commands, the
$VerbosePreference variable in
the job session and remote session determine
whether the verbose message is displayed by default.
For more information about
the $VerbosePreference variable, see
about_Preference_Variables.

Related Links
about_Output_Streams
about_Redirection
Write-Debug
Write-Error
Write-Host
Write-Information
Write-Output
Write-Progress
Write-Warning
Write-Warning
Reference
Module: Microsoft.PowerShell.Utility

Writes a warning message.

Syntax
PowerShell

Write-Warning

[-Message] <String>

[<CommonParameters>]

Description
The Write-Warning cmdlet writes a warning message to the 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.

Examples

Example 1: Write a warning message


This command displays the message "WARNING: This is only a test warning."

PowerShell

Write-Warning "This is only a test warning."

Example 2: Pass a string to Write-Warning


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

PowerShell
$w = "This is only a test warning."

$w | Write-Warning

Example 3: Set the $WarningPreference variable and write


a warning
This example shows the effect of the value of the $WarningPreference variable on a
Write-Warning
command.

PowerShell

PS> $WarningPreference

Continue

PS> Write-Warning "This is only a test warning."

This is only a test warning.

PS> $WarningPreference = "SilentlyContinue"

PS> Write-Warning "This is only a test warning."

PS> $WarningPreference = "Stop"

PS> Write-Warning "This is only a test warning."

WARNING: This is only a test warning.

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

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: Set the WarningAction parameter and write a


warning
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
PowerShell responds to warnings resulting from that command. The
WarningAction common parameter
overrides the value of the $WarningPreference only
for that particular command.

PowerShell

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"):

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.

Parameters
-Message

Specifies the warning message.

Type: String

Aliases: Msg

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

Inputs
String

You can pipe a string that contains the warning to this cmdlet.

Outputs
None

This cmdlet returns no output. It writes only to the warning stream.

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 lists the valid values.

Related Links
about_Output_Streams
about_Redirection
Write-Debug
Write-Error
Write-Host
Write-Information
Write-Output
Write-Progress
Write-Verbose
Microsoft.WSMan.Management
Reference

This section contains the help topics for the cmdlets that are installed with PowerShell
Microsoft.WSMan.Management module. The WSMan module contains cmdlets and
providers that manage the
WS-Management protocol in PowerShell.

Microsoft.WSMan.Management
Connect-WSMan Connects to the WinRM service on a remote computer.

Disable-WSManCredSSP Disables CredSSP authentication on a computer.

Disconnect-WSMan Disconnects the client from the WinRM service on a remote


computer.

Enable-WSManCredSSP Enables Credential Security Support Provider (CredSSP)


authentication on a computer.

Get-WSManCredSSP Gets the Credential Security Support 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 session option hash table to use as input parameters for
WS-Management cmdlets.

Remove-WSManInstance Deletes a management resource instance.

Set-WSManInstance Modifies the management information that is related to a


resource.

Set-WSManQuickConfig Configures the local computer for remote management.

Test-WSMan Tests whether the WinRM service is running on a local or remote


computer.
about_WS-Management_Cmdlets
Article • 09/19/2022 • 3 minutes to read

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 (WSMan)
The WSMan 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 WSMan 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 WSMan 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
Windows
documentation.

Windows Remote Management

About Windows Remote Management

Installation and Configuration for Windows Remote Management

Windows Remote Management Architecture

WS-Management Protocol

Windows Remote Management and WMI

Resource URIs

Remote Hardware Management

Events

See also
Connect-WSMan
Test-WSMan
Invoke-WSManAction
Disconnect-WSMan
Disable-WSManCredSSP
Enable-WSManCredSSP
Get-WSManCredSSP
Get-WSManInstance
New-WSManInstance
Remove-WSManInstance
Set-WSManInstance
Set-WSManQuickConfig
about_WSMan_Provider
Article • 09/19/2022 • 12 minutes to read

Provider name
WSMan

Drives
WSMan:

Short description
Provides access to Web Services for Management (WS-Management) configuration
information.

Detailed description
The WSMan provider for PowerShell lets you add, change, clear, and
delete WS-
Management configuration data on local or remote computers.

The WSMan provider exposes a PowerShell drive with a directory


structure that
corresponds to a logical grouping of WS-Management configuration
settings. These
groupings are known as containers.

Beginning in Windows PowerShell 3.0, the WSMan provider has been


updated to
support new properties for session configurations, such as
OutputBufferingMode. The
session configurations appear as items in the
Plugin directory of the WSMan: drive and
the properties appear as items in
each session configuration.

The WSMan provider supports the following cmdlets, which are covered
in this article.

Get-Location
Set-Location
Get-Item
Get-ChildItem
New-Item
Remove-Item
7 Note

You can use commands in the WSMan: drive to change the values of the new
properties. However, you cannot use the WSMan: drive in PowerShell 2.0
to change
properties that are introduced in Windows PowerShell 3.0.
Although no error is
generated, the commands are not effective To change these
settings, use the
WSMan drive in Windows PowerShell 3.0.

Organization of the WSMan: Drive


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.

7 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, PowerShell provides three plug-ins:
The Event Forwarding plug-in.
The Microsoft.PowerShell plug-in.
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 WSMan Provider


The directory hierarchy of the WSMan 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 WSMan 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>

Navigating the WSMan: Drive


This command uses the Set-Location cmdlet to change the current location to
the
WSMan: drive.

PowerShell

Set-Location WSMan:

To return to a file system drive, type the drive name. For example, type.
PowerShell

Set-Location C:

Navigating to a remote system store location


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.

PowerShell

Set-Location -Path WSMan:\SERVER01

7 Note

The above command assume that a connection to the remote system already
exists.

Displaying the Contents of the WSMan: Drive


This command uses the Get-Childitem cmdlet to display the WS-Management stores
in
the Localhost store location.

PowerShell

Get-ChildItem -path WSMan:\Localhost

If you are in the WSMan: drive, you can omit the drive name.

This command uses the Get-Childitem cmdlet to display the WS-Management


stores in
the remote computer "SERVER01" store location.

PowerShell

Get-ChildItem -path WSMan:\SERVER01

7 Note
The above command assume that a connection to the remote system already
exists.

Setting the value of items in the WSMAN: drive


You can use the Set-Item cmdlet to change configuration settings in the
WSMAN drive.
The following example sets the TrustedHosts value to
accept all hosts with the suffix
"contoso.com".

PowerShell

# You do not need to specify the -Path parameter name when using Set-Item.

PS WSMAN:\localhost\Client> Set-Item .\TrustedHosts -Value "*.contoso.com"

The Set-Item cmdlet supports an additional parameter -Concatenate that


appends a
value instead of changing it. The following example will append a
new value
"*.domain2.com" to the old value stored in TrustedHost:

PowerShell

Set-Item WSMAN:\localhost\Client\TrustedHosts *.domain2.com -Concatenate

Creating items in the WSMAN: drive

Creating a new listener


The New-Item cmdlet creates items within a provider drive. Each provider
has different
item types that you can create. In the WSMAN: drive, you can
create Listeners which you
configure to receive and respond to remote
requests. The following command creates a
new HTTP listener using the New-Item
cmdlet.

PowerShell

New-Item -Path WSMan:\localhost\Listener -Address * -Transport HTTP -force

Creating a new plug-in


This command creates (registers) a plug-in for the WS-Management service.
PowerShell

New-Item -Path WSMan:\localhost\Plugin `

-Plugin TestPlugin `

-FileName %systemroot%\system32\WsmWmiPl.dll `

-Resource http://schemas.dmtf.org/wbem/wscim/2/cim-schema `

-SDKVersion 1 `

-Capability "Get","Put","Invoke","Enumerate" `

-XMLRenderingType text

Creating a new resource entry


This command creates a resource entry in the Resources directory of
a TestPlugin. This
command assumes that a TestPlugin has been created using
a separate command.

PowerShell

New-Item -Path WSMan:\localhost\Plugin\TestPlugin\Resources `

-ResourceUri http://schemas.dmtf.org/wbem/wscim/3/cim-schema `

-Capability "Enumerate"

Creating a new security entry for a resource


This command creates a security entry in the Security directory of
Resource_5967683 (a
specific resource). This command assumes that the resource
entry has been created
using a separate command.

PowerShell

$path = "WSMan:\localhost\Plugin\TestPlugin\Resources\Resource_5967683"

New-Item -Path $path\Security `

-Sddl "O:NSG:BAD:P(A;;GA;;;BA)S:P(AU;FA;GA;;;WD)(AU;SA;GWGX;;;WD)"

Creating a new Client Certificate


This command creates ClientCertificate entry that can be used by the
WS-Management
client. The new ClientCertificate will show up under the
ClientCertificate directory as
"ClientCertificate_1234567890". All of the
parameters are mandatory. The Issuer needs
to be thumbprint of the issuers
certificate.

PowerShell
$cred = Get-Credential

New-Item -Path WSMan:\localhost\ClientCertificate `

-Issuer 1b3fd224d66c6413fe20d21e38b304226d192dfe `

-URI wmicimv2/* `

-Credential $cred;

Creating a new Initialization Parameter


This command creates an Initialization parameter named "testparametername"
in the
"InitializationParameters" directory. This command assumes that the
"TestPlugin" has
been created using a separate command.

PowerShell

New-Item -Path WSMan:\localhost\Plugin\TestPlugin\InitializationParameters `

-ParamName testparametername `

-ParamValue testparametervalue

Dynamic parameters
Dynamic parameters are cmdlet parameters that are added by a 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 adapters.)
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 an adapter.
For example:
MAC:32-a3-58-90-be-cc.

7 Note

The Address value is set when creating a Listener.

Cmdlets supported
New-Item

Capability <Enumeration>
When working with Plug-ins this parameter 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. You can specify
any valid attributes for a given
operation, if the operation supports it.

These attributes include SupportsFiltering and SupportsFragment.

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 for Create operations and
should be
set to "False".

7 Note

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 for Delete operations and
should be
set to "False".

7 Note

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

7 Note

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 for Get operations and
should be set
to "False".

7 Note

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

7 Note

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 for Put operations and
should be set
to "False".

7 Note

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 for Subscribe operations and
should
be set to "False".

7 Note

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 for Shell operations and
should be
set to "False".

7 Note

This operation is not valid for a URI if ANY other operation is also
supported.

7 Note

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

New-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 PowerShell Cert: drive.

Cmdlets supported

New-Item

Enabled <Boolean>
Specifies whether the listener is enabled or disabled. The default is True.

Cmdlets Supported
New-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

New-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
New-Item

Issuer <String>
Specifies the name of the certification authority that issued the certificate.

Cmdlets Supported

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

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

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

New-Item

Resource <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
New-Item

SDKVersion <String>
Specifies the version of the WS-Management plug-in SDK. The only valid value is
1.

Cmdlets Supported

New-Item

Subject <String>
Specifies the entity that is identified by the certificate.

Cmdlets Supported
New-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
New-Item

URI <String>
Identifies the URI for which access is authorized based on the value of the
Sddl
parameter.

Cmdlets Supported

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

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

New-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
New-Item

Using the pipeline


Provider cmdlets accept pipeline input. You can use the pipeline to simplify
task by
sending provider data from one cmdlet to another provider cmdlet.
To read more about
how to use the pipeline with provider cmdlets, see the
cmdlet references provided
throughout this article.

Getting help
Beginning in Windows PowerShell 3.0, you can get customized help topics for
provider
cmdlets that explain how those cmdlets behave in a file system drive.

To get the help topics that are customized for the file system drive, run a
Get-Help
command in a file
system drive or use the -Path parameter of
Get-Help to specify a file
system drive.

PowerShell

Get-Help Get-ChildItem

PowerShell

Get-Help Get-ChildItem -Path wsman:

See also
about_Providers
Connect-WSMan
Reference
Module: Microsoft.WSMan.Management

Connects to the WinRM service on a remote computer.

Syntax
PowerShell

Connect-WSMan

[-ApplicationName <String>]

[[-ComputerName] <String>]
[-OptionSet <Hashtable>]

[-Port <Int32>]

[-SessionOption <SessionOption>]

[-UseSSL]

[-Credential <PSCredential>]

[-Authentication <AuthenticationMechanism>]

[-CertificateThumbprint <String>]

[<CommonParameters>]

PowerShell

Connect-WSMan

[-ConnectionURI <Uri>]

[-OptionSet <Hashtable>]

[-Port <Int32>]

[-SessionOption <SessionOption>]

[-Credential <PSCredential>]

[-Authentication <AuthenticationMechanism>]

[-CertificateThumbprint <String>]

[<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 in
the context of the WSMan
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 WSMan provider. The
remote computer
appears in the root directory of the WSMan provider.
Explicit credentials are required when the client and server computers are in different
domains or
workgroups.

For information about how to disconnect from the WinRM service on a remote
computer, see the
Disconnect-WSMan cmdlet.

Examples

Example 1: Connect to a remote computer


PowerShell

PS C:\> Connect-WSMan -ComputerName "server01"

PS C:\> cd wsman:

PS WSMan:\>

PS WSMan:\> dir

WSManConfig: Microsoft.WSMan.Management\WSMan::WSMan

ComputerName Type

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

localhost Container

server01 Container

This command creates a connection to the remote server01 computer.

The Connect-WSMan cmdlet is generally used in the context of the WSMan 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
WSMan provider. Those connections appear in
the ComputerName list.

Example 2: Connect to a remote computer by using


Administrator credentials
PowerShell

PS C:\> $cred = Get-Credential Administrator

PS C:\> Connect-WSMan -ComputerName "server01" -Credential $cred

PS C:\> cd wsman:

PS WSMan:\>

PS WSMan:\> dir

WSManConfig: Microsoft.WSMan.Management\WSMan::WSMan

ComputerName Type

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

localhost Container

server01 Container

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. Get-Credential prompts you for a password
of username and
password through 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 by
using the
Administrator credentials.

Example 3: Connect to a remote computer over a


specified port
PowerShell

PS C:\> Connect-WSMan -ComputerName "server01" -Port 80

PS C:\> cd wsman:

PS WSMan:\>

PS WSMan:\> dir

WSManConfig: Microsoft.WSMan.Management\WSMan::WSMan

ComputerName Type

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

localhost Container

server01 Container

This command creates a connection to the remote server01 computer over port 80.

Example 4: Connect to a remote computer by using


connection options
PowerShell

PS C:\> $a = New-WSManSessionOption -OperationTimeout 30000

PS C:\> Connect-WSMan -ComputerName "server01" -SessionOption $a

PS C:\> cd wsman:

PS WSMan:\> dir

WSManConfig: Microsoft.WSMan.Management\WSMan::WSMan

ComputerName Type

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

localhost Container

server01 Container

This example 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 New-WSManSessionOption 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.

Parameters
-ApplicationName

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

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-Authentication

Specifies the authentication mechanism to be used at the server. The acceptable


values for this
parameter 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 for
negotiation to determine whether the
Kerberos protocol or NTLM is used.
CredSSP - Use Credential Security Support Provider (CredSSP) authentication,

which lets the user


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.

U Caution

CredSSP delegates the user 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.

Type: Microsoft.WSMan.Management.AuthenticationMechanism

Aliases: auth, am

Accepted values: None, Default, Digest, Negotiate, Basic, Kerberos,


ClientCertificate, Credssp

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-CertificateThumbprint

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.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ComputerName

Specifies the computer against which 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.

Type: String

Aliases: cn

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ConnectionURI

Specifies the connection endpoint. The format of this string is as follows:

<Transport>://<Server>:<Port>/<ApplicationName>
The following string is a correctly formatted value for this parameter:

http://Server01:8080/WSMAN

The URI must be fully qualified.

Type: Uri

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Credential

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, this cmdlet prompts you for a

password.

Type: PSCredential

Aliases: cred, c

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-OptionSet

Specifies a set of switches to a service to modify or refine the nature of the request.
These
resemble 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}
Type: Hashtable

Aliases: os

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Port

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

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SessionOption

Specifies 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, type Get-Help New-
WSManSessionOption .

Type: Microsoft.WSMan.Management.SessionOption

Aliases: so

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-UseSSL

Specifies that the Secure Sockets Layer (SSL) protocol is 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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

This cmdlet returns no 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.

Related Links
Disable-WSManCredSSP
Disconnect-WSMan
Enable-WSManCredSSP
Get-WSManCredSSP
Get-WSManInstance
Invoke-WSManAction
New-WSManInstance
New-WSManSessionOption
Remove-WSManInstance
Set-WSManInstance
Set-WSManQuickConfig
Test-WSMan
Disable-WSManCredSSP
Reference
Module: Microsoft.WSMan.Management

Disables CredSSP authentication on a computer.

Syntax
PowerShell

Disable-WSManCredSSP

[-Role] <String>

[<CommonParameters>]

Description
The Disable-WSManCredSSP cmdlet disables Credential Security Support Provider
(CredSSP)
authentication on a client or on a server computer. When CredSSP
authentication is used, the user
credentials are passed to a remote computer to be
authenticated.

Use this cmdlet to disable CredSSP on the client by specifying Client in the Role
parameter.
This cmdlet performs the following actions:

Disables CredSSP on the client. This cmdlet sets the WS-Management setting
<localhost|computername>\Client\Auth\CredSSP to false.

Removes any WSMan/* setting from the Windows CredSSP policy


AllowFreshCredentials on the
client.

Use this cmdlet to disable CredSSP on the server by specifying Server in Role. This
cmdlet
performs the following action:

Disables CredSSP on the server. This cmdlet sets the WS-Management setting
<localhost|computername>\Client\Auth\CredSSP to false.

U Caution

CredSSP authentication delegates the user 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.

Examples

Example 1: Disable CredSSP on a client


PowerShell

Disable-WSManCredSSP -Role Client

This command disables CredSSP on the client, which prevents delegation to servers.

Example 2: Disable CredSSP on a server


PowerShell

Disable-WSManCredSSP -Role Server

This command disables CredSSP on the server, which prevents delegation from clients.

Parameters
-Role

Specifies whether to disable CredSSP as a client or as a server. The acceptable values


for this
parameter are: Client and Server.

If you specify Client, this cmdlet performs the following actions:

Disables CredSSP on the client. This cmdlet sets WS-Management setting


<localhost|computername>\Client\Auth\CredSSP to false.

Removes any WSMan/* setting from the Windows CredSSP policy


AllowFreshCredentials on the
client.

If you specify Server, this cmdlet performs the following action:

Disables CredSSP on the server. This cmdlet sets the WS-Management setting
<localhost|computername>\Client\Auth\CredSSP to false.
Type: String

Accepted values: Client, Server

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
To enable CredSSP authentication, use the Enable-WSManCredSSP cmdlet.

Related Links
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
Reference
Module: Microsoft.WSMan.Management

Disconnects the client from the WinRM service on a remote computer.

Syntax
PowerShell

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

For more information about how to connect to the WinRM service on a remote
computer, see
Connect-WSMan .

Examples

Example 1: Delete a connection to a remote computer


PowerShell

PS C:\> Disconnect-WSMan -computer server01

PS C:\> cd WSMan:

PS WSMan:\> dir

WSManConfig: Microsoft.WSMan.Management\WSMan::WSMan

ComputerName Type

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

localhost Container

This command deletes the connection to the remote computer named server01.

This cmdlet is generally used within the context of the WSMan provider to disconnect
from a remote
computer, in this case the server01 computer. However, you can also use
Disconnect-WSMan to remove
connections to remote computers before you change to
the WSMan provider. Those connections do not
appear in the ComputerName list.

Parameters
-ComputerName

Specifies the computer against which 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.

You cannot disconnect from the local host. That is, you cannot disconnect the default
connection to
the local computer. However, if you create a separate connection to
the local computer, for example,
by using the computer name.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

This cmdlet returns no output.

Related Links
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-WSManCredSSP
Reference
Module: Microsoft.WSMan.Management

Enables Credential Security Support Provider (CredSSP) authentication on a computer.

Syntax
PowerShell

Enable-WSManCredSSP

[[-DelegateComputer] <String[]>]

[-Force]

[-Role] <String>

[<CommonParameters>]

Description
The Enable-WSManCredSSP cmdlet enables CredSSP authentication on a client or on a
server computer.
When CredSSP authentication is used, the user credentials are passed
to a remote computer to be
authenticated. This type of authentication is designed for
commands that create a remote session
from another remote session. For example, if
you want to run a background job on a remote computer,
use this kind of
authentication.

Enable-WSManCredSSP can enable CredSSP on a Client or a Server. To enable CredSSP on

a
client, specify Client in the Role parameter. Clients delegate explicit credentials to a
server when server authentication is achieved. To enable CredSSP on a server, specify
Server in
the Role parameter. A server acts as a delegate for clients. For more details,
see Role in
the Parameters section.

U Caution

CredSSP authentication delegates the user 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.
Examples

Example 1: Delegate client credentials


This example allows the client credentials to be delegated to a computer by using the
fully
qualified domain name.

PowerShell

Enable-WSManCredSSP -Role "Client" -DelegateComputer "Server02.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

Example 2: Delegate client credentials to all computers in


a domain
This example allows the client credentials to be delegated to all the computers in the
fabrikam.com domain. The asterisk ( * ) wildcard specifies all computers.

7 Note

Using wildcards with the DelegateComputer parameter can enable CredSSP on


more computers than
necessary.

PowerShell

Enable-WSManCredSSP -Role "Client" -DelegateComputer "*.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
Example 3: Delegate client credentials to multiple
computers
This example allows the client credentials to be delegated to multiple computers.

PowerShell

$servers = "server02.fabrikam.com", "server03.fabrikam.com",


"server04.fabrikam.com"

Enable-WSManCredSSP -Role "Client" -DelegateComputer $servers

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

The $servers variable contains a list of server names. Enable-WSManCredSSP uses the
Role
parameter to specify the Client role. The DelegateComputer gets the computer
names from the
$servers variable.

Example 4: Allow a computer to act as a delegate


This example 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 its
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. This example
sets the CredSSP
item in the Service node of WSMan to true.

PowerShell

Enable-WSManCredSSP -Role "Server"

Example 5: Allow a computer to act as a delegate by


using Set-Item
This example allows a computer to act as a delegate for another computer. The Enable-
WSManCredSSP
commands, 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.

PowerShell

Connect-WSMan -ComputerName "server02"

Set-Item -Path "WSMan:\server02\service\auth\credSSP" -Value $True

Connect-WSMan creates a connection to the remote computer, server02. Set-Item uses


the Path
parameter to specify the WSMan provider's location. The Value parameter sets
the Service
setting to true.

Parameters
-DelegateComputer

Specifies servers to which client credentials are delegated. The best practice is to use
fully
qualified domain names.

Wildcards are accepted, but can enable CredSSP on more computers than necessary.

If the Role parameter is Client, you must specify this parameter. If Role is Server,
don't specify this parameter.

Type: String[]

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: True

-Force

Forces the command to run without asking for user confirmation.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False


Accept wildcard characters: False

-Role

Specifies whether to enable CredSSP as a client or as a server. The acceptable values


for this
parameter are: Client and Server.

If you specify Client, the following actions are performed. These settings allow the
client to
delegate explicit credentials to a server when server authentication is
achieved.

Enables CredSSP on the client.


Sets the WS-Management setting \
<localhost|computername\>\Client\Auth\CredSSP to true.

Sets the Windows CredSSP policy AllowFreshCredentials to WSMan/Delegate


on the client.

If you specify Server, the following actions are performed. This policy setting allows
the
server to act as a delegate for clients.

Enables CredSSP on the server.


Sets the WS-Management setting \
<localhost|computername\>\Service\Auth\CredSSP to true.

Type: String

Accepted values: Client, Server

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
XmlElement

If CredSSP authentication is successfully enabled, this cmdlet returns an XMLElement


object.

Notes
To disable CredSSP authentication, use the Disable-WSManCredSSP cmdlet.

Related Links
Connect-WSMan
Disable-WSManCredSSP
Disconnect-WSMan
Get-WSManCredSSP
Get-WSManInstance
Invoke-WSManAction
New-WSManInstance
New-WSManSessionOption
Remove-WSManInstance
Set-WSManInstance
Set-WSManQuickConfig
Test-WSMan
Get-WSManCredSSP
Reference
Module: Microsoft.WSMan.Management

Gets the Credential Security Support Provider-related configuration for the client.

Syntax
PowerShell

Get-WSManCredSSP []

Description
The Get-WSManCredSSP cmdlet gets the Credential Security Support Provider-related
configuration of
the client and the server. The output indicates whether Credential
Security Support Provider
(CredSSP) authentication is enabled or disabled. This cmdlet
also displays configuration information
for the AllowFreshCredentials policy of CredSSP.

When you use CredSSP authentication, the user credentials are passed to a remote
computer to be
authenticated. This type of authentication is designed for commands
that create a remote session
from another remote session. For example, if you want to
run a background job on a remote computer,
use this kind of authentication.

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

U Caution

CredSSP authentication delegates the user 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.
Examples

Example 1: Display CredSSP configuration


PowerShell

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.

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
String

This cmdlet returns a message string describing the configuration state for CredSSP.

Notes
To disable CredSSP authentication, use the Disable-WSManCredSSP cmdlet. To enable
CredSSP
authentication, use the Enable-WSManCredSSP cmdlet.

Related Links
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
Reference
Module: Microsoft.WSMan.Management

Displays management information for a resource instance specified by a Resource URI.

Syntax
PowerShell

Get-WSManInstance

[-ApplicationName <String>]

[-ComputerName <String>]

[-ConnectionURI <Uri>]

[-Dialect <Uri>]

[-Fragment <String>]

[-OptionSet <Hashtable>]

[-Port <Int32>]

[-ResourceURI] <Uri>

[-SelectorSet <Hashtable>]

[-SessionOption <SessionOption>]

[-UseSSL]

[-Credential <PSCredential>]

[-Authentication <AuthenticationMechanism>]

[-CertificateThumbprint <String>]

[<CommonParameters>]

PowerShell

Get-WSManInstance

[-ApplicationName <String>]

[-BasePropertiesOnly]

[-ComputerName <String>]

[-ConnectionURI <Uri>]

[-Dialect <Uri>]

[-Enumerate]

[-Filter <String>]

[-OptionSet <Hashtable>]

[-Port <Int32>]

[-Associations]

[-ResourceURI] <Uri>

[-ReturnType <String>]

[-SessionOption <SessionOption>]

[-Shallow]

[-UseSSL]

[-Credential <PSCredential>]

[-Authentication <AuthenticationMechanism>]

[-CertificateThumbprint <String>]

[<CommonParameters>]

Description
The Get-WSManInstance cmdlet retrieves an instance of a management resource that is
specified by a
resource Uniform Resource Identifier (URI). The information that is
retrieved can be a complex XML
information set, which is an object, or a simple value.
This cmdlet is the equivalent to the
standard Web Services for Management (WS-
Management) Get command.

This cmdlet uses the WS-Management connection/transport layer to retrieve


information.

Examples

Example 1: Get all information from WMI


PowerShell

Get-WSManInstance -ResourceURI wmicimv2/win32_service -SelectorSet


@{name="winrm"} -ComputerName "Server01"

This command returns all of the information that Windows Management


Instrumentation (WMI) exposes
about the WinRM service on the remote server01
computer.

Example 2: Get the status of the Spooler service


PowerShell

Get-WSManInstance -ResourceURI wmicimv2/win32_service -SelectorSet


@{name="spooler"} -Fragment Status -ComputerName "Server01"

This command returns only the status of the Spooler service on the remote server01
computer.

Example 3: Get endpoint references for all services


PowerShell
Get-WSManInstance -Enumerate -ResourceURI wmicimv2/win32_service -ReturnType
EPR

This command returns endpoint references that correspond to all the services on the
local computer.

Example 4: Get services that meet specified criteria


PowerShell

Get-WSManInstance -Enumerate -ResourceURI wmicimv2/* -Filter "select * from


win32_service where StartMode = 'Auto' and State = 'Stopped'" -ComputerName
"Server01"

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 5: Get listener configuration that matches


criteria on the local computer
PowerShell

Get-WSManInstance -ResourceURI winrm/config/listener -SelectorSet


@{Address="*";Transport="http"}

This command lists the WS-Management listener configuration on the local computer
for the listener
that matches the criteria in the selector set.

Example 6: Get listener configuration that matches


criteria on a remote computer
PowerShell

Get-WSManInstance -ResourceURI winrm/config/listener -SelectorSet


@{Address="*";Transport="http"} -ComputerName "Server01"

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 7: Get associated instances related to a specified
instance
PowerShell

Get-WSManInstance -Enumerate -Dialect Association -Filter "


{Object=win32_service?name=winrm}" -ResourceURI wmicimv2/*

This command gets the associated instances that are related to the specified instance
(winrm).

You must enclose the filter in quotation marks, as shown in the example.

Example 8: Get association instances related to a


specified instance
PowerShell

Get-WSManInstance -Enumerate -Dialect Association -Associations -Filter "


{Object=win32_service?name=winrm}" -ResourceURI wmicimv2/*

This command gets association instances that are related to the specified instance
(winrm). Because
the Dialect value is association and the Associations parameter is
used, this command
returns association instances, not associated instances.

You must enclose the filter in quotation marks, as shown in the example.

Parameters
-ApplicationName

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 if many computers
establish remote connections to one computer that
is running PowerShell. In this
case, IIS hosts WS-Management for efficiency.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Associations

Indicates that this cmdlet gets association instances, not associated instances. You
can use this
parameter only when the Dialect parameter has a value of Association.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Authentication

Specifies the authentication mechanism to be used at the server. The acceptable


values for this
parameter 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 for
negotiation to determine whether the
Kerberos protocol or NTLM is used.
CredSSP - Use Credential Security Support Provider (CredSSP) authentication,

which lets the user


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.

U Caution

CredSSP delegates the user 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.

Type: Microsoft.WSMan.Management.AuthenticationMechanism

Aliases: auth, am

Accepted values: None, Default, Digest, Negotiate, Basic, Kerberos,


ClientCertificate, Credssp

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-BasePropertiesOnly

Indicates that this cmdlet 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.

Type: SwitchParameter

Aliases: UBPO, Base

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

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


PowerShell
Cert: drive.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ComputerName

Specifies the computer against which 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.

Type: String

Aliases: CN

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ConnectionURI

Specifies the connection endpoint. The format of this string is as follows:

<Transport>://<Server>:<Port>/<ApplicationName>

The following string is a correctly formatted value for this parameter:


http://Server01:8080/WSMAN

The URI must be fully qualified.

Type: Uri

Aliases: CURI, CU

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Credential

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, this cmdlet prompts you for a
password.

Type: PSCredential

Aliases: cred, c

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Dialect

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
Type: Uri

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Enumerate

Indicates that this cmdlet returns all of the instances of a management resource.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Filter

Specifies the filter expression for the enumeration. If you specify this parameter, you
must also
specify Dialect.

The valid values of this parameter depend on the dialect that is specified in Dialect.
For
example, if Dialect is 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 Dialect is Association, Filter 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\]}

Type: String

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-Fragment

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 the
following:

-Fragment Status

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-OptionSet

Specifies a set of switches to a service to modify or refine the nature of the request.
These
resemble 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}

Type: Hashtable

Aliases: OS

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

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

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ResourceURI

Specifies the URI of the resource class or instance. The URI identifies a specific type
of resource,
such as disks or processes, on a computer.

A URI consists of a prefix and a path of 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

Type: Uri

Aliases: RURI

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-ReturnType

Specifies the type of data to be returned. The acceptable values for this parameter
are:
Object

EPR
ObjectAndEPR

The default value is Object .

If you specify Object or do not specify this parameter, this cmdlet returns only
objects. If you
specify endpoint reference (EPR) this cmdlet returns only the endpoint
references of the objects.
Endpoint references contain information about the
resource URI and the selectors for the instance.
If you specify ObjectAndEPR , this
cmdlet returns both the object and its associated endpoint
references.

Type: String

Aliases: RT

Accepted values: object, epr, objectandepr

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SelectorSet

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"}

Type: Hashtable

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SessionOption
Specifies 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, type Get-Help New-
WSManSessionOption .

Type: Microsoft.WSMan.Management.SessionOption

Aliases: SO

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Shallow

Indicates that this cmdlet returns only instances of the base class that is specified in
the
resource URI. If you do not specify this parameter, this cmdlet returns instances
of the base class
that is specified in the URI and in all its derived classes.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-UseSSL

Specifies that the Secure Sockets Layer (SSL) protocol is 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.

Type: SwitchParameter

Aliases: SSL
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
XmlElement

This cmdlet returns an XMLElement object.

Related Links
Connect-WSMan
Disable-WSManCredSSP
Disconnect-WSMan
Enable-WSManCredSSP
Get-WSManCredSSP
Invoke-WSManAction
New-WSManInstance
New-WSManSessionOption
Remove-WSManInstance
Set-WSManInstance
Set-WSManQuickConfig
Test-WSMan
Invoke-WSManAction
Reference
Module: Microsoft.WSMan.Management

Invokes an action on the object that is specified by the Resource URI and by the
selectors.

Syntax
PowerShell

Invoke-WSManAction

[-Action] <String>

[-ConnectionURI <Uri>]

[-FilePath <String>]

[-OptionSet <Hashtable>]

[[-SelectorSet] <Hashtable>]

[-SessionOption <SessionOption>]

[-ValueSet <Hashtable>]

[-ResourceURI] <Uri>

[-Credential <PSCredential>]

[-Authentication <AuthenticationMechanism>]

[-CertificateThumbprint <String>]

[<CommonParameters>]

PowerShell

Invoke-WSManAction

[-Action] <String>

[-ApplicationName <String>]
[-ComputerName <String>]

[-FilePath <String>]

[-OptionSet <Hashtable>]

[-Port <Int32>]

[[-SelectorSet] <Hashtable>]

[-SessionOption <SessionOption>]

[-UseSSL]

[-ValueSet <Hashtable>]

[-ResourceURI] <Uri>

[-Credential <PSCredential>]

[-Authentication <AuthenticationMechanism>]

[-CertificateThumbprint <String>]

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

Examples

Example 1: Invoke a method


PowerShell

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

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: Invoke a method


PowerShell

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

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: Invoke a method with specified parameter


values
PowerShell

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

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: Invoke a method on a remote computer


PowerShell

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

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.

Parameters
-Action

Specifies the method to run on the management object specified by the


ResourceURI and selectors.

Type: String

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ApplicationName

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.

Type: String

Position: Named

Default value: Wsman

Accept pipeline input: False


Accept wildcard characters: False

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

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

Type: Microsoft.WSMan.Management.AuthenticationMechanism

Aliases: auth, am

Accepted values: None, Default, Digest, Negotiate, Basic, Kerberos,


ClientCertificate, Credssp

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-CertificateThumbprint

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.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ComputerName

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.

Type: String

Aliases: cn

Position: Named

Default value: Localhost

Accept pipeline input: False

Accept wildcard characters: False

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

Type: Uri

Aliases: CURI, CU

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Credential

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.

Type: PSCredential

Aliases: cred, c

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-FilePath

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"

/>

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-OptionSet

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}

Type: Hashtable

Aliases: os

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Port

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.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ResourceURI

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

Type: Uri

Aliases: ruri

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-SelectorSet

Specifies a set of value pairs that are used to select particular management resource
instances.
SelectorSet is used when more than one instance of the resource exists.
The value of
SelectorSet must be a hash table.

The following example shows how to enter a value for this parameter:
-SelectorSet @{Name="WinRM";ID="yyy"}

Type: Hashtable

Position: 2

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-SessionOption

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 .

Type: Microsoft.WSMan.Management.SessionOption

Aliases: so

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-UseSSL

Specifies that the Secure Sockets Layer (SSL) protocol is used to establish a
connection to the
remote computer. By default, SSL is not used.

WS-Management encrypts all the 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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-ValueSet

Specifies a hash table that helps modify a management resource. You specify the
management resource
using the ResourceURI and SelectorSet parameters. The
value of the ValueSet parameter must
be a hash table.

Type: Hashtable

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
XmlElement

This cmdlet returns the result of the operation as an XmlElement object.

Related Links
Invoke-WmiMethod
Connect-WSMan
Disable-WSManCredSSP
Disconnect-WSMan
Enable-WSManCredSSP
Get-WSManCredSSP
Get-WSManInstance
New-WSManInstance
New-WSManSessionOption
Remove-WSManInstance
Set-WSManInstance
Set-WSManQuickConfig
Test-WSMan
New-WSManInstance
Reference
Module: Microsoft.WSMan.Management

Creates a new instance of a management resource.

Syntax
PowerShell

New-WSManInstance

[-ApplicationName <String>]

[-ComputerName <String>]

[-FilePath <String>]

[-OptionSet <Hashtable>]

[-Port <Int32>]

[-ResourceURI] <Uri>

[-SelectorSet] <Hashtable>

[-SessionOption <SessionOption>]

[-UseSSL]

[-ValueSet <Hashtable>]

[-Credential <PSCredential>]

[-Authentication <AuthenticationMechanism>]

[-CertificateThumbprint <String>]

[<CommonParameters>]

PowerShell

New-WSManInstance

[-ConnectionURI <Uri>]

[-FilePath <String>]

[-OptionSet <Hashtable>]

[-ResourceURI] <Uri>

[-SelectorSet] <Hashtable>

[-SessionOption <SessionOption>]

[-ValueSet <Hashtable>]

[-Credential <PSCredential>]

[-Authentication <AuthenticationMechanism>]

[-CertificateThumbprint <String>]

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

Examples

Example 1: Create a HTTPS listener


This command creates an instance of a WS-Management HTTPS listener on all IP
addresses.

PowerShell

New-WSManInstance winrm/config/Listener -SelectorSet @{Transport='HTTPS';


Address='*'} -ValueSet @{Hostname="HOST";CertificateThumbprint="XXXXXXXXXX"}

Parameters
-ApplicationName

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.

Type: String

Position: Named

Default value: Wsman


Accept pipeline input: False

Accept wildcard characters: False

-Authentication

Specifies the authentication mechanism to be used at the server. Possible values are:

Basic: Basic is a scheme in which the username 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 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 Support 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.

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

Type: Microsoft.WSMan.Management.AuthenticationMechanism

Aliases: auth, am

Accepted values: None, Default, Digest, Negotiate, Basic, Kerberos,


ClientCertificate, Credssp

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-CertificateThumbprint

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


PowerShell Cert:
drive.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ComputerName

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.

Type: String

Aliases: cn

Position: Named

Default value: Localhost

Accept pipeline input: False

Accept wildcard characters: False

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

Type: Uri

Aliases: CURI, CU

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Credential

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.

Type: PSCredential

Aliases: cred, c

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-FilePath

Specifies the path of a file that is used to create a management resource. You specify
the
management resource using the ResourceURI parameter and the SelectorSet
parameter . For
example, the following command uses the File parameter:
Invoke-WSManAction -Action stopservice -ResourceUri wmi/cimv2/Win32_Service -

SelectorSet @{Name="spooler"} -File c:\input.xml -Authentication Default

This command calls the StopService method on the Spooler service 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"

/>

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-OptionSet

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}

Type: Hashtable

Aliases: os

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Port

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

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ResourceURI

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

Type: Uri

Aliases: ruri

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SelectorSet

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"}

Type: Hashtable

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-SessionOption

Defines a set of extended options for the WS-Management session. Enter a


SessionOption object
that you create using the New-WSManSessionOption cmdlet. For
more information about the options
that are available, see New-WSManSessionOption .

Type: Microsoft.WSMan.Management.SessionOption

Aliases: so

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.

Type: SwitchParameter

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-ValueSet

Specifies a hash table that helps modify a management resource. You specify the
management resource
using the ResourceURI parameter and the SelectorSet
parameter. The value of the ValueSet
parameter must be a hash table.

Type: Hashtable

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
XmlElement

This cmdlet returns the created WSMan instance as an XmlElement object.

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.

Related Links
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
Reference
Module: Microsoft.WSMan.Management

Creates session option hash table to use as input parameters for WS-Management
cmdlets.

Syntax
PowerShell

New-WSManSessionOption

[-ProxyAccessType <ProxyAccessType>]

[-ProxyAuthentication <ProxyAuthentication>]

[-ProxyCredential <PSCredential>]

[-SkipCACheck]

[-SkipCNCheck]

[-SkipRevocationCheck]

[-SPNPort <Int32>]

[-OperationTimeout <Int32>]

[-NoEncryption]

[-UseUTF16]

[<CommonParameters>]

Description
The New-WSManSessionOption cmdlet creates a WSMan Session option hash table which
can be passed to
WSMan cmdlets:

Get-WSManInstance

Set-WSManInstance

Invoke-WSManAction
Connect-WSMan

Examples

Example 1: Create a connection that uses connection


options
PowerShell
PS C:\> $a = New-WSManSessionOption -OperationTimeout 30000

PS C:\> Connect-WSMan -ComputerName "server01" -SessionOption $a

PS C:\> cd wsman:

PS WSMan:\> dir

WSManConfig: Microsoft.WSMan.Management\WSMan::WSMan

ComputerName Type

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

localhost Container

server01 Container

This example creates a connection to the remote server01 computer by using the
connection options
that are defined by New-WSManSessionOption .

The first command uses New-WSManSessionOption 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.

Connect-WSMan is generally used in the context of the WSMan 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 WSMan
provider. Those connections appear in
the ComputerName list.

Parameters
-NoEncryption

Indicates that the connection does not use encryption for remote operations over
HTTP.

By default, unencrypted traffic is not enabled. It must be enabled in the local


configuration.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-OperationTimeout

Specifies the time-out, in milliseconds, for the WS-Management operation.

Type: Int32

Aliases: OperationTimeoutMSec

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ProxyAccessType

Specifies the mechanism by which the proxy server is located. The acceptable values
for this
parameter are:

ProxyIEConfig - Use the Internet Explorer proxy configuration for the current

user.
ProxyWinHttpConfig - The WSMan client uses the proxy settings configured for

WinHTTP, using the


ProxyCfg.exe utility.
ProxyAutoDetect - Force auto-detection of a proxy server.

ProxyNoProxyServer - Do not use a proxy server. Resolve all host names locally.

The default value is ProxyIEConfig.

Type: Microsoft.WSMan.Management.ProxyAccessType

Accepted values: ProxyIEConfig, ProxyWinHttpConfig, ProxyAutoDetect,


ProxyNoProxyServer

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ProxyAuthentication
Specifies the authentication method to use at the proxy. The acceptable values for
this parameter
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 - 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.

The default value is Negotiate.

Type: Microsoft.WSMan.Management.ProxyAuthentication

Accepted values: Negotiate, Basic, Digest

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ProxyCredential

Specifies a user account that has permission to gain access through an intermediate
Web proxy.

Type: PSCredential

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SkipCACheck

Specifies that, when it connects over HTTPS, the client does not validate that the
server
certificate is signed by a trusted certification authority (CA). Use this option
only when the
remote computer is trusted by another method, 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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SkipCNCheck

Specifies that the certificate common name (CN) of the server does not have to
match the host name
of the server. This is used only in remote operations using
HTTPS. This option should only be used
for trusted computers.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SkipRevocationCheck

Indicates that the connection does not validate the revocation status on the server
certificate.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SPNPort

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.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-UseUTF16

Indicates that the connection encodes the request in UTF16 format instead of UTF8
format. The
default is UTF8 encoding.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Outputs
Microsoft.WSMan.Management.SessionOption

This cmdlet returns the created WSMan session option as a SessionOption object.

Related Links
Connect-WSMan
Disable-WSManCredSSP
Disconnect-WSMan
Enable-WSManCredSSP
Get-WSManCredSSP
Get-WSManInstance
Invoke-WSManAction
New-WSManInstance
Remove-WSManInstance
Set-WSManInstance
Set-WSManQuickConfig
Test-WSMan
Remove-WSManInstance
Reference
Module: Microsoft.WSMan.Management

Deletes a management resource instance.

Syntax
PowerShell

Remove-WSManInstance

[-ApplicationName <String>]
[-ComputerName <String>]

[-OptionSet <Hashtable>]

[-Port <Int32>]

[-ResourceURI] <Uri>

[-SelectorSet] <Hashtable>

[-SessionOption <SessionOption>]

[-UseSSL]

[-Credential <PSCredential>]

[-Authentication <AuthenticationMechanism>]

[-CertificateThumbprint <String>]

[<CommonParameters>]

PowerShell

Remove-WSManInstance

[-ConnectionURI <Uri>]

[-OptionSet <Hashtable>]

[-ResourceURI] <Uri>

[-SelectorSet] <Hashtable>

[-SessionOption <SessionOption>]

[-Credential <PSCredential>]

[-Authentication <AuthenticationMechanism>]

[-CertificateThumbprint <String>]

[<CommonParameters>]

Description
The Remove-WSManInstance cmdlet 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.
Examples

Example 1: Delete a listener


PowerShell

Remove-WSManInstance -ResourceUri winrm/config/Listener -SelectorSet


Address=test.fabrikam.com;Transport=http

This command deletes the WS-Management HTTP listener on a computer.

Parameters
-ApplicationName

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

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Authentication
Specifies the authentication mechanism to be used at the server.
The acceptable
values for this parameter 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 for
negotiation to determine whether the
Kerberos protocol or NTLM is used.
CredSSP - Use Credential Security Support Provider (CredSSP) authentication,

which lets the user


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.

U Caution

CredSSP delegates the user 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.

Type: Microsoft.WSMan.Management.AuthenticationMechanism

Aliases: auth, am

Accepted values: None, Default, Digest, Negotiate, Basic, Kerberos,


ClientCertificate, Credssp

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

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

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ComputerName

Specifies the computer against which 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.

Type: String

Aliases: cn

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ConnectionURI

Specifies the connection endpoint. The format of this string is as follows:

<Transport>://<Server>:<Port>/<ApplicationName>

The following string is a correctly formatted value for this parameter:


http://Server01:8080/WSMAN

The URI must be fully qualified.

Type: Uri

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Credential

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, this cmdlet prompts you for a
password.

Type: PSCredential

Aliases: cred, c

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-OptionSet

Specifies a set of switches to a service to modify or refine the nature of the request.
These
resemble 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}

Type: Hashtable
Aliases: os

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Port

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

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ResourceURI

Specifies the 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 of 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

Type: Uri

Aliases: ruri

Position: 0
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SelectorSet

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
SelectorSet must be a hash table.

The following example shows how to enter a value for this parameter:

-SelectorSet @{Name="WinRM";ID="yyy"}

Type: Hashtable

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-SessionOption

Specifies 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, type Get-Help New-
WSManSessionOption .

Type: Microsoft.WSMan.Management.SessionOption

Aliases: so

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-UseSSL
Specifies that the Secure Sockets Layer (SSL) protocol is 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.

Type: SwitchParameter

Aliases: ssl

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
The cmdlets in the CimCmdlets module are similar. They use the DCOM
connection/transport layer to
create or update WMI instances.

Related Links
Connect-WSMan
Disable-WSManCredSSP
Disconnect-WSMan
Enable-WSManCredSSP
Get-WSManCredSSP
Get-WSManInstance
Invoke-WSManAction
New-WSManInstance
New-WSManSessionOption
Set-WSManInstance
Set-WSManQuickConfig
Test-WSMan
Set-WSManInstance
Reference
Module: Microsoft.WSMan.Management

Modifies the management information that is related to a resource.

Syntax
PowerShell

Set-WSManInstance

[-ApplicationName <String>]

[-ComputerName <String>]

[-Dialect <Uri>]

[-FilePath <String>]

[-Fragment <String>]

[-OptionSet <Hashtable>]

[-Port <Int32>]

[-ResourceURI] <Uri>

[[-SelectorSet] <Hashtable>]

[-SessionOption <SessionOption>]

[-UseSSL]

[-ValueSet <Hashtable>]

[-Credential <PSCredential>]

[-Authentication <AuthenticationMechanism>]

[-CertificateThumbprint <String>]

[<CommonParameters>]

PowerShell

Set-WSManInstance

[-ConnectionURI <Uri>]

[-Dialect <Uri>]

[-FilePath <String>]

[-Fragment <String>]

[-OptionSet <Hashtable>]

[-ResourceURI] <Uri>

[[-SelectorSet] <Hashtable>]

[-SessionOption <SessionOption>]

[-ValueSet <Hashtable>]

[-Credential <PSCredential>]

[-Authentication <AuthenticationMechanism>]

[-CertificateThumbprint <String>]

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

Examples

Example 1: Disable a listener on the local computer


PowerShell

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

This command disables the HTTPS listener on the local computer.

) Important

The ValueSet parameter is case-sensitive when matching the properties specified.

For example, in this command,

This fails: -ValueSet @{enabled="False"}

This succeeds: -ValueSet @{Enabled="False"}

Example 2: Set the maximum envelope size on the local


computer
PowerShell

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

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: Disable a listener on a remote computer


PowerShell

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

Parameters
-ApplicationName

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.

Type: String

Position: Named

Default value: Wsman

Accept pipeline input: False

Accept wildcard characters: False

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

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

Type: Microsoft.WSMan.Management.AuthenticationMechanism

Aliases: auth, am

Accepted values: None, Default, Digest, Negotiate, Basic, Kerberos,


ClientCertificate, Credssp

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

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


PowerShell
Cert: drive.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ComputerName

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,
localhost , or 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 pipe a value for this parameter to the cmdlet.

Type: String

Aliases: cn

Position: Named

Default value: Localhost

Accept pipeline input: False

Accept wildcard characters: False

-ConnectionURI

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.

Type: Uri

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Credential

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

Type: PSCredential

Aliases: cred, c

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Dialect

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
Type: Uri

Position: Named

Default value: http://schemas.microsoft.com/wbem/wsman/1/WQL

Accept pipeline input: False

Accept wildcard characters: False

-FilePath

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"
/>

Type: String

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Fragment

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 .

Type: String

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-OptionSet

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}

Type: Hashtable

Aliases: os

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Port

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.

Type: Int32

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-ResourceURI

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

Type: Uri

Aliases: ruri

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SelectorSet

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"}

Type: Hashtable

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False


-SessionOption

Defines a set of extended options for the WS-Management session. Enter a


SessionOption object
that you create with the New-WSManSessionOption cmdlet. For
more information about the options
that are available, see New-
WSManSessionOption.

Type: Microsoft.WSMan.Management.SessionOption

Aliases: so

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.

Type: SwitchParameter

Aliases: ssl

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ValueSet

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.
Type: Hashtable

Position: Named

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

This cmdlet returns no output.

Related Links
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
Reference
Module: Microsoft.WSMan.Management

Configures the local computer for remote management.

Syntax
PowerShell

Set-WSManQuickConfig

[-UseSSL]

[-Force]

[-SkipNetworkProfileCheck]

[<CommonParameters>]

Description
The Set-WSManQuickConfig cmdlet configures the computer to receive PowerShell
remote commands that
are sent by using the Web Services for Management (WS-
Management) technology.

Set-WSManQuickConfig performs the following actions:

Checks whether the WinRM service is running. If the WinRM service isn't running,
the service is
started.
Sets the WinRM service startup type to automatic.
Creates a listener to accept requests on any IP address. The default transport is
HTTP.
Enables a firewall exception for WinRM traffic.

To run Set-WSManQuickConfig , start PowerShell with the Run as Administrator option.

Examples

Example 1: Enable remote management of the local


computer over HTTP
This example sets the required configuration to enable remote management of the local
computer. By
default, this command creates a WS-Management listener on HTTP.

PowerShell

Set-WSManQuickConfig

Example 2: Enable remote management of the local


computer over HTTPS
This example sets the required configuration to enable remote management of the local
computer. The
UseSSL parameter specifies that HTTPS is used to communicate with the
computer.

PowerShell

Set-WSManQuickConfig -UseSSL

7 Note

HTTPS requires manual configuration. For more information, see the UseSSL
parameter's
description.

Parameters
-Force

Forces the command to run without asking for user confirmation.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-SkipNetworkProfileCheck
Configures Windows client versions for remoting when the computer is on a public
network. This
parameter enables a firewall rule for public networks that allows
remote access only from computers
in the same local subnet.

This parameter has no effect on server versions of Windows, that by default, have a
local subnet
firewall rule for public networks. If the local subnet firewall rule is
disabled on the server
version of Windows, Enable-PSRemoting re-enables it,
regardless of this parameter's value.

To remove the local subnet restriction and enable remote access from all locations
on public
networks, use the Set-NetFirewallRule cmdlet in the NetSecurity module.

This parameter was introduced in PowerShell 3.0.

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-UseSSL

Specifies that the Secure Sockets Layer (SSL) protocol is used to establish a
connection to the
remote computer. By default, SSL isn't used.

WS-Management encrypts all the PowerShell content that is transmitted over the
network. The
UseSSL parameter lets you specify the additional protection of HTTPS
instead of HTTP. If you use
this parameter and SSL isn't available on the port that's
used for the connection, the command
fails.

HTTPS requires manual configuration of WinRM and firewall rules. For more
information, see
How To: Configure WINRM for HTTPS .

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

This cmdlet returns no output.

Related Links
Connect-WSMan
Disable-WSManCredSSP
Disconnect-WSMan
Enable-PSRemoting
Enable-WSManCredSSP
Get-WSManCredSSP
Get-WSManInstance
How To: Configure WINRM for HTTPS
Invoke-WSManAction
New-PSSession
New-WSManInstance
New-WSManSessionOption
Test-WSMan
Test-WSMan
Reference
Module: Microsoft.WSMan.Management

Tests whether the WinRM service is running on a local or remote computer.

Syntax
PowerShell

Test-WSMan

[[-ComputerName] <String>]

[-Authentication <AuthenticationMechanism>]

[-Port <Int32>]

[-UseSSL]

[-ApplicationName <String>]

[-Credential <PSCredential>]

[-CertificateThumbprint <String>]

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

Examples

Example 1: Determine the status of the WinRM service


PowerShell

Test-WSMan

This command determines whether the WinRM service is running on the local computer
or on a remote
computer.
Example 2: Determine the status of the WinRM service on
a remote computer
PowerShell

Test-WSMan -ComputerName "server01"

This command determines whether the WinRM service is running on the server01
computer.

Example 3: Determine the status of the WinRM service


and the operating system version
PowerShell

Test-WSMan -Authentication default

This command tests to see whether the WS-Management (WinRM) service is running on
the local computer
by using the authentication parameter.

Using the authentication parameter enables Test-WSMan to return the operating system
version.

Example 4: Determine the status of the WinRM service


and the OS version on a remote computer
PowerShell

Test-WSMan -ComputerName "server01" -Authentication default

This command tests to see whether the WS-Management (WinRM) service is running on
the computer named
server01 using the authentication parameter.

Using the authentication parameter enables Test-WSMan to return the operating system
version.

Parameters
-ApplicationName
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 if many 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.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Authentication

Specifies the authentication mechanism to be used at the server. The acceptable


values for this
parameter 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.
1 - 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 for
negotiation to determine whether the
Kerberos protocol or NTLM is used.
CredSSP - Use Credential Security Support Provider (CredSSP) authentication,
which lets the user
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.

U Caution

CredSSP delegates the user 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 you do not specify the Authentication parameter,, the Test-WSMan request is


sent to the
remote computer anonymously, without using authentication. If the
request is made anonymously, it
returns no information that is specific to the
operating-system version. Instead, this cmdlet
displays null values for the
operating system version and service pack level (OS: 0.0.0 SP: 0.0).

Type: Microsoft.WSMan.Management.AuthenticationMechanism

Aliases: auth, am

Accepted values: None, Default, Digest, Negotiate, Basic, Kerberos,


ClientCertificate, Credssp

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-CertificateThumbprint

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.
Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ComputerName

Specifies the computer against which 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.

Type: String

Aliases: cn

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Credential

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, this cmdlet prompts you for a

password.

Type: PSCredential

Aliases: cred, c

Position: Named

Default value: None

Accept pipeline input: True


Accept wildcard characters: False

-Port

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

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-UseSSL

Specifies that the Secure Sockets Layer (SSL) protocol is 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.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.


Outputs
None

This cmdlet returns no output.

Notes
By default, the Test-WSMan cmdlet queries the WinRM service without using
authentication, and it
returns no 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).

Related Links
Connect-WSMan
Disable-WSManCredSSP
Disconnect-WSMan
Enable-WSManCredSSP
Get-WSManCredSSP
Get-WSManInstance
Invoke-WSManAction
New-WSManInstance
New-WSManSessionOption
Remove-WSManInstance
Set-WSManInstance
Set-WSManQuickConfig
PSDiagnostics
Reference

The PowerShell Diagnostics Module contains a set of cmdlets that enables the use of
ETW
tracing in PowerShell on Windows.

PSDiagnostics
Disable-PSTrace Disables the Microsoft-Windows-PowerShell event provider logs.

Disable- Stop the logging session started by Enable-


PSWSManCombinedTrace PSWSManCombinedTrace.

Disable-WSManTrace Stop the WSMan logging session started by Enable-


WSManTrace.

Enable-PSTrace Enables the Microsoft-Windows-PowerShell event provider logs.

Enable- Start a logging session with the WSMan and PowerShell


PSWSManCombinedTrace providers enabled.

Enable-WSManTrace Start a logging session with the WSMan providers enabled.

Get-LogProperties Retrieves the properties of a Windows event log.

Set-LogProperties Changes the properties of a Windows event log.

Start-Trace Start an Event Trace logging session.

Stop-Trace Stop an Event Trace logging session.


Disable-PSTrace
Reference
Module: PSDiagnostics

Disables the Microsoft-Windows-PowerShell event provider logs.

Syntax
PowerShell

Disable-PSTrace

[-AnalyticOnly]

[<CommonParameters>]

Description
This cmdlet disables the Operational and Analytic event logs of the Microsoft-Windows-
PowerShell
event provider.

You must run this cmdlet from an elevated PowerShell session.

Examples

Example 1: Disable the Analytic event log for PowerShell


The following example disables only the Analytic event log of the Microsoft-Windows-
PowerShell
provider.

PowerShell

Disable-PSTrace -AnalyticOnly

Parameters
-AnalyticOnly

When this parameter is used, the cmdlet disables the Analytic event log of the
Microsoft-Windows-PowerShell provider. The Operational event log is not changed.
Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
This cmdlet uses the Get-LogProperties and Set-LogProperties cmdlets.

You must run this cmdlet from an elevated PowerShell session.

Related Links
Get-LogProperties
Set-LogProperties
Enable-PSTrace
Disable-PSWSManCombinedTrace
Reference
Module: PSDiagnostics

Stop the logging session started by Enable-PSWSManCombinedTrace.

Syntax
PowerShell

Disable-PSWSManCombinedTrace []

Description
This cmdlet stops the logging session started by Enable-PSWSManCombinedTrace .

This cmdlet uses the Stop-Trace cmdlet.

You must run this cmdlet from an elevated PowerShell session.

Examples

Example 1: Disable the combined logging session


PowerShell

Disable-PSWSManCombinedTrace

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None
This cmdlet returns no output.

Related Links
Event Tracing
Stop-Trace
Enable-PSWSManCombinedTrace
Disable-WSManTrace
Reference
Module: PSDiagnostics

Stop the WSMan logging session started by Enable-WSManTrace.

Syntax
PowerShell

Disable-WSManTrace []

Description
This cmdlet stops the WSMan logging session started by Enable-WSManTrace.

This cmdlet uses the Stop-Trace cmdlet.

You must run this cmdlet from an elevated PowerShell session.

Examples

Example 1: Stop a WSMan trace


PowerShell

Disable-WSManTrace

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None
This cmdlet returns no output.

Related Links
Event Tracing
Stop-Trace
Enable-WSManTrace
Enable-PSTrace
Reference
Module: PSDiagnostics

Enables the Microsoft-Windows-PowerShell event provider logs.

Syntax
PowerShell

Enable-PSTrace

[-Force]

[-AnalyticOnly]

Description
This cmdlet enables the Operational and Analytic event logs of the Microsoft-Windows-
PowerShell
event provider.

You must run this cmdlet from an elevated PowerShell session.

Examples

Example 1: Enable the Analytic event log for PowerShell


The following example enables only the Analytic event log of the Microsoft-Windows-
PowerShell
provider.

PowerShell

Enable-PSTrace -AnalyticOnly

Parameters
-AnalyticOnly

When this parameter is used, the cmdlet enables the Analytic event log of the
Microsoft-Windows-PowerShell provider. The Operational event log is not changed.
Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Force

Used to force the change without prompting.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
This cmdlet uses the Get-LogProperties and Set-LogProperties cmdlets.

You must run this cmdlet from an elevated PowerShell session.

Related Links
Get-LogProperties
Set-LogProperties
Disable-PSTrace
Enable-PSWSManCombinedTrace
Reference
Module: PSDiagnostics

Start a logging session with the WSMan and PowerShell providers enabled.

Syntax
PowerShell

Enable-PSWSManCombinedTrace

[-DoNotOverwriteExistingTrace]

[<CommonParameters>]

Description
This cmdlet starts a logging session with the following PowerShell providers enabled:

Microsoft-Windows-PowerShell
Microsoft-Windows-WinRM

The session is named 'PSTrace'.

This cmdlet uses the Start-Trace cmdlet.

You must run this cmdlet from an elevated PowerShell session.

Examples

Example 1: Start a combined logging session


PowerShell

Enable-PSWSManCombinedTrace

Parameters
-DoNotOverwriteExistingTrace
By default, the events are written to $PSHOME\Traces\PSTrace.etl . When this
parameter is used,
the cmdlet creates a unique filename:
$PSHOME\Traces\PSTrace_{guid}.etl

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

This cmdlet returns no output.

Related Links
Event Tracing
Start-Trace
Disable-PSWSManCombinedTrace
Enable-WSManTrace
Reference
Module: PSDiagnostics

Start a logging session with the WSMan providers enabled.

Syntax
PowerShell

Enable-WSManTrace []

Description
This cmdlet starts a logging session with the WSMan providers enabled. The following
event
providers are enabled:

Event Forwarding

IpmiDrv
IPMIPrv

WinRM
WinrsCmd

WinrsExe

WinrsMgr
WSManProvHost

The session is named wsmlog .

This cmdlet uses the Start-Trace cmdlet.

You must run this cmdlet from an elevated PowerShell session.

Examples

Example 1: Start a WSMan logging session


PowerShell
Enable-WSManTrace

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

This cmdlet returns no output.

Related Links
Event Tracing
Start-Trace
Disable-WSManTrace
Get-LogProperties
Reference
Module: PSDiagnostics

Retrieves the properties of a Windows event log.

Syntax
PowerShell

Get-LogProperties

[-Name] <string>

[<CommonParameters>]

Description
This cmdlet gets the configuration settings of a Windows event log. This cmdlet is used
by the
Enable-PSTrace and Disable-PSTrace cmdlets.

Examples

Example 1: Get the configuration settings of the Windows


PowerShell event log
PowerShell

Get-LogProperties 'Windows PowerShell'

Name : Windows PowerShell

Enabled : True

Type : Admin

Retention : False

AutoBackup : False

MaxLogSize : 15728640

Parameters
-Name
The name of the event provider.

Type: Object

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

Inputs
Object

Outputs
Microsoft.PowerShell.Diagnostics.LogDetails

This cmdlet returns a LogDetails object.

The PSDiagnostics module adds the LogDetails class to the


Microsoft.PowerShell.Diagnostics namespace.

Related Links
Set-LogProperties
Enable-PSTrace
Disable-PSTrace
Set-LogProperties
Reference
Module: PSDiagnostics

Changes the properties of a Windows event log.

Syntax
PowerShell

Set-LogProperties

[-LogDetails] <LogDetails>

[-Force]

[<CommonParameters>]

Description
This cmdlet changes the configuration settings of a Windows event log. This cmdlet is
used by the
Enable-PSTrace and Disable-PSTrace cmdlets.

You must run this cmdlet from an elevated PowerShell session.

Examples

Example 1: Change the retention setting of the Windows


PowerShell event log
PowerShell

$logDetails = Get-LogProperties 'Windows PowerShell'

$logDetails.Retention = $True

Set-LogProperties -LogDetails $logDetails

Get-LogProperties 'Windows PowerShell'

Name : Windows PowerShell

Enabled : True

Type : Admin

Retention : True

AutoBackup : False

MaxLogSize : 15728640
Parameters
-Force

Used to force the change without prompting.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-LogDetails

The updated configuration settings to be assigned to the event log.

Type: Microsoft.PowerShell.Diagnostics.LogDetails

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

Inputs
Microsoft.PowerShell.Diagnostics.LogDetails

You can pipe a fully configured LogDetails object to this cmdlet. Therefore, to change
one
setting, you should use Get-LogProperties to retrieve the current configuration.

Outputs
None

This cmdlet returns no output.

Notes
You must run this cmdlet from an elevated PowerShell session.

Related Links
Get-LogProperties
Enable-PSTrace
Disable-PSTrace
Start-Trace
Reference
Module: PSDiagnostics

Start an Event Trace logging session.

Syntax
PowerShell

Start-Trace

[-SessionName] <String>

[[-OutputFilePath] <String>]
[[-ProviderFilePath] <String>]

[-ETS]

[-Format <String>]

[-MinBuffers <Int32>]

[-MaxBuffers <Int32>]

[-BufferSizeInKB <Int32>]

[-MaxLogFileSizeInMB <Int32>]

[<CommonParameters>]

Description
This cmdlet starts a Windows Event Trace logging session.

This cmdlet is used by the following cmdlets:

Enable-PSWSManCombinedTrace
Enable-WSManTrace

You must run this cmdlet from an elevated PowerShell session.

Examples

Example 1: Start a WSMan Trace logging session


PowerShell

$parameters = @{

SessionName = 'wsmlog'

ETS = $true

OutputFilePath = "$env:windir\system32\wsmtraces.log"

Format = 'bincirc'

MinBuffers = 16

MaxBuffers = 256

BufferSizeInKb = 64

MaxLogFileSizeInMB = 256

ProviderFilePath = "$env:windir\system32\wsmtraceproviders.txt"

Start-Trace @parameters

Parameters
-BufferSizeInKB

Event Trace Session buffer size in kilobytes (KB).

Type: Int32

Position: Named

Default value: 0

Accept pipeline input: False

Accept wildcard characters: False

-ETS

Send commands to Event Trace Sessions directly without saving or scheduling.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Format

Specifies the log format for the data collector. For SQL database format, you must
use the
OutputFilePath option in the command line with the dsn!log value. The
default is binary
(bin). The possible values are:

bin - binary
bincirc - binary with circular logging
csv - Comma-separated values
tsv - Tab-separated values
sql - SQL database

Type: Object

Accepted values: bin, bincirc, csv, tsv, sql

Position: Named

Default value: bin

Accept pipeline input: False

Accept wildcard characters: False

-MaxBuffers

Sets the maximum number of Event Trace Session buffers.

Type: Int32

Position: Named

Default value: 256

Accept pipeline input: False

Accept wildcard characters: False

-MaxLogFileSizeInMB

Sets the maximum log file size in megabytes (MB) or number of records for SQL logs.

Type: Int32

Position: Named

Default value: 0 (no limit)

Accept pipeline input: False

Accept wildcard characters: False

-MinBuffers

Sets the minimum number of Event Trace Session buffers.


Type: Int32

Position: Named

Default value: 0

Accept pipeline input: False

Accept wildcard characters: False

-OutputFilePath

Path of the output log file or the DSN and log set name in a SQL database. The
default path is
$env:systemdrive\PerfLogs\Admin .

Type: String

Position: 1

Default value: $env:systemdrive\PerfLogs\Admin

Accept pipeline input: False

Accept wildcard characters: False

-ProviderFilePath

File listing multiple Event Trace providers to enable.

Type: String

Position: 2

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SessionName

The name of the Event Trace session. To stop a trace session you must know the
session name.

Type: String

Position: 0
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

This cmdlet returns no output.

Related Links
Event Tracing
Stop-Trace
Disable-PSWSManCombinedTrace
Disable-WSManTrace
Enable-PSWSManCombinedTrace
Enable-WSManTrace
Stop-Trace
Reference
Module: PSDiagnostics

Stop an Event Trace logging session.

Syntax
PowerShell

Stop-Trace

[-SessionName] <Object>

[-ETS]

[<CommonParameters>]

Description
This cmdlet stops a Windows Event Trace logging session.

This cmdlet is used by the following cmdlets:

Disable-PSWSManCombinedTrace

Disable-WSManTrace

You must run this cmdlet from an elevated PowerShell session.

Examples

Example 1: Stop a WSMan Trace logging session


PowerShell

Stop-Trace -SessionName 'wsmlog'

Parameters
-ETS
Send commands to Event Trace Sessions directly without saving or scheduling.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-SessionName

The name of the Event Trace session to be stopped.

Type: Object

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

This cmdlet returns no output.

Related Links
Event Tracing
Start-Trace
Disable-PSWSManCombinedTrace
Disable-WSManTrace
Enable-PSWSManCombinedTrace
Enable-WSManTrace
PSReadLine
Reference

The PSReadLine module contains cmdlets that let you customize the command-line
editing environment
in PowerShell.

There have been many updates to PSReadLine since the version that ships in
Windows
PowerShell 5.1.

PowerShell 7.3.0 ships with PSReadLine 2.2.6


PowerShell 7.2.5 ships with PSReadLine 2.1.0
PowerShell 7.0.11 ships with PSReadLine 2.0.4
PowerShell 5.1 ships with PSReadLine 2.0.0

These articles document version 2.0.0 of PSReadLine.

PSReadLine
Get-PSReadLineKeyHandler Gets the key bindings for the PSReadLine module.

Get-PSReadLineOption Gets values for the options that can be configured.

PSConsoleHostReadLine This function is the main entry point for PSReadLine.

Remove- Removes a key binding.


PSReadLineKeyHandler

Set-PSReadLineKeyHandler Binds keys to user-defined or PSReadLine key handler functions.

Set-PSReadLineOption Customizes the behavior of command line editing in


PSReadLine.
about_PSReadLine
Article • 11/14/2022 • 4 minutes to read

Short Description
PSReadLine provides an improved command-line editing experience in the
PowerShell
console.

Long Description
PowerShell 5.1 ships with PSReadLine 2.0.0. There are newer versions
available. The
current version of PSReadLine can be installed and used on
Windows PowerShell 5.1 and
newer. For some features, you need to be running
PowerShell 7.2 or higher.

PSReadLine provides a powerful command-line editing experience for the


PowerShell
console. It provides:

Syntax coloring of the command line


A visual indication of syntax errors
A better multi-line experience (both editing and history)
Customizable key bindings
Cmd and Emacs modes
Many configuration options
Bash style completion (optional in Cmd mode, default in Emacs mode)
Emacs yank/kill-ring
PowerShell token based "word" movement and deletion

PSReadLine requires PowerShell 5.1, or newer. PSReadLine works with the default
Windows console host, Window Terminal, and Visual Studio Code. It doesn't work
in the
Windows PowerShell ISE.

PSReadLine can be installed from the PowerShell Gallery. To install PSReadLine


in a
supported version of PowerShell run the following command.

PowerShell

Install-Module -Name PSReadLine -AllowClobber -Force

Custom Key Bindings


PSReadLine supports custom key bindings using the Set-PSReadLineKeyHandler
cmdlet.
Most custom key bindings call one of the
bindable functions, for example

PowerShell

Set-PSReadLineKeyHandler -Key UpArrow -Function HistorySearchBackward

You can bind a ScriptBlock to a key. The ScriptBlock can do pretty much
anything you
want. Some useful examples include

edit the command line


opening a new window (for example, help)
change directories without changing the command line

The ScriptBlock receives two arguments:

$key - A [ConsoleKeyInfo] object that is the key that triggered the


custom
binding. If you bind the same ScriptBlock to multiple keys and need to
perform
different actions depending on the key, you can check $key . Many
custom
bindings ignore this argument.

$arg - An arbitrary argument. Most often, this would be an integer


argument that

the user passes from the key bindings DigitArgument. If your


binding doesn't
accept arguments, it's reasonable to ignore this argument.

Let's take a look at an example that adds a command line to history without
executing
it. This is useful when you realize you forgot to do something, but
don't want to re-enter
the command line you've already entered.

PowerShell

$parameters = @{

Key = 'Alt+w'

BriefDescription = 'SaveInHistory'

LongDescription = 'Save current line in history but do not execute'

ScriptBlock = {

param($key, $arg) # The arguments are ignored in this example

# GetBufferState gives us the command line (with the cursor position)

$line = $null

$cursor = $null

[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line,

[ref]$cursor)

# AddToHistory saves the line in history, but does not execute it.

[Microsoft.PowerShell.PSConsoleReadLine]::AddToHistory($line)

# RevertLine is like pressing Escape.

[Microsoft.PowerShell.PSConsoleReadLine]::RevertLine()

Set-PSReadLineKeyHandler @parameters

You can see many more examples in the file SamplePSReadLineProfile.ps1 , which
is
installed in the PSReadLine module folder.

Most key bindings use some helper functions for editing the command line. Those
APIs
are documented in
about_PSReadLine_Functions.

Notes

Command History
PSReadLine maintains a history file containing all the commands and data you've
entered from the command line. The history files are a file named
$($host.Name)_history.txt . On Windows systems the history file is stored at
$env:APPDATA\Microsoft\Windows\PowerShell\PSReadLine .

The history can contain sensitive data including passwords. PSReadLine attempts
to filter
out sensitive information. Any command lines containing the following
strings aren't
written to the history file.

password
asplaintext
token
apikey
secret

PSReadLine 2.2.0 improves the filtering of sensitive data in the following ways:

Uses the PowerShell Abstract Syntax Tree (AST) of the parsed command line to
look for sensitive data.
Uses an allowlist of safe cmdlets from the SecretManagement module to
allow
those commands to be added to the history. The allowlist contains:
Get-Secret
Get-SecretInfo

Get-SecretVault

Register-SecretVault
Remove-Secret
Set-SecretInfo

Set-SecretVaultDefault
Test-SecretVault

Unlock-SecretVault
Unregister-SecretVault

For example, the following commands are allowed to be written to the history
file:

PowerShell

Get-Secret PSGalleryApiKey -AsPlainText # Get-Secret is in the allowlist

$token = Get-Secret -Name github-token -Vault MySecret

[MyType]::CallRestAPI($token, $url, $args)

$template -f $token

The following commands aren't being written to the history file:

PowerShell

$token = 'abcd' # Assign expr-value to sensitive variable name.

Set-Secret abc $mySecret # Set-Secret is not in the allowlist.

ConvertTo-SecureString stringValue -AsPlainText # '-AsPlainText' is an


alert.

Invoke-WebRequest -Token xxx # Expr-value as argument to '-Token'.


Get-ResultFromTwo -Secret1 (Get-Secret -Name blah -AsPlainText) -Secret2
sdv87ysdfayf798hfasd8f7ha # '-Secret2' has expr-value argument.

PSReadLine release history


There have been many updates to PSReadLine since the version that ships in
Windows
PowerShell 5.1.

PowerShell 7.3 ships with PSReadLine 2.2.6


PowerShell 7.2.5 ships with PSReadLine 2.1.0
PowerShell 7.0.11 ships with PSReadLine 2.0.4
PowerShell 5.1 ships with PSReadLine 2.0.0

For a full list of changes, see the PSReadLine


ChangeLog .

PSReadLine 2.2.6

In this release, the Predictive IntelliSense feature is enabled by default


depending
on the following conditions:
If Virtual Terminal (VT) is supported and PSReadLine running in PowerShell
7.2
or higher, PredictionSource is set to HistoryAndPlugin
If VT is supported and PSReadLine running in PowerShell prior to 7.2,
PredictionSource is set to History
If VT isn't supported, PredictionSource is set to None

PSReadLine 2.2.5

Official servicing release with minor bug fixes.

PSReadLine 2.2.2
PSReadLine added two new predictive IntelliSense features:
Added the PredictionViewStyle parameter to allow for the selection of
the
new ListView .
Connected PSReadLine to the CommandPrediction APIs introduced in
PowerShell 7.2 to allow a user can import a predictor module that can
render
the suggestions from a custom source.
Updated to use the 1.0.0 version of Microsoft.PowerShell.Pager for
dynamic
help
Improved the scrubbing of sensitive history items
Lots of bug fixes and smaller improvements

PSReadLine 2.1.0

This release rolls up the following enhancements added since the 2.0.4
release:
Add Predictive IntelliSense suggestions from the command history
Many bug fixes and API enhancements

PSReadLine 2.0.4

This release rolls up the following enhancements added since the 2.0.0
release:
Added the -Chord parameter to Get-PSReadLineKeyHandler to allow
searching
for specific key bindings

Feedback & contributing to PSReadLine


PSReadLine on GitHub

Feel free to submit a pull request or submit feedback on the GitHub page.

See Also
PSReadLine is heavily influenced by the GNU
readline library.
about_PSReadLine_Functions
Article • 09/19/2022 • 21 minutes to read

Short Description
PSReadLine provides an improved command-line editing experience in the
PowerShell
console.

Long Description
PowerShell 5.1 ships with PSReadLine 2.0.0. There are newer versions available.
The
current version of PSReadLine can be installed and used on Windows
PowerShell 5.1 and
newer. For some features, you need to be running PowerShell
7.2 or higher.

This article documents the functions provided by PSReadLine. These functions


can be
bound to keystrokes for easy access and invocation.

Using the
Microsoft.PowerShell.PSConsoleReadLine class
The following functions are available in the class
Microsoft.PowerShell.PSConsoleReadLine.

Basic editing functions

Abort
Abort current action, for example: incremental history search.

Emacs: <Ctrl+g>

AcceptAndGetNext
Attempt to execute the current input. If it can be executed (like AcceptLine),
then recall
the next item from history the next time ReadLine is called.

Emacs: <Ctrl+o>
AcceptLine
Attempt to execute the current input. If the current input is incomplete (for
example
there's a missing closing parenthesis, bracket, or quote) then the
continuation prompt is
displayed on the next line and PSReadLine waits for
keys to edit the current input.

Cmd: <Enter>
Emacs: <Enter>
Vi insert mode: <Enter>

AddLine
The continuation prompt is displayed on the next line and PSReadLine waits for
keys to
edit the current input. This is useful to enter multi-line input as a
single command even
when a single line is complete input by itself.

Cmd: <Shift+Enter>
Emacs: <Shift+Enter>
Vi insert mode: <Shift+Enter>
Vi command mode: <Shift+Enter>

BackwardDeleteChar
Delete the character before the cursor.

Cmd: <Backspace> , <Ctrl+h>


Emacs: <Backspace> , <Ctrl+Backspace> , <Ctrl+h>
Vi insert mode: <Backspace>
Vi command mode: <X> , <d,h>

BackwardDeleteLine
Like BackwardKillLine - deletes text from the point to the start of the line,
but doesn't
put the deleted text in the kill-ring.

Cmd: <Ctrl+Home>
Vi insert mode: <Ctrl+u> , <Ctrl+Home>
Vi command mode: <Ctrl+u> , <Ctrl+Home> , <d,0>

BackwardDeleteWord
Deletes the previous word.

Vi command mode: <Ctrl+w> , <d,b>

BackwardKillLine
Clear the input from the start of the input to the cursor. The cleared text is
placed in the
kill-ring.

Emacs: <Ctrl+u> , <Ctrl+x,Backspace>

BackwardKillWord
Clear the input from the start of the current word to the cursor. If the cursor
is between
words, the input is cleared from the start of the previous word to
the cursor. The cleared
text is placed in the kill-ring.

Cmd: <Ctrl+Backspace>
Emacs: <Alt+Backspace> , <Escape,Backspace>
Vi insert mode: <Ctrl+Backspace>
Vi command mode: <Ctrl+Backspace>

CancelLine
Cancel the current input, leaving the input on the screen, but returns back to
the host so
the prompt is evaluated again.

Vi insert mode: <Ctrl+c>


Vi command mode: <Ctrl+c>

Copy
Copy selected region to the system clipboard. If no region is selected, copy
the whole
line.

Cmd: <Ctrl+C>

CopyOrCancelLine
If text is selected, copy to the clipboard, otherwise cancel the line.

Cmd: <Ctrl+c>
Emacs: <Ctrl+c>

Cut
Delete selected region placing deleted text in the system clipboard.

Cmd: <Ctrl+x>

DeleteChar
Delete the character under the cursor.

Cmd: <Delete>
Emacs: <Delete>
Vi insert mode: <Delete>
Vi command mode: <Delete> , <x> , <d,l> , <d,Space>

DeleteCharOrExit
Delete the character under the cursor, or if the line is empty, exit the
process.

Emacs: <Ctrl+d>

DeleteEndOfWord
Delete to the end of the word.

Vi command mode: <d,e>

DeleteLine
Deletes the current line, enabling undo.

Vi command mode: <d,d>

DeleteLineToFirstChar
Deletes text from the cursor to the first non-blank character of the line.

Vi command mode: <d,^>


DeleteToEnd
Delete to the end of the line.

Vi command mode: <D> , <d,$>

DeleteWord
Delete the next word.

Vi command mode: <d,w>

ForwardDeleteLine
Like ForwardKillLine - deletes text from the point to the end of the line, but
doesn't put
the deleted text in the kill-ring.

Cmd: <Ctrl+End>
Vi insert mode: <Ctrl+End>
Vi command mode: <Ctrl+End>

InsertLineAbove
A new empty line is created above the current line regardless of where the
cursor is on
the current line. The cursor moves to the beginning of the new
line.

Cmd: <Ctrl+Enter>

InsertLineBelow
A new empty line is created below the current line regardless of where the
cursor is on
the current line. The cursor moves to the beginning of the new
line.

Cmd: <Shift+Ctrl+Enter>

InvertCase
Invert the case of the current character and move to the next one.

Vi command mode: <~>


KillLine
Clear the input from the cursor to the end of the input. The cleared text is
placed in the
kill-ring.

Emacs: <Ctrl+k>

KillRegion
Kill the text between the cursor and the mark.

Function is unbound.

KillWord
Clear the input from the cursor to the end of the current word. If the cursor
is between
words, the input is cleared from the cursor to the end of the next
word. The cleared text
is placed in the kill-ring.

Cmd: <Ctrl+Delete>
Emacs: <Alt+d> , <Escape,d>
Vi insert mode: <Ctrl+Delete>
Vi command mode: <Ctrl+Delete>

Paste
Paste text from the system clipboard.

Cmd: <Ctrl+v> , <Shift+Insert>


Vi insert mode: <Ctrl+v>
Vi command mode: <Ctrl+v>

) Important

When using the Paste function, the entire contents of the clipboard
buffer is pasted
into the input buffer of PSReadLine. The input buffer is
then passed to the
PowerShell parser. Input pasted using the console
application's right-click paste
method is copied to the input buffer one
character at a time. The input buffer is
passed to the parser when a newline
character is copied. Therefore, the input is
parsed one line at a time. The
difference between paste methods results in different
execution behavior.
PasteAfter
Paste the clipboard after the cursor, moving the cursor to the end of the
pasted text.

Vi command mode: <p>

PasteBefore
Paste the clipboard before the cursor, moving the cursor to the end of the
pasted text.

Vi command mode: <P>

PrependAndAccept
Prepend a '#' and accept the line.

Vi command mode: <#>

Redo
Undo an undo.

Cmd: <Ctrl+y>
Vi insert mode: <Ctrl+y>
Vi command mode: <Ctrl+y>

RepeatLastCommand
Repeat the last text modification.

Vi command mode: <.>

RevertLine
Reverts all input to the current input.

Cmd: <Escape>
Emacs: <Alt+r> , <Escape,r>

ShellBackwardKillWord
Clear the input from the start of the current word to the cursor. If the cursor
is between
words, the input is cleared from the start of the previous word to
the cursor. The cleared
text is placed in the kill-ring.

Function is unbound.

ShellKillWord
Clear the input from the cursor to the end of the current word. If the cursor
is between
words, the input is cleared from the cursor to the end of the next
word. The cleared text
is placed in the kill-ring.

Function is unbound.

SwapCharacters
Swap the current character and the one before it.

Emacs: <Ctrl+t>
Vi insert mode: <Ctrl+t>
Vi command mode: <Ctrl+t>

Undo
Undo a previous edit.

Cmd: <Ctrl+z>
Emacs: <Ctrl+_> , <Ctrl+x,Ctrl+u>
Vi insert mode: <Ctrl+z>
Vi command mode: <Ctrl+z> , <u>

UndoAll
Undo all previous edits for line.

Vi command mode: <U>

UnixWordRubout
Clear the input from the start of the current word to the cursor. If the cursor
is between
words, the input is cleared from the start of the previous word to
the cursor. The cleared
text is placed in the kill-ring.

Emacs: <Ctrl+w>

ValidateAndAcceptLine
Attempt to execute the current input. If the current input is incomplete (for
example
there's a missing closing parenthesis, bracket, or quote) then the
continuation prompt is
displayed on the next line and PSReadLine waits for keys
to edit the current input.

Emacs: <Ctrl+m>

ViAcceptLine
Accept the line and switch to Insert mode.

Vi command mode: <Enter>

ViAcceptLineOrExit
Like DeleteCharOrExit in Emacs mode, but accepts the line instead of deleting a
character.

Vi insert mode: <Ctrl+d>


Vi command mode: <Ctrl+d>

ViAppendLine
A new line is inserted below the current line.

Vi command mode: <o>

ViBackwardDeleteGlob
Deletes the previous word, using only whitespace as the word delimiter.

Vi command mode: <d,B>

ViBackwardGlob
Moves the cursor back to the beginning of the previous word, using only
whitespace as
delimiters.
Vi command mode: <B>

ViDeleteBrace
Find the matching brace, parenthesis, or square bracket and delete all contents
within,
including the brace.

Vi command mode: <d,%>

ViDeleteEndOfGlob
Delete to the end of the word.

Vi command mode: <d,E>

ViDeleteGlob
Delete the next glob (whitespace delimited word).

Vi command mode: <d,W>

ViDeleteToBeforeChar
Deletes until given character.

Vi command mode: <d,t>

ViDeleteToBeforeCharBackward
Deletes until given character.

Vi command mode: <d,T>

ViDeleteToChar
Deletes until given character.

Vi command mode: <d,f>

ViDeleteToCharBackward
Deletes backwards until given character.
Vi command mode: <d,F>

ViInsertAtBegining
Switch to Insert mode and position the cursor at the beginning of the line.

Vi command mode: <I>

ViInsertAtEnd
Switch to Insert mode and position the cursor at the end of the line.

Vi command mode: <A>

ViInsertLine
A new line is inserted above the current line.

Vi command mode: <O>

ViInsertWithAppend
Append from the current line position.

Vi command mode: <a>

ViInsertWithDelete
Delete the current character and switch to Insert mode.

Vi command mode: <s>

ViJoinLines
Joins the current line and the next line.

Vi command mode: <J>

ViReplaceLine
Erase the entire command line.
Vi command mode: <S> , <c,c>

ViReplaceToBeforeChar
Replaces until given character.

Vi command mode: <c,t>

ViReplaceToBeforeCharBackward
Replaces until given character.

Vi command mode: <c,T>

ViReplaceToChar
Deletes until given character.

Vi command mode: <c,f>

ViReplaceToCharBackward
Replaces until given character.

Vi command mode: <c,F>

ViYankBeginningOfLine
Yank from the beginning of the buffer to the cursor.

Vi command mode: <y,0>

ViYankEndOfGlob
Yank from the cursor to the end of the WORD(s).

Vi command mode: <y,E>

ViYankEndOfWord
Yank from the cursor to the end of the word(s).
Vi command mode: <y,e>

ViYankLeft
Yank character(s) to the left of the cursor.

Vi command mode: <y,h>

ViYankLine
Yank the entire buffer.

Vi command mode: <y,y>

ViYankNextGlob
Yank from cursor to the start of the next WORD(s).

Vi command mode: <y,W>

ViYankNextWord
Yank the word(s) after the cursor.

Vi command mode: <y,w>

ViYankPercent
Yank to/from matching brace.

Vi command mode: <y,%>

ViYankPreviousGlob
Yank from beginning of the WORD(s) to cursor.

Vi command mode: <y,B>

ViYankPreviousWord
Yank the word(s) before the cursor.
Vi command mode: <y,b>

ViYankRight
Yank character(s) under and to the right of the cursor.

Vi command mode: <y,l> , <y,Space>

ViYankToEndOfLine
Yank from the cursor to the end of the buffer.

Vi command mode: <y,$>

ViYankToFirstChar
Yank from the first non-whitespace character to the cursor.

Vi command mode: <y,^>

Yank
Add the most recently killed text to the input.

Emacs: <Ctrl+y>

YankLastArg
Yank the last argument from the previous history line. With an argument, the
first time
it's invoked, behaves just like YankNthArg. If invoked multiple
times, instead it iterates
through history and arg sets the direction (negative
reverses the direction.)

Cmd: <Alt+.>
Emacs: <Alt+.> , <Alt+_> , <Escape,.> , <Escape,_>

YankNthArg
Yank the first argument (after the command) from the previous history line.
With an
argument, yank the nth argument (starting from 0), if the argument is
negative, start
from the last argument.

Emacs: <Ctrl+Alt+y> , <Escape,Ctrl+y>


YankPop
If the previous operation was Yank or YankPop, replace the previously yanked
text with
the next killed text from the kill-ring.

Emacs: <Alt+y> , <Escape,y>

Cursor movement functions

BackwardChar
Move the cursor one character to the left. This may move the cursor to the
previous line
of multi-line input.

Cmd: <LeftArrow>
Emacs: <LeftArrow> , <Ctrl+b>
Vi insert mode: <LeftArrow>
Vi command mode: <LeftArrow> , <Backspace> , <h>

BackwardWord
Move the cursor back to the start of the current word, or if between words, the
start of
the previous word. Word boundaries are defined by a configurable set
of characters.

Cmd: <Ctrl+LeftArrow>
Emacs: <Alt+b> , <Escape,b>
Vi insert mode: <Ctrl+LeftArrow>
Vi command mode: <Ctrl+LeftArrow>

The characters that define word boundaries are configured in the


WordDelimiters
property of the PSConsoleReadLineOptions object. To view or change the
WordDelimiters property, see
Get-PSReadLineOption and
Set-PSReadLineOption.

BeginningOfLine
If the input has multiple lines, move to the start of the current line, or if
already at the
start of the line, move to the start of the input. If the input
has a single line, move to the
start of the input.

Cmd: <Home>
Emacs: <Home> , <Ctrl+a>
Vi insert mode: <Home>
Vi command mode: <Home>

EndOfLine
If the input has multiple lines, move to the end of the current line, or if
already at the
end of the line, move to the end of the input. If the input has
a single line, move to the
end of the input.

Cmd: <End>
Emacs: <End> , <Ctrl+e>
Vi insert mode: <End>

ForwardChar
Move the cursor one character to the right. This may move the cursor to the
next line of
multi-line input.

Cmd: <RightArrow>
Emacs: <RightArrow> , <Ctrl+f>
Vi insert mode: <RightArrow>
Vi command mode: <RightArrow> , <Space> , <l>

ForwardWord
Move the cursor forward to the end of the current word, or if between words, to
the end
of the next word. Word boundaries are defined by a configurable set of
characters.

Emacs: <Alt+f> , <Escape,f>

The characters that define word boundaries are configured in the


WordDelimiters
property of the PSConsoleReadLineOptions object. To view or change the
WordDelimiters property, see
Get-PSReadLineOption and
Set-PSReadLineOption.

GotoBrace
Go to the matching brace, parenthesis, or square bracket.

Cmd: <Ctrl+]>
Vi insert mode: <Ctrl+]>
Vi command mode: <Ctrl+]>
GotoColumn
Move to the column indicated by arg.

Vi command mode: <|>

GotoFirstNonBlankOfLine
Move the cursor to the first non-blank character in the line.

Vi command mode: <^>

MoveToEndOfLine
Move the cursor to the end of the input.

Vi command mode: <End> , <$>

NextLine
Move the cursor to the next line.

Function is unbound.

NextWord
Move the cursor forward to the start of the next word. Word boundaries are
defined by
a configurable set of characters.

Cmd: <Ctrl+RightArrow>
Vi insert mode: <Ctrl+RightArrow>
Vi command mode: <Ctrl+RightArrow>

The characters that define word boundaries are configured in the


WordDelimiters
property of the PSConsoleReadLineOptions object. To view or change the
WordDelimiters property, see
Get-PSReadLineOption and
Set-PSReadLineOption.

NextWordEnd
Move the cursor forward to the end of the current word, or if between words, to
the end
of the next word. Word boundaries are defined by a configurable set of
characters.
Vi command mode: <e>

The characters that define word boundaries are configured in the


WordDelimiters
property of the PSConsoleReadLineOptions object. To view or change the
WordDelimiters property, see
Get-PSReadLineOption and
Set-PSReadLineOption.

PreviousLine
Move the cursor to the previous line.

Function is unbound.

ShellBackwardWord
Move the cursor back to the start of the current word, or if between words, the
start of
the previous word. Word boundaries are defined by PowerShell tokens.

Function is unbound.

ShellForwardWord
Move the cursor forward to the start of the next word. Word boundaries are
defined by
PowerShell tokens.

Function is unbound.

ShellNextWord
Move the cursor forward to the end of the current word, or if between words, to
the end
of the next word. Word boundaries are defined by PowerShell tokens.

Function is unbound.

ViBackwardWord
Move the cursor back to the start of the current word, or if between words,
the start of
the previous word. Word boundaries are defined by a configurable
set of characters.

Vi command mode: <b>

The characters that define word boundaries are configured in the


WordDelimiters
property of the PSConsoleReadLineOptions object. To view or change the
WordDelimiters property, see
Get-PSReadLineOption and
Set-PSReadLineOption.
ViEndOfGlob
Moves the cursor to the end of the word, using only whitespace as delimiters.

Vi command mode: <E>

ViEndOfPreviousGlob
Moves to the end of the previous word, using only whitespace as a word
delimiter.

Function is unbound.

ViGotoBrace
Similar to GotoBrace, but is character based instead of token based.

Vi command mode: <%>

ViNextGlob
Moves to the next word, using only whitespace as a word delimiter.

Vi command mode: <W>

ViNextWord
Move the cursor forward to the start of the next word. Word boundaries are
defined by
a configurable set of characters.

Vi command mode: <w>

The characters that define word boundaries are configured in the


WordDelimiters
property of the PSConsoleReadLineOptions object. To view or change the
WordDelimiters property, see
Get-PSReadLineOption and
Set-PSReadLineOption.

History functions

BeginningOfHistory
Move to the first item in the history.

Emacs: <Alt+<>
ClearHistory
Clears history in PSReadLine. This doesn't affect PowerShell history.

Cmd: <Alt+F7>

EndOfHistory
Move to the last item (the current input) in the history.

Emacs: <Alt+>>

ForwardSearchHistory
Perform an incremental forward search through history.

Cmd: <Ctrl+s>
Emacs: <Ctrl+s>

HistorySearchBackward
Replace the current input with the 'previous' item from PSReadLine history that
matches
the characters between the start and the input and the cursor.

Cmd: <F8>

HistorySearchForward
Replace the current input with the 'next' item from PSReadLine history that
matches the
characters between the start and the input and the cursor.

Cmd: <Shift+F8>

NextHistory
Replace the current input with the 'next' item from PSReadLine history.

Cmd: <DownArrow>
Emacs: <DownArrow> , <Ctrl+n>
Vi insert mode: <DownArrow>
Vi command mode: <DownArrow> , <j> , <+>
PreviousHistory
Replace the current input with the 'previous' item from PSReadLine history.

Cmd: <UpArrow>
Emacs: <UpArrow> , <Ctrl+p>
Vi insert mode: <UpArrow>
Vi command mode: <UpArrow> , <k> , <->

ReverseSearchHistory
Perform an incremental backward search through history.

Cmd: <Ctrl+r>
Emacs: <Ctrl+r>

ViSearchHistoryBackward
Prompts for a search string and initiates search upon AcceptLine.

Vi insert mode: <Ctrl+r>


Vi command mode: </> , <Ctrl+r>

Completion functions

Complete
Attempt to perform completion on the text surrounding the cursor. If there are
multiple
possible completions, the longest unambiguous prefix is used for
completion. If trying
to complete the longest unambiguous completion, a list of
possible completions is
displayed.

Emacs: <Tab>

MenuComplete
Attempt to perform completion on the text surrounding the cursor. If there are
multiple
possible completions, the longest unambiguous prefix is used for
completion. If trying
to complete the longest unambiguous completion, a list of
possible completions is
displayed.
Cmd: <Ctrl+Space>
Emacs: <Ctrl+Space>

PossibleCompletions
Display the list of possible completions.

Emacs: <Alt+=>
Vi insert mode: <Ctrl+Space>
Vi command mode: <Ctrl+Space>

TabCompleteNext
Attempt to complete the text surrounding the cursor with the next available
completion.

Cmd: <Tab>
Vi command mode: <Tab>

TabCompletePrevious
Attempt to complete the text surrounding the cursor with the previous available
completion.

Cmd: <Shift+Tab>
Vi command mode: <Shift+Tab>

ViTabCompleteNext
Ends the current edit group, if needed, and invokes TabCompleteNext.

Vi insert mode: <Tab>

ViTabCompletePrevious
Ends the current edit group, if needed, and invokes TabCompletePrevious.

Vi insert mode: <Shift+Tab>

Miscellaneous functions
CaptureScreen
Start interactive screen capture - up/down arrows select lines, enter copies
selected text
to clipboard as text and HTML.

Function is unbound.

ClearScreen
Clear the screen and draw the current line at the top of the screen.

Cmd: <Ctrl+l>
Emacs: <Ctrl+l>
Vi insert mode: <Ctrl+l>
Vi command mode: <Ctrl+l>

DigitArgument
Start a new digit argument to pass to other functions. You can use this as a
multiplier for
the next function that's invoked by a keypress. For example,
pressing <Alt+1> <Alt+0>
sets the digit-argument value to 10. Then,
pressing the # key sends 10 # characters
( ########## ) to the input line.
Similarly, you can use this with other operations, like
<Delete> or
Left-Arrow .

Cmd: <Alt+0> , <Alt+1> , <Alt+2> , <Alt+3> , <Alt+4> , <Alt+5> ,


<Alt+6> , <Alt+7> ,
<Alt+8> , <Alt+9> , <Alt+->

Emacs: <Alt+0> , <Alt+1> , <Alt+2> , <Alt+3> , <Alt+4> , <Alt+5> ,


<Alt+6> , <Alt+7> ,
<Alt+8> , <Alt+9> , <Alt+->

Vi command mode: <0> , <1> , <2> , <3> , <4> , <5> , <6> , <7> ,
<8> , <9>

InvokePrompt
Erases the current prompt and calls the prompt function to redisplay the
prompt. Useful
for custom key handlers that change state. For example, change
the current directory.

Function is unbound.

ScrollDisplayDown
Scroll the display down one screen.
Cmd: <PageDown>
Emacs: <PageDown>

ScrollDisplayDownLine
Scroll the display down one line.

Cmd: <Ctrl+PageDown>
Emacs: <Ctrl+PageDown>

ScrollDisplayToCursor
Scroll the display to the cursor.

Emacs: <Ctrl+End>

ScrollDisplayTop
Scroll the display to the top.

Emacs: <Ctrl+Home>

ScrollDisplayUp
Scroll the display up one screen.

Cmd: <PageUp>
Emacs: <PageUp>

ScrollDisplayUpLine
Scroll the display up one line.

Cmd: <Ctrl+PageUp>
Emacs: <Ctrl+PageUp>

SelfInsert
Insert the key.

Function is unbound.
ShowKeyBindings
Show all bound keys.

Cmd: <Ctrl+Alt+?>
Emacs: <Ctrl+Alt+?>
Vi insert mode: <Ctrl+Alt+?>

ViCommandMode
Switch the current operating mode from Vi-Insert to Vi-Command.

Vi insert mode: <Escape>

ViDigitArgumentInChord
Start a new digit argument to pass to other functions while in one of vi's
chords.

Function is unbound.

ViEditVisually
Edit the command line in a text editor specified by $env:EDITOR or
$env:VISUAL .

Emacs: <Ctrl+x,Ctrl+e>
Vi command mode: <v>

ViExit
Exits the shell.

Function is unbound.

ViInsertMode
Switch to Insert mode.

Vi command mode: <i>

WhatIsKey
Read a key and tell me what the key is bound to.
Cmd: <Alt+?>
Emacs: <Alt+?>

Selection functions

ExchangePointAndMark
The cursor is placed at the location of the mark and the mark is moved to the
location of
the cursor.

Emacs: <Ctrl+x,Ctrl+x>

SelectAll
Select the entire line.

Cmd: <Ctrl+a>

SelectBackwardChar
Adjust the current selection to include the previous character.

Cmd: <Shift+LeftArrow>
Emacs: <Shift+LeftArrow>

SelectBackwardsLine
Adjust the current selection to include from the cursor to the start of the
line.

Cmd: <Shift+Home>
Emacs: <Shift+Home>

SelectBackwardWord
Adjust the current selection to include the previous word.

Cmd: <Shift+Ctrl+LeftArrow>
Emacs: <Alt+B>

SelectForwardChar
Adjust the current selection to include the next character.

Cmd: <Shift+RightArrow>
Emacs: <Shift+RightArrow>

SelectForwardWord
Adjust the current selection to include the next word using ForwardWord.

Emacs: <Alt+F>

SelectLine
Adjust the current selection to include from the cursor to the end of the line.

Cmd: <Shift+End>
Emacs: <Shift+End>

SelectNextWord
Adjust the current selection to include the next word.

Cmd: <Shift+Ctrl+RightArrow>

SelectShellBackwardWord
Adjust the current selection to include the previous word using
ShellBackwardWord.

Function is unbound.

SelectShellForwardWord
Adjust the current selection to include the next word using ShellForwardWord.

Function is unbound.

SelectShellNextWord
Adjust the current selection to include the next word using ShellNextWord.

Function is unbound.
SetMark
Mark the current location of the cursor for use in a subsequent editing
command.

Emacs: <Ctrl+>

Search functions

CharacterSearch
Read a character and search forward for the next occurrence of that character.
If an
argument is specified, search forward (or backward if negative) for the
nth occurrence.

Cmd: <F3>
Emacs: <Ctrl+]>
Vi insert mode: <F3>
Vi command mode: <F3>

CharacterSearchBackward
Read a character and search backward for the next occurrence of that character.
If an
argument is specified, search backward (or forward if negative) for the
nth occurrence.

Cmd: <Shift+F3>
Emacs: <Ctrl+Alt+]>
Vi insert mode: <Shift+F3>
Vi command mode: <Shift+F3>

RepeatLastCharSearch
Repeat the last recorded character search.

Vi command mode: <;>

RepeatLastCharSearchBackwards
Repeat the last recorded character search, but in the opposite direction.

Vi command mode: <,>


RepeatSearch
Repeat the last search in the same direction as before.

Vi command mode: <n>

RepeatSearchBackward
Repeat the last search in the same direction as before.

Vi command mode: <N>

SearchChar
Read the next character and then find it, going forward, and then back off a
character.
This is for 't' functionality.

Vi command mode: <f>

SearchCharBackward
Read the next character and then find it, going backward, and then back off a
character.
This is for 'T' functionality.

Vi command mode: <F>

SearchCharBackwardWithBackoff
Read the next character and then find it, going backward, and then back off a
character.
This is for 'T' functionality.

Vi command mode: <T>

SearchCharWithBackoff
Read the next character and then find it, going forward, and then back off a
character.
This is for 't' functionality.

Vi command mode: <t>

SearchForward
Prompts for a search string and initiates search upon AcceptLine.

Vi insert mode: <Ctrl+s>


Vi command mode: <?> , <Ctrl+s>

Custom Key Binding Support APIs


The following functions are public in Microsoft.PowerShell.PSConsoleReadLine,
but can't
be directly bound to a key. Most are useful in custom key bindings.

C#

void AddToHistory(string command)

Add a command line to history without executing it.

C#

void ClearKillRing()

Clear the kill-ring. This is mostly used for testing.

C#

void Delete(int start, int length)

Delete length characters from start. This operation supports undo/redo.

C#

void Ding()

Perform the Ding action based on the user's preference.

C#

void GetBufferState([ref] string input, [ref] int cursor)

void GetBufferState([ref] Ast ast, [ref] Token[] tokens,

[ref] ParseError[] parseErrors, [ref] int cursor)

These two functions retrieve useful information about the current state of the
input
buffer. The first is more commonly used for simple cases. The second is
used if your
binding is doing something more advanced with the Ast.
C#

IEnumerable[Microsoft.PowerShell.KeyHandler]

GetKeyHandlers(bool includeBound, bool includeUnbound)

This function is used by Get-PSReadLineKeyHandler and probably isn't useful


in a custom
key binding.

C#

Microsoft.PowerShell.PSConsoleReadLineOptions GetOptions()

This function is used by Get-PSReadLineOption and probably isn't too useful in


a custom
key binding.

C#

void GetSelectionState([ref] int start, [ref] int length)

If there's no selection on the command line, the function returns -1 in both


start and
length. If there's a selection on the command line, the start and
length of the selection
are returned.

C#

void Insert(char c)

void Insert(string s)

Insert a character or string at the cursor. This operation supports undo/redo.

C#

string ReadLine(runspace remoteRunspace,

System.Management.Automation.EngineIntrinsics engineIntrinsics)

This is the main entry point to PSReadLine. It doesn't support recursion, so


isn't useful in
a custom key binding.

C#

void RemoveKeyHandler(string[] key)

This function is used by Remove-PSReadLineKeyHandler and probably isn't too


useful in
a custom key binding.

C#

void Replace(int start, int length, string replacement)

Replace some input. This operation supports undo/redo. This is preferred over
Delete
followed by Insert because it's treated as a single action for undo.

C#

void SetCursorPosition(int cursor)

Move the cursor to the given offset. Cursor movement isn't tracked for undo.

C#

void SetOptions(Microsoft.PowerShell.SetPSReadLineOption options)

This function is a helper method used by the cmdlet Set-PSReadLineOption , but


might
be useful to a custom key binding that wants to temporarily change a
setting.

C#

bool TryGetArgAsInt(System.Object arg, [ref] int numericArg,

int defaultNumericArg)

This helper method is used for custom bindings that honor DigitArgument. A
typical call
looks like

PowerShell

[int]$numericArg = 0

[Microsoft.PowerShell.PSConsoleReadLine]::TryGetArgAsInt($arg,

[ref]$numericArg, 1)

Notes
Behavior of the OnIdle event

When PSReadLine is in use, the OnIdle event is fired when ReadKey()


times out (no
typing in 300ms). The event could be signaled while the user is
in the middle of
editing a command line, for example, the user is reading
help to decide which
parameter to use.

Beginning in PSReadLine 2.2.0-beta4, OnIdle behavior changed to signal


the event
only if there's a ReadKey() timeout and the current editing
buffer is empty.

See Also
about_PSReadLine
Get-PSReadLineKeyHandler
Reference
Module: PSReadLine

Gets the key bindings for the PSReadLine module.

Syntax
PowerShell

Get-PSReadLineKeyHandler

[-Bound]

[-Unbound]

[<CommonParameters>]

Description
The Get-PSReadLineKeyHandler cmdlet returns the currently bound key bindings.

Examples

Example 1: Get all key mappings


This command returns all key mappings, bound and unbound.

PowerShell

Get-PSReadLineKeyHandler -Bound -Unbound

Key Function Description

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

Enter AcceptLine Accept the input or move to


the next line if input is missing a closing token.

Shift+Enter AddLine Move the cursor to the next


line without attempting to execute the input

Escape RevertLine Equivalent to undo all edits


(clears the line except lines imported from history)

LeftArrow BackwardChar Move the cursor back one


character

RightArrow ForwardChar Move the cursor forward one


character

Ctrl+LeftArrow BackwardWord Move the cursor to the


beginning of the current or previous word

Ctrl+RightArrow NextWord Move the cursor forward to the


start of the next word

Shift+LeftArrow SelectBackwardChar Adjust the current selection


to include the previous character
Shift+RightArrow SelectForwardChar Adjust the current selection
to include the next character

Ctrl+Shift+LeftArrow SelectBackwardWord Adjust the current selection


to include the previous word

Ctrl+Shift+RightArrow SelectNextWord Adjust the current selection


to include the next word

UpArrow PreviousHistory Replace the input with the


previous item in the history

DownArrow NextHistory Replace the input with the


next item in the history

Home BeginningOfLine Move the cursor to the


beginning of the line

End EndOfLine Move the cursor to the end of


the line

Shift+Home SelectBackwardsLine Adjust the current selection


to include from the cursor to the end of the line

Shift+End SelectLine Adjust the current selection


to include from the cursor to the start of the line

Delete DeleteChar Delete the character under the


cursor

Backspace BackwardDeleteChar Delete the character before


the cursor

Ctrl+Spacebar MenuComplete Complete the input if there is


a single completion, otherwise complete the input by selecting from a menu
o...

Tab TabCompleteNext Complete the input using the


next completion

Shift+Tab TabCompletePrevious Complete the input using the


previous completion

Ctrl+a SelectAll Select the entire line. Moves


the cursor to the end of the line

Ctrl+c CopyOrCancelLine Either copy selected text to


the clipboard, or if no text is selected, cancel editing the line with
Cancel...

Ctrl+C Copy Copy selected region to the


system clipboard. If no region is selected, copy the whole line

Ctrl+l ClearScreen Clear the screen and redraw


the current line at the top of the screen

Ctrl+r ReverseSearchHistory Search history backwards


interactively

...

Example 2: Get bound keys


This command returns only bound keys and key combinations.

PowerShell
Get-PSReadLineKeyHandler

Key Function Description

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

Enter AcceptLine Accept the input or move to


the next line if input is missing a closing token.

Shift+Enter AddLine Move the cursor to the next


line without attempting to execute the input

Escape RevertLine Equivalent to undo all edits


(clears the line except lines imported from history)

LeftArrow BackwardChar Move the cursor back one


character

RightArrow ForwardChar Move the cursor forward one


character

Ctrl+LeftArrow BackwardWord Move the cursor to the


beginning of the current or previous word

Ctrl+RightArrow NextWord Move the cursor forward to the


start of the next word

Shift+LeftArrow SelectBackwardChar Adjust the current selection


to include the previous character
Shift+RightArrow SelectForwardChar Adjust the current selection
to include the next character

Ctrl+Shift+LeftArrow SelectBackwardWord Adjust the current selection


to include the previous word

Ctrl+Shift+RightArrow SelectNextWord Adjust the current selection


to include the next word

UpArrow PreviousHistory Replace the input with the


previous item in the history

DownArrow NextHistory Replace the input with the


next item in the history

Home BeginningOfLine Move the cursor to the


beginning of the line

End EndOfLine Move the cursor to the end of


the line

Shift+Home SelectBackwardsLine Adjust the current selection


to include from the cursor to the end of the line

Shift+End SelectLine Adjust the current selection


to include from the cursor to the start of the line

Delete DeleteChar Delete the character under the


cursor

Backspace BackwardDeleteChar Delete the character before


the cursor

Ctrl+Spacebar MenuComplete Complete the input if there is


a single completion, otherwise complete the input by selecting from a menu
o...

Tab TabCompleteNext Complete the input using the


next completion

...

Parameters
-Bound

Indicates that this cmdlet returns functions that are bound.

Type: SwitchParameter

Position: Named

Default value: True

Accept pipeline input: False

Accept wildcard characters: False

-Unbound

Indicates that this cmdlet returns functions that are unbound.

Type: SwitchParameter

Position: Named

Default value: True

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
KeyHandler

This cmdlet returns a KeyHandler object.

Related Links
Remove-PSReadLineKeyHandler
Get-PSReadLineOption
Set-PSReadLineOption
Set-PSReadLineKeyHandler
Get-PSReadLineOption
Reference
Module: PSReadLine

Gets values for the options that can be configured.

Syntax
PowerShell

Get-PSReadLineOption []

Description
The Get-PSReadLineOption cmdlet returns the current state of the settings that can be
configured
by using the Set-PSReadLineOption cmdlet. You can use the returned object
to change
PSReadLine options. This provides a slightly simpler way to set syntax
coloring options for
multiple kinds of tokens.

Examples

Example 1: Get options and their values


PowerShell

Get-PSReadLineOption

EditMode : Windows

AddToHistoryHandler :
System.Func`2[System.String,System.Object]

HistoryNoDuplicates : True

HistorySavePath :
C:\Users\username\AppData\Roaming\Microsoft\Windows\

PowerShell\PSReadLine\ConsoleHost_history.txt

HistorySaveStyle : SaveIncrementally

HistorySearchCaseSensitive : False

HistorySearchCursorMovesToEnd : False

MaximumHistoryCount : 4096

ContinuationPrompt : >>

ExtraPromptLineCount : 0

PromptText : {> }

BellStyle : Audible

DingDuration : 50

DingTone : 1221

CommandsToValidateScriptBlockArguments : {ForEach-Object, %, Invoke-Command,


icm...}

CommandValidationHandler :

CompletionQueryItems : 100

MaximumKillRingCount : 10

ShowToolTips : True

ViModeIndicator : None

WordDelimiters : ;:,.[]{}()/\|^&*-=+'"---

AnsiEscapeTimeout : 100

CommandColor : "$([char]0x1b)[93m"

CommentColor : "$([char]0x1b)[32m"

ContinuationPromptColor : "$([char]0x1b)[37m"

DefaultTokenColor : "$([char]0x1b)[37m"

EmphasisColor : "$([char]0x1b)[96m"

ErrorColor : "$([char]0x1b)[91m"

KeywordColor : "$([char]0x1b)[92m"

MemberColor : "$([char]0x1b)[97m"

NumberColor : "$([char]0x1b)[97m"

OperatorColor : "$([char]0x1b)[90m"

ParameterColor : "$([char]0x1b)[90m"

SelectionColor : "$([char]0x1b)[30;47m"

StringColor : "$([char]0x1b)[36m"

TypeColor : "$([char]0x1b)[37m"

VariableColor : "$([char]0x1b)[92m"

This command returns the list of available PSReadLine options and their current values.

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
PSConsoleReadLineOptions

This cmdlet returns an instance of the current options. Changing the property values of
this object
updates the settings in PSReadLine directly without invoking Set-
PSReadLineOption .

Related Links
Remove-PSReadLineKeyHandler
Get-PSReadLineKeyHandler
Set-PSReadLineOption
Set-PSReadLineKeyHandler
PSConsoleHostReadLine
Reference
Module: PSReadLine

This function is the main entry point for PSReadLine.

Syntax
PowerShell

PSConsoleHostReadLine

Description
PSConsoleHostReadLine is the main entry point for the PSReadLine module. The
PowerShell console
host automatically loads the PSReadLine module and calls this
function. Under normal operating
conditions, this function is not intended to be used
from the command line.

The extension point PSConsoleHostReadLine is special to the console host. The host calls
any
alias, function, or script with this name. PSReadLine defines this function so that it is
called
from the console host.

Examples

Example 1
This function is not intended to be used from the command line.

PowerShell

Inputs
None
Outputs
None

Related Links
about_PSReadLine
Remove-PSReadLineKeyHandler
Reference
Module: PSReadLine

Removes a key binding.

Syntax
PowerShell

Remove-PSReadLineKeyHandler

[-Chord] <String[]>

[-ViMode <ViMode>]

[<CommonParameters>]

Description
The Remove-PSReadLineKeyHandler cmdlet removes a specified key binding.

Examples

Example 1: Remove a binding


PowerShell

Remove-PSReadLineKeyHandler -Chord Ctrl+B

This command removes the binding from the key combination, or chord, Ctrl+B . The
Ctrl+B chord is
created in the Set-PSReadLineKeyHandler article.

Parameters
-Chord

Specifies an array of keys or sequences of keys to be removed. A single binding is


specified by
using a single string. If the binding is a sequence of keys, separate the
keys by a comma, as in
the following example:
Ctrl+x,Ctrl+l

This parameter accepts an array of strings. Each string is a separate binding, not a
sequence of
keys for a single binding.

Type: String[]

Aliases: Key

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ViMode

Specify which vi mode the binding applies to. Possible values are: Insert, Command.

Type: ViMode

Accepted values: Insert, Command

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

This cmdlet returns no output.

Related Links
Get-PSReadLineKeyHandler
Get-PSReadLineOption
Set-PSReadLineOption
Set-PSReadLineKeyHandler
Set-PSReadLineKeyHandler
Reference
Module: PSReadLine

Binds keys to user-defined or PSReadLine key handler functions.

Syntax
PowerShell

Set-PSReadLineKeyHandler

[-ScriptBlock] <ScriptBlock>

[-BriefDescription <String>]

[-Description <String>]

[-Chord] <String[]>

[-ViMode <ViMode>]

[<CommonParameters>]

PowerShell

Set-PSReadLineKeyHandler

[-Chord] <String[]>

[-ViMode <ViMode>]

[-Function] <String>

[<CommonParameters>]

Description
The Set-PSReadLineKeyHandler cmdlet customizes the result when a key or sequence of
keys is
pressed. With user-defined key bindings, you can do almost anything that is
possible from within a
PowerShell script.

Examples

Example 1: Bind the arrow key to a function


This command binds the up arrow key to the HistorySearchBackward function. This
function
searches command history for command lines that start with the current
contents of the command line.
PowerShell

Set-PSReadLineKeyHandler -Chord UpArrow -Function HistorySearchBackward

Example 2: Bind a key to a script block


This example shows how a single key can be used to run a command. The command
binds the key Ctrl+B
to a script block that clears the line, inserts the word "build", and
then accepts the line.

PowerShell

Set-PSReadLineKeyHandler -Chord Ctrl+B -ScriptBlock {

[Microsoft.PowerShell.PSConsoleReadLine]::RevertLine()

[Microsoft.PowerShell.PSConsoleReadLine]::Insert('build')

[Microsoft.PowerShell.PSConsoleReadLine]::AcceptLine()

Parameters
-BriefDescription

A brief description of the key binding. This description is displayed by the


Get-
PSReadLineKeyHandler cmdlet.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Chord

The key or sequence of keys to be bound to a function or script block. Use a single
string to
specify a single binding. If the binding is a sequence of keys, separate the
keys by a comma, as in
the following example:

Ctrl+X,Ctrl+L
7 Note

As of PSReadLine 2.0.0, the Chord parameter is case-sensitive. Meaning,


Ctrl +
X and Ctrl + x create different bindings.

This parameter accepts an array of strings. Each string is a separate binding, not a
sequence of
keys for a single binding.

Type: String[]

Aliases: Key

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Description

Specifies a more detailed description of the key binding that is visible in the output
of the
Get-PSReadLineKeyHandler cmdlet.

Type: String

Aliases: LongDescription

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Function

Specifies the name of an existing key handler provided by PSReadLine. This


parameter lets you rebind
existing key bindings, or bind a handler that is currently
unbound.

Type: String

Position: 1
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ScriptBlock

Specifies a script block value to run when the chord is entered. PSReadLine passes
one or two
parameters to this script block. The first parameter is a ConsoleKeyInfo
object representing the
key pressed. The second argument can be any object
depending on the context.

Type: ScriptBlock

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ViMode

Specify which vi mode the binding applies to.

Valid values are:

Insert
Command

Type: ViMode

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.


Outputs
None

This cmdlet returns no output.

Related Links
Get-PSReadLineKeyHandler
Remove-PSReadLineKeyHandler
Get-PSReadLineOption
Set-PSReadLineOption
Set-PSReadLineOption
Reference
Module: PSReadLine

Customizes the behavior of command line editing in PSReadLine.

Syntax
PowerShell

Set-PSReadLineOption

[-EditMode <EditMode>]

[-ContinuationPrompt <String>]
[-HistoryNoDuplicates]

[-AddToHistoryHandler <System.Func[System.String,System.Object]>]

[-CommandValidationHandler
<System.Action[System.Management.Automation.Language.CommandAst]>]

[-HistorySearchCursorMovesToEnd]

[-MaximumHistoryCount <Int32>]
[-MaximumKillRingCount <Int32>]

[-ShowToolTips]

[-ExtraPromptLineCount <Int32>]

[-DingTone <Int32>]

[-DingDuration <Int32>]

[-BellStyle <BellStyle>]

[-CompletionQueryItems <Int32>]

[-WordDelimiters <String>]

[-HistorySearchCaseSensitive]

[-HistorySaveStyle <HistorySaveStyle>]

[-HistorySavePath <String>]

[-AnsiEscapeTimeout <Int32>]

[-PromptText <String[]>]

[-ViModeIndicator <ViModeStyle>]

[-ViModeChangeHandler <ScriptBlock>]

[-Colors <Hashtable>]

[<CommonParameters>]

Description
The Set-PSReadLineOption cmdlet customizes the behavior of the PSReadLine module
when you're
editing the command line. To view the PSReadLine settings, use Get-
PSReadLineOption .

Examples
Example 1: Set foreground and background colors
This example sets PSReadLine to display the Comment token with green foreground
text on a
gray background. In the escape sequence used in the example, 32 represents
the foreground color
and 47 represents the background color.

PowerShell

Set-PSReadLineOption -Colors @{ "Comment"="$([char]0x1b)[32;47m" }

You can choose to set only a foreground text color. For example, a bright green
foreground text
color for the Comment token: "Comment"="$([char]0x1b)[92m" .

Example 2: Set bell style


In this example, PSReadLine will respond to errors or conditions that require user
attention.
The BellStyle is set to emit an audible beep at 1221 Hz for 60 ms.

PowerShell

Set-PSReadLineOption -BellStyle Audible -DingTone 1221 -DingDuration 60

7 Note

This feature may not work in all hosts on platforms.

Example 3: Set multiple options


Set-PSReadLineOption can set multiple options with a hash table.

PowerShell

$PSReadLineOptions = @{

EditMode = "Emacs"

HistoryNoDuplicates = $true

HistorySearchCursorMovesToEnd = $true

Colors = @{

"Command" = "#8181f7"

Set-PSReadLineOption @PSReadLineOptions
The $PSReadLineOptions hash table sets the keys and values. Set-PSReadLineOption uses
the keys
and values with @PSReadLineOptions to update the PSReadLine options.

You can view the keys and values entering the hash table name, $PSReadLineOptions on
the
PowerShell command line.

Example 4: Set multiple color options


This example shows how to set more than one color value in a single command.

PowerShell

Set-PSReadLineOption -Colors @{

Command = 'Magenta'

Number = 'DarkGray'
Member = 'DarkGray'
Operator = 'DarkGray'
Type = 'DarkGray'
Variable = 'DarkGreen'

Parameter = 'DarkGreen'

ContinuationPrompt = 'DarkGray'
Default = 'DarkGray'
}

Example 5: Set color values for multiple types


This example shows three different methods for how to set the color of tokens displayed
in
PSReadLine.

PowerShell

Set-PSReadLineOption -Colors @{

# Use a ConsoleColor enum

"Error" = [ConsoleColor]::DarkRed

# 24 bit color escape sequence

"String" = "$([char]0x1b)[38;5;100m"

# RGB value

"Command" = "#8181f7"

Example 6: Use ViModeChangeHandler to display Vi


mode changes
This example emits a cursor change VT escape in response to a Vi mode change.

PowerShell

function OnViModeChange {

if ($args[0] -eq 'Command') {

# Set the cursor to a blinking block.

Write-Host -NoNewLine "$([char]0x1b)[1 q"

} else {

# Set the cursor to a blinking line.

Write-Host -NoNewLine "$([char]0x1b)[5 q"

Set-PSReadLineOption -ViModeIndicator Script -ViModeChangeHandler


$Function:OnViModeChange

The OnViModeChange function sets the cursor options for the Vi modes: insert and
command.
ViModeChangeHandler uses the Function: provider to reference
OnViModeChange as a script
block object.

For more information, see


about_Providers.

Parameters
-AddToHistoryHandler

Specifies a ScriptBlock that controls which commands get added to PSReadLine


history.

The ScriptBlock receives the command line as input.

The ScripBlock should return a member of the AddToHistoryOption enum, the


string name of
one of those members, or a boolean value. The list below describes
the possible values and their
effects.

MemoryAndFile - Add the command to the history file and the current session.
MemoryOnly - Add the command to history for the current session only.

SkipAdding - Don't add the command to the history file for current session.
$false - Same as if the value was SkipAdding .

$true - Same as if the value was MemoryAndFile .

Type: Func<T,TResult>[System.String,System.Object]

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-AnsiEscapeTimeout

This option is specific to Windows when input is redirected, for example, when
running under tmux
or screen .

With redirected input on Windows, many keys are sent as a sequence of characters
starting with the
escape character. It's impossible to distinguish between a single
escape character followed by
more characters and a valid escape sequence.

The assumption is that the terminal can send the characters faster than a user types.
PSReadLine
waits for this timeout before concluding that it has received a complete
escape sequence.

If you see random or unexpected characters when you type, you can adjust this
timeout.

Type: Int32

Position: Named

Default value: 100

Accept pipeline input: False

Accept wildcard characters: False

-BellStyle

Specifies how PSReadLine responds to various error and ambiguous conditions.

The valid values are as follows:

Audible: A short beep.


Visual: Text flashes briefly.
None: No feedback.

Type: BellStyle

Position: Named

Default value: Audible


Accept pipeline input: False

Accept wildcard characters: False

-Colors

The Colors parameter specifies various colors used by PSReadLine.

The argument is a hash table where the keys specify which element and the values
specify the color.
For more information, see about_Hash_Tables.

Colors can be either a value from ConsoleColor, for example [ConsoleColor]::Red ,


or a valid
ANSI escape sequence. Valid escape sequences depend on your terminal.
In PowerShell 5.0, an example
escape sequence for red text is $([char]0x1b)[91m . In
PowerShell 6 and above, the same escape
sequence is `e[91m . You can specify other
escape sequences including the following types:

256 color
24-bit color
Foreground, background, or both
Inverse, bold

For more information about ANSI color codes, see ANSI escape code in Wikipedia.

The valid keys include:

ContinuationPrompt: The color of the continuation prompt.


Emphasis: The emphasis color. For example, the matching text when searching
history.
Error: The error color. For example, in the prompt.
Selection: The color to highlight the menu selection or selected text.
Default: The default token color.
Comment: The comment token color.
Keyword: The keyword token color.
String: The string token color.
Operator: The operator token color.
Variable: The variable token color.
Command: The command token color.
Parameter: The parameter token color.
Type: The type token color.
Number: The number token color.
Member: The member name token color.
Type: Hashtable

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-CommandValidationHandler

Specifies a ScriptBlock that is called from ValidateAndAcceptLine. If an exception is


thrown, validation fails and the error is reported.

Before throwing an exception, the validation handler can place the cursor at the
point of the error
to make it easier to fix. A validation handler can also change the
command line, such as to correct
common typographical errors.

ValidateAndAcceptLine is used to avoid cluttering your history with commands that


can't work.

Type: Action<T>[CommandAst]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-CompletionQueryItems

Specifies the maximum number of completion items that are shown without
prompting.

If the number of items to show is greater than this value, PSReadLine prompts
yes/no before
displaying the completion items.

Type: Int32

Position: Named

Default value: 100

Accept pipeline input: False

Accept wildcard characters: False


-ContinuationPrompt

Specifies the string displayed at the beginning of the subsequent lines when multi-
line input is
entered. The default is double greater-than signs ( >> ). An empty string
is valid.

Type: String

Position: Named

Default value: >>

Accept pipeline input: False

Accept wildcard characters: False

-DingDuration

Specifies the duration of the beep when BellStyle is set to Audible.

Type: Int32

Position: Named

Default value: 50ms

Accept pipeline input: False

Accept wildcard characters: False

-DingTone

Specifies the tone in Hertz (Hz) of the beep when BellStyle is set to Audible.

Type: Int32

Position: Named

Default value: 1221

Accept pipeline input: False

Accept wildcard characters: False

-EditMode
Specifies the command line editing mode. Using this parameter resets any key
bindings set by
Set-PSReadLineKeyHandler .

The valid values are as follows:

Windows: Key bindings emulate PowerShell, cmd, and Visual Studio.


Emacs: Key bindings emulate Bash or Emacs.
Vi: Key bindings emulate Vi.

Use Get-PSReadLineKeyHandler to see the key bindings for the currently configured
EditMode.

Type: EditMode

Position: Named

Default value: Windows

Accept pipeline input: False

Accept wildcard characters: False

-ExtraPromptLineCount

Specifies the number of extra lines.

If your prompt spans more than one line, specify a value for this parameter. Use this
option when
you want extra lines to be available when PSReadLine displays the
prompt after showing some
output. For example, PSReadLine returns a list of
completions.

This option is needed less than in previous versions of PSReadLine, but is useful
when the
InvokePrompt function is used.

Type: Int32

Position: Named

Default value: 0

Accept pipeline input: False

Accept wildcard characters: False

-HistoryNoDuplicates
This option controls the recall behavior. Duplicate commands are still added to the
history file.
When this option is set, only the most recent invocation appears when
recalling commands. Repeated
commands are added to history to preserve ordering
during recall. However, you typically don't want
to see the command multiple times
when recalling or searching the history.

By default, the HistoryNoDuplicates property of the global


PSConsoleReadLineOptions object
is set to True . Using this SwitchParameter sets
the property value to True . To change the
property value, you must specify the value
of the SwitchParameter as follows:
-HistoryNoDuplicates:$False .

Using the following command, you can set the property value directly:

(Get-PSReadLineOption).HistoryNoDuplicates = $False

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-HistorySavePath

Specifies the path to the file where history is saved. Computers running Windows or
non-Windows
platforms store the file in different locations. The filename is stored in
a variable
$($Host.Name)_history.txt , for example ConsoleHost_history.txt .

If you don't use this parameter, the default path is:

$env:APPDATA\Microsoft\Windows\PowerShell\PSReadLine\$($Host.Name)_history.txt

Type: String

Position: Named

Default value: A file named $($Host.Name)_history.txt in


$env:APPDATA\Microsoft\Windows\PowerShell\PSReadLine on
Windows and $env:XDG_DATA_HOME/powershell/PSReadLine
or $HOME/.local/share/powershell/PSReadLine on non-
Windows platforms

Accept pipeline input: False


Accept wildcard characters: False

-HistorySaveStyle

Specifies how PSReadLine saves history.

Valid values are as follows:

SaveIncrementally: Save history after each command is executed and share


across multiple
instances of PowerShell.
SaveAtExit: Append history file when PowerShell exits.
SaveNothing: Don't use a history file.

Type: HistorySaveStyle

Position: Named

Default value: SaveIncrementally

Accept pipeline input: False

Accept wildcard characters: False

-HistorySearchCaseSensitive

Specifies that history searching is case-sensitive in functions like


ReverseSearchHistory or
HistorySearchBackward.

By default, the HistorySearchCaseSensitive property of the global


PSConsoleReadLineOptions
object is set to False . Using this SwitchParameter sets
the property value to True . To
change the property value back, you must specify the
value of the SwitchParameter as follows:
-HistorySearchCaseSensitive:$False .

Using the following command, you can set the property value directly:

(Get-PSReadLineOption).HistorySearchCaseSensitive = $False

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


-HistorySearchCursorMovesToEnd

Indicates that the cursor moves to the end of commands that you load from history
by using a search.
When this parameter is set to $False , the cursor remains at the
position it was when you pressed
the up or down arrows.

By default, the HistorySearchCursorMovesToEnd property of the global


PSConsoleReadLineOptions object is set to False . Using this SwitchParameter set
the
property value to True . To change the property value back, you must specify the
value of the
SwitchParameter as follows: -HistorySearchCursorMovesToEnd:$False .

Using the following command, you can set the property value directly:

(Get-PSReadLineOption).HistorySearchCursorMovesToEnd = $False

Type: SwitchParameter

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-MaximumHistoryCount

Specifies the maximum number of commands to save in PSReadLine history.

PSReadLine history is separate from PowerShell history.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-MaximumKillRingCount

Specifies the maximum number of items stored in the kill ring.

Type: Int32

Position: Named
Default value: 10

Accept pipeline input: False

Accept wildcard characters: False

-PromptText

When there's a parse error, PSReadLine changes a part of the prompt red.
PSReadLine analyzes
your prompt function to determine how to change only the
color of part of your prompt. This analysis
isn't 100% reliable.

Use this option if PSReadLine is changing your prompt in unexpected ways. Include
any trailing
whitespace.

For example, if your prompt function looked like the following example:

function prompt { Write-Host -NoNewLine -ForegroundColor Yellow "$pwd"; return


"# " }

Then set:

Set-PSReadLineOption -PromptText "# "

Type: String[]

Position: Named

Default value: >

Accept pipeline input: False

Accept wildcard characters: False

-ShowToolTips

When displaying possible completions, tooltips are shown in the list of completions.

This option is enabled by default. This option wasn't enabled by default in prior
versions of
PSReadLine. To disable, set this option to $False .

By default, the ShowToolTips property of the global PSConsoleReadLineOptions


object is set to True . Using this SwitchParameter sets the property value to True . To
change
the property value, you must specify the value of the SwitchParameter as
follows:
-ShowToolTips:$False .
Using the following command, you can set the property value directly:

(Get-PSReadLineOption).ShowToolTips = $False

Type: SwitchParameter

Position: Named

Default value: True

Accept pipeline input: False

Accept wildcard characters: False

-ViModeChangeHandler

When the ViModeIndicator is set to Script , the script block provided will be
invoked every
time the mode changes. The script block is provided one argument of
type ViMode .

This parameter was introduced in PowerShell 7.

Type: ScriptBlock

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ViModeIndicator

This option sets the visual indication for the current Vi mode. Either insert mode or
command
mode.

The valid values are as follows:

None: There's no indication.


Prompt: The prompt changes color.
Cursor: The cursor changes size.
Script: User-specified text is printed.

Type: ViModeStyle

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WordDelimiters

Specifies the characters that delimit words for functions like ForwardWord or
KillWord.

Type: String

Position: Named

Default value: ;:,.[]{}()/\|^&*-=+'"---

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
None

This cmdlet returns no output.

Related Links
about_PSReadLine
Get-PSReadLineKeyHandler
Get-PSReadLineOption
Remove-PSReadLineKeyHandler
Set-PSReadLineKeyHandler
PSScheduledJob
Reference

The PSScheduledJob module contains cmdlets and providers that manage scheduled
jobs in Windows
PowerShell.

PSScheduledJob
Add-JobTrigger Adds job triggers to scheduled jobs.

Disable-JobTrigger Disables the job triggers of scheduled jobs.

Disable-ScheduledJob Disables a scheduled job.

Enable-JobTrigger Enables the job triggers of scheduled jobs.

Enable-ScheduledJob Enables a scheduled job.

Get-JobTrigger Gets the job triggers of scheduled jobs.

Get-ScheduledJob Gets scheduled jobs on the local computer.

Get-ScheduledJobOption Gets the job options of scheduled jobs.

New-JobTrigger Creates a job trigger for a scheduled job.

New-ScheduledJobOption Creates an object that contains advanced options for a


scheduled job.

Register-ScheduledJob Creates a scheduled job.

Remove-JobTrigger Delete job triggers from scheduled jobs.

Set-JobTrigger Changes the job trigger of a scheduled job.

Set-ScheduledJob Changes scheduled jobs.

Set-ScheduledJobOption Changes the job options of a scheduled job.

Unregister-ScheduledJob Deletes scheduled jobs on the local computer.


about_Scheduled_Jobs
Article • 11/15/2022 • 5 minutes to read

Short description
Describes scheduled jobs and explains how to use and manage scheduled jobs in
PowerShell and in Task Scheduler.

Long description
PowerShell scheduled jobs are a useful hybrid of PowerShell background jobs and
Task
Scheduler tasks.

Like PowerShell background jobs, scheduled jobs run asynchronously in the


background. Instances of scheduled jobs that have run can be managed by using
the
job cmdlets, such as Start-Job , Get-Job , Stop-Job , and Receive-Job .

Like Task Scheduler tasks, scheduled jobs are saved to disk. You can view and
manage
the jobs in Task Scheduler, enable and disable them as needed, run them
or use them as
templates, establish a one-time or recurring schedules for
starting the jobs, or set
conditions under which the jobs start.

In addition, the results of scheduled job instances are saved to disk in an


easily
accessible format, providing a running log of job output. Scheduled jobs
come with a
customized set of cmdlets for managing them. The cmdlets let you
create, edit, manage,
disable, and re-enable scheduled jobs, job triggers and
job options.

This comprehensive and flexible set of tools make scheduled jobs an essential
component of many professional PowerShell IT solutions.

The scheduled job cmdlets are included in the PSScheduledJob module that is
installed
with PowerShell. This module was introduced in PowerShell 3.0 and
works in PowerShell
3.0 and later versions of PowerShell. For more information
about the cmdlets contained
in the PSScheduledJob module, see PSScheduledJob.

For more information about PowerShell background jobs, see about_Jobs.

For more information about Task Scheduler, see Task Scheduler.

7 Note
You can view and manage PowerShell scheduled jobs in Task Scheduler. The
PowerShell jobs and scheduled job cmdlets work only on scheduled jobs that
are
created in PowerShell.

Quick start
This example creates a scheduled job that starts every day at 3:00 AM and runs
the Get-
Process cmdlet. The job starts even if the computer is running on
batteries.

PowerShell

$trigger = New-JobTrigger -Daily -At 3AM

$options = New-ScheduledJobOption -StartIfOnBattery

Register-ScheduledJob -Name ProcessJob -ScriptBlock {Get-Process} `

-Trigger $trigger -ScheduledJobOption $options

The Get-ScheduledJob cmdlet gets the scheduled jobs on the local computer.

PowerShell

Get-ScheduledJob

Output

Id Name Triggers Command Enabled

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

7 ProcessJob {1} Get-Process True

Get-JobTrigger gets the job triggers of ProcessJob. The input parameters


specify the

scheduled job, not the trigger, because triggers are saved in a


scheduled job.

PowerShell

Get-JobTrigger -Name ProcessJob

Output

Id Frequency Time DaysOfWeek Enabled

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

1 Daily 11/5/2011 3:00:00 AM True

This example uses the ContinueIfGoingOnBattery parameter of the


Set-ScheduledJob
cmdlet to change the StopIfGoingOnBatteries property of
ProcessJob to False.

PowerShell

Get-ScheduledJob -Name ProcessJob | Set-ScheduledJobOption `

-ContinueIfGoingOnBattery -Passthru

Output

StartIfOnBatteries : True

StopIfGoingOnBatteries : False

WakeToRun : True

StartIfNotIdle : True

StopIfGoingOffIdle : False

RestartOnIdleResume : False

IdleDuration : 00:10:00
IdleTimeout : 01:00:00
ShowInTaskScheduler : True

RunElevated : False

RunWithoutNetwork : True

DoNotAllowDemandStart : False

MultipleInstancePolicy : IgnoreNew

JobDefinition :
Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition

The Get-ScheduledJob cmdlet gets the ProcessJob scheduled job.

PowerShell

Get-ScheduledJob ProcessJob

Output

Id Name Triggers Command Enabled

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

7 ProcessJob {1} Get-Process True

The Get-Job cmdlet gets all instances of the ProcessJob scheduled job
that have run
thus far. The Get-Job cmdlet gets scheduled jobs only when the
PSScheduledJob
module is imported into the current session.

 Tip
Notice that you use the scheduled job cmdlets to manage scheduled jobs, but
you
use the job cmdlets to manage instances of scheduled jobs.

PowerShell

Get-Job -Name ProcessJob

Output

Id Name PSJobTypeName State HasMoreData Location Command

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

45 ProcessJob PSScheduledJob Completed True localhost Get-


Process

46 ProcessJob PSScheduledJob Completed True localhost Get-


Process

47 ProcessJob PSScheduledJob Completed True localhost Get-


Process

48 ProcessJob PSScheduledJob Completed True localhost Get-


Process

49 ProcessJob PSScheduledJob Completed True localhost Get-


Process

50 ProcessJob PSScheduledJob Completed True localhost Get-


Process

51 ProcessJob PSScheduledJob Completed True localhost Get-


Process

The Receive-Job cmdlet gets the results of the most recent instance of the
ProcessJob
scheduled job (ID = 51).

PowerShell

Receive-Job -ID 51

Even though the Receive-Job command did not include the Keep parameter,
the results
of the job are saved on disk until you delete them or the maximum
number of results
are exceeded.

The job results are no longer available in this session, but if you start a new
session or
open a new PowerShell window, the results of the job are available
again.

The following command uses the DefinitionName parameter of the Start-Job


cmdlet
to start the ProcessJob scheduled job.

Jobs that are started by using the Start-Job cmdlet are standard PowerShell
background jobs, not instances of the scheduled job. Like all background jobs,
these
jobs start immediately, they aren't subject to job options or affected by
job triggers, and
their output is not saved in the output directory of the
scheduled job directory.

PowerShell

Start-Job -DefinitionName ProcessJob

The Unregister-ScheduledJob cmdlet deletes the ProcessJob scheduled job


and all
saved results of its job instances.

PowerShell

Unregister-ScheduledJob ProcessJob

Scheduled jobs concepts


A scheduled job runs commands or a script. A scheduled job can include job
triggers
that start the job and job options that set conditions for running the
job.

A job trigger starts a scheduled job automatically. A job trigger can include a
one-time
or recurring schedule or specify an event, such as when a user logs on
or Windows
starts. A scheduled job can have one or more job triggers, and you
can create, add,
enable, disable, and get job triggers.

Job triggers are optional. You can start scheduled jobs immediately by using
the Start-
Job cmdlet , or by adding the RunNow parameter to your
Register-ScheduledJob

command.

Job options set the conditions for running a scheduled job. Every scheduled job
has one
job options object. You can create and edit job options objects and add
them to one or
more scheduled jobs.

Each time a scheduled job starts, a job instance is created. Use the PowerShell
job
cmdlets to view and manage the job instance.

Scheduled jobs are saved to disk and use the cmdlet verb, Register , instead
of New . The
XML files are located on the local computer in the directory
$HOME\AppData\Local\Microsoft\Windows\PowerShell\ScheduledJobs .

PowerShell creates a directory for each scheduled job and saves the job
commands, job
triggers, job options and job results in the scheduled job
directory. Job triggers and job
options aren't saved to disk independently.
They are saved in the scheduled job XML of
each scheduled job with which they
are associated.

Scheduled jobs, job triggers, and job options appear in PowerShell as objects.
The
objects are interlinked, which makes them easy to discover and use in
commands and
scripts.

Scheduled jobs appear as ScheduledJobDefinition objects. The


ScheduledJobDefinition
object has a JobTriggers property that contains
the job triggers of the scheduled job
and an Options property that contains
the job options. The ScheduledJobTriggers and
ScheduledJobOptions
objects that represent job triggers and job options, respectively,
each have a
JobDefinition property that contains the scheduled job with which they are
associated. This recursive interconnection makes it easy to find the triggers
and options
of a scheduled job and to find, script, and display the scheduled
job to which any job
trigger or job option is associated.

See also
about_Scheduled_Jobs_Basics
about_Scheduled_Jobs_Advanced
about_Scheduled_Jobs_Troubleshooting
PSScheduledJob module cmdlets
Task Scheduler
about_Scheduled_Jobs_Advanced
Article • 11/15/2022 • 5 minutes to read

Short description
Explains advanced scheduled job topics, including the file structure that
underlies
scheduled jobs.

Long description
For more information about the cmdlets contained in the PSScheduledJob
module, see
PSScheduledJob.

Scheduled job directories and files


PowerShell scheduled jobs are both PowerShell jobs and Task Scheduler tasks.
Each
scheduled job is registered in Task Scheduler and saved on disk in
Microsoft .NET
Framework Serialization XML format.

When you create a scheduled job, PowerShell creates a directory for the
scheduled job
in the
$HOME\AppData\Local\Microsoft\Windows\PowerShell\ScheduledJobs directory on
the local computer. The directory name is the same as the job name.

The following is a sample ScheduledJobs directory.

PowerShell

Get-ChildItem $HOME\AppData\Local\Microsoft\Windows\PowerShell\ScheduledJobs

Output

Directory: C:\Users\User01\AppData\Local

\Microsoft\Windows\PowerShell\ScheduledJobs

Mode LastWriteTime Length Name

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

d---- 9/29/2011 10:03 AM ArchiveProjects

d---- 9/30/2011 1:18 PM Inventory

d---- 10/20/2011 9:15 AM Backup-Scripts

d---- 11/7/2011 10:40 AM ProcessJob

d---- 11/2/2011 10:25 AM SecureJob

d---- 9/27/2011 1:29 PM Test-HelpFiles

d---- 9/26/2011 4:22 PM DeployPackage

Each scheduled job has its own directory. The directory contains the scheduled
job XML
file and an Output subdirectory.

PowerShell

$Path = "$HOME\AppData\Local\Microsoft\Windows\PowerShell"

$Path += "\ScheduledJobs\ProcessJob"

Get-ChildItem $Path

Output

Directory: C:\Users\User01\AppData\Local\Microsoft\Windows\PowerShell

\ScheduledJobs\ProcessJob

Mode LastWriteTime Length Name

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

d---- 11/1/2011 3:00 PM Output

-a--- 11/1/2011 3:43 PM 7281 ScheduledJobDefinition.xml

The Output directory for a scheduled job contains its execution history.
Each time a job
trigger starts a scheduled job, PowerShell creates a
timestamp-named directory in the
output directory. The timestamp directory
contains the results of the job in a
Results.xml file and the job status in
a Status.xml file.

The following command shows the execution history directories for the
ProcessJob
scheduled job.

PowerShell

$Path = "$HOME\AppData\Local\Microsoft"

$Path += "\Windows\PowerShell\ScheduledJobs\ProcessJob\Output"

Get-ChildItem $Path

Output

Directory: C:\Users\User01\AppData\Local\Microsoft

\Windows\PowerShell\ScheduledJobs\ProcessJob\Output

Mode LastWriteTime Length Name

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

d---- 11/2/2011 3:00 AM 20111102-030002-260

d---- 11/3/2011 3:00 AM 20111103-030002-277

d---- 11/4/2011 3:00 AM 20111104-030002-209

d---- 11/5/2011 3:00 AM 20111105-030002-251

d---- 11/6/2011 3:00 AM 20111106-030002-174

d---- 11/7/2011 12:00 AM 20111107-000001-914

d---- 11/7/2011 3:00 AM 20111107-030002-376

PowerShell

$Path = "$HOME\AppData\Local\Microsoft\Windows\PowerShell\"

$Path += "ScheduledJobs\ProcessJob\Output\20111102-030002-260"

Get-ChildItem $Path

Output

Directory: C:\Users\User01\AppData\Local\Microsoft\Windows\PowerShell

\ScheduledJobs\ProcessJob\Output\20111102-030002-260

Mode LastWriteTime Length Name

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

-a--- 11/2/2011 3:00 AM 581106 Results.xml

-a--- 11/2/2011 3:00 AM 9451 Status.xml

You can open and examine the ScheduledJobDefinition.xml, Results.xml


and Status.xml
files or use the Select-XML cmdlet to parse the files.

2 Warning

Do not edit the XML files. If any XML file contains invalid XML, PowerShell
deletes
the scheduled job and its execution history, including job results.

Start a scheduled job immediately


You can start a scheduled job immediately in one of two ways:

Run the Start-Job cmdlet to start any scheduled job.


Add the RunNow parameter to your Register-ScheduledJob command to start
the
job as soon as the command is run.

Jobs that are started by using the Start-Job cmdlet are standard PowerShell
background jobs, not instances of the scheduled job. Like all background jobs,
these
jobs start immediately, they aren't subject to job options or affected by
job triggers. The
job output isn't saved in the Output directory of the
scheduled job directory.

The following command uses the DefinitionName parameter of the Start-Job


cmdlet
to start the ProcessJob scheduled job.
PowerShell

Start-Job -DefinitionName ProcessJob

To manage the job and get the job results, use the job cmdlets. For more
information
about the job cmdlets, see about_Jobs.

7 Note

To use the Job cmdlets on instances of scheduled jobs, the PSScheduledJob


module must be imported into the session. To import the PSScheduledJob
module,
type Import-Module PSScheduledJob or use any scheduled job cmdlet,
such as Get-
ScheduledJob .

Rename a scheduled job


To rename a scheduled job, use the Name parameter of the Set-ScheduledJob
cmdlet.
When you rename a scheduled job, PowerShell changes the name of the
scheduled job
and the scheduled job directory. However, it doesn't change the
names of instances of
the scheduled job that have already run.

Get start and end times


To get the dates and times that job instances started and ended, use the
PSBeginTime
and PSEndTime properties of the ScheduledJob object that
Get-Job returns for
scheduled jobs.

The following example uses the Property parameter of the Format-Table


cmdlet to
display the PSBeginTime and PSEndTime properties of each job
instance in a table. A
calculated property named Label displays the elapsed
time of each job instance.

PowerShell

Get-job -Name UpdateHelpJob |

Format-Table -Property ID, PSBeginTime, PSEndTime,

@{Label="Elapsed Time";Expression={$.PsEndTime - $.PSBeginTime}}

Output

Id PSBeginTime PSEndTime Elapsed Time

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

2 11/3/2011 3:00:01 AM 11/3/2011 3:00:39 AM 00:00:38.0053854

3 11/4/2011 3:00:02 AM 11/4/2011 3:01:01 AM 00:00:59.1188475

4 11/5/2011 3:00:02 AM 11/5/2011 3:00:50 AM 00:00:48.3692034

5 11/6/2011 3:00:01 AM 11/6/2011 3:00:54 AM 00:00:52.8013036

6 11/7/2011 3:00:01 AM 11/7/2011 3:00:38 AM 00:00:37.1930350

7 11/8/2011 3:00:01 AM 11/8/2011 3:00:57 AM 00:00:56.2570556

8 11/9/2011 3:00:03 AM 11/9/2011 3:00:55 AM 00:00:51.8142222

9 11/10/2011 3:00:02 AM 11/10/2011 3:00:42 AM 00:00:40.7195954

Manage execution history


You can determine the number of job instance results that are saved for each
scheduled
job and delete the execution history and saved job results of any
scheduled job.

The ExecutionHistoryLength property of a scheduled job determines how many


job
instance results are saved for the scheduled job. When the number of saved
results
exceeds the value of the ExecutionHistoryLength property,
PowerShell deletes the
results of the oldest instance to make room for the
results of the newest instance.

By default, PowerShell saves the execution history and results of 32 instances


of each
scheduled job. To change that value, use the MaxResultCount
parameters of the
Register-ScheduledJob or Set-ScheduledJob cmdlets.

To delete the execution history and all results for a scheduled job, use the
ClearExecutionHistory parameter of the Set-ScheduledJob cmdlet. Deleting
this
execution history does not prevent PowerShell from saving the results of
new instances
of the scheduled job.

The following example uses splatting to create $JobParms which are parameter
values
that are passed to the Register-ScheduledJob cmdlet. For more
information, see
about_Splatting.md.
The Register-ScheduledJob uses @JobParms to create a scheduled
job. The
command uses the MaxResultCount parameter with a value of 12 to save only
the 12 newest job instance results of the scheduled job.

PowerShell

$JobParms = @{

Name = "ProcessJob"

ScriptBlock = {Get-Process}

MaxResultCount = "12"

Register-ScheduledJob @JobParms

The following command uses the MaxResultCount parameter of the


Set-ScheduledJob
cmdlet to increase the number of saved instance results to
15.

PowerShell

Get-ScheduledJob ProcessJob | Set-ScheduledJob -MaxResultCount 15

The following command deletes the execution history and the current saved
results of
the ProcessJob scheduled job.

PowerShell

Get-ScheduledJob ProcessJob | Set-ScheduledJob -ClearExecutionHistory

The following command gets the values of the name and


ExecutionHistoryLength
properties of all scheduled jobs on the computer and
displays them in a table.

PowerShell

Get-ScheduledJob |

Format-Table -Property Name, ExecutionHistoryLength -AutoSize

See also
about_Scheduled_Jobs
about_Scheduled_Jobs_Basics
about_Scheduled_Jobs_Troubleshooting
about_Splatting.md
PSScheduledJob module cmdlets
Task Scheduler
about_Scheduled_Jobs_Basics
Article • 09/19/2022 • 7 minutes to read

Short description
Explains how to create and manage scheduled jobs.

Long description
This document shows how to perform basic tasks of creating and managing
scheduled
jobs. For information about more advanced tasks, see about_Scheduled_Jobs_Advanced.

For more information about the cmdlets contained in the PSScheduledJob


module, see
PSScheduledJob.

How to create a scheduled job


To create a scheduled job, use the Register-ScheduledJob cmdlet. The cmdlet
requires a
name and the commands or script that the job runs. You can either
run the job
immediately by adding the RunNow parameter, or create a job
trigger and set job
options when you create the job, or edit an existing job.

To create a job that runs a script, use the FilePath parameter to specify
the path to the
script file. To create a job that runs commands, use the
ScriptBlock parameter.

The Register-ScheduledJob cmdlet creates the ProcessJob, which runs a


Get-Process
command. This scheduled job has the default job options and no
job trigger.

PowerShell

Register-ScheduledJob -Name ProcessJob -ScriptBlock { Get-Process }

Output

Id Name Triggers Command Enabled

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

8 ProcessJob {} Get-Process True

How to create a job trigger


Job triggers start a scheduled job automatically. A job trigger can be one-time
or
recurring schedule or an event, such as when a user logs on or Windows
starts. Each job
can have zero, one, or multiple job triggers.

To create a job trigger, use the New-JobTrigger cmdlet. The following command
creates
a job trigger that starts a job every Monday and Thursday at 5:00 AM.
The command
saves the job trigger in the $T variable.

PowerShell

$T = New-JobTrigger -Weekly -DaysOfWeek "Monday", "Thursday" -At "5:00 AM"

Job triggers are optional. You can start a scheduled job at any time by adding
the
RunNow parameter to your Register-ScheduledJob command, or by using
the Start-
Job cmdlets.

How to add a job trigger


When you add a job trigger to a scheduled job, the job trigger is added to the
scheduled job XML file for the scheduled job and becomes part of the scheduled
job.

You can add a job trigger to a scheduled job when you create the scheduled job,
or edit
an existing job. You can change the job trigger of a scheduled job at
any time.

PowerShell uses some of the same job triggers that Task Scheduler uses. For
detailed
information about job triggers, see the help topic for the New-JobTrigger
cmdlet.

The following example uses splatting to create $JobParms which are parameter
values
that are passed to the Register-ScheduledJob cmdlet. For more
information, see
about_Splatting.md.
The Register-ScheduledJob uses @JobParms to create a scheduled
job. It uses
the Trigger parameter to specify the job trigger in the $T variable.

PowerShell

$JobParms = @{

Name = "ProcessJob"

ScriptBlock = {Get-Command}

Trigger = $T

Register-ScheduledJob @JobParms

You can also add a job trigger to an existing scheduled job at any time. The
Add-
JobTrigger cmdlet adds the job trigger in the $T variable to the
ProcessJob scheduled
job.

PowerShell

Add-JobTrigger -Name ProcessJob -Trigger $T

As a result, the job trigger starts the ProcessJob automatically every


Monday and
Thursday at 5:00 AM.

How to get a job trigger


To get the job trigger of a scheduled job, use the Get-JobTrigger cmdlet. Use
the Name,
ID, and InputObject parameters to specify the scheduled
job, not the job trigger.

Get-JobTrigger gets the job trigger of the ProcessJob.

PowerShell

Get-JobTrigger -Name ProcessJob

Output

Id Frequency Time DaysOfWeek Enabled

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

1 Weekly 11/7/2011 5:00:00 AM {Monday, Thursday} True

How to create job options


Job options establish conditions for starting and running the job. Every job
has the
default job options unless you change them. Because job options can
prevent a job
from running at the scheduled time, it is important to understand
the job options and
use them carefully.

PowerShell uses the same job options that Task Scheduler uses. For detailed
information
about the job options, see the help topic for New-ScheduledJobOption.

Job options are stored in the scheduled job XML file. You can set job options
when you
create a scheduled job or change them at any time.
The New-ScheduledJobOption cmdlet creates a scheduled job option in which the
WakeToRun scheduled job option is set to True. The WakeToRun option
runs the
scheduled job even if the computer is in the Sleep or Hibernate state
at the scheduled
start time. The command saves the job options in the $O
variable.

PowerShell

$O = New-ScheduledJobOption -WakeToRun

How to get job options


To get the job options of a scheduled job, use the Get-ScheduledJobOption
cmdlet. Use
the Name, ID, and InputObject parameters to specify the
scheduled job, not the job
options.

Get-ScheduledJobOption gets the job options of the ProcessJob.

PowerShell

Get-ScheduledJobOption -Name ProcessJob

Output

StartIfOnBatteries : False

StopIfGoingOnBatteries : True

WakeToRun : False

StartIfNotIdle : True

StopIfGoingOffIdle : False

RestartOnIdleResume : False

IdleDuration : 00:10:00
IdleTimeout : 01:00:00
ShowInTaskScheduler : True

RunElevated : False

RunWithoutNetwork : True

DoNotAllowDemandStart : False

MultipleInstancePolicy : IgnoreNew

JobDefinition :
Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition

How to change job options


You can change the job options of a scheduled job when you create a scheduled
job or
edit an existing job.
The splatted $JobParms are passed to the Add-JobTrigger cmdlet to create
the process
job. It uses the ScheduledJobOption parameter to specify the
job options in the $O
variable.

PowerShell

$JobParms = @{

Name = "ProcessJob"

ScriptBlock = {Get-Process}

ScheduledJobOption = $O

Add-JobTrigger @JobParms

You can also change the job options to an existing scheduled job at any time.
The
following command uses the Set-ScheduledJobOption cmdlet to change the
value of the
WakeToRun option of the ProcessJob scheduledJob to
True.

The Set cmdlets in the PSScheduledJob module, such as the


Set-ScheduledJobOption
cmdlet, don't have Name or ID parameters. You
can use the InputObject parameter to
specify the scheduled job options or
pipe a scheduled job from Get-ScheduledJobOption
cmdlet to
Set-ScheduledJobOption .

This example uses the Get-ScheduledJob cmdlet to get the ProcessJob. It uses
the Get-
ScheduledJobOption cmdlet to get the job options in the
ProcessJob and the Set-

ScheduledJobOption cmdlet to change the


WakeToRun job option in the ProcessJob to

True.

PowerShell

Get-ScheduledJob -Name ProcessJob | Get-ScheduledJobOption |

Set-ScheduledJobOption -WakeToRun

How to get scheduled job instances


When a scheduled job is started, PowerShell creates a job instance that is
similar to a
standard PowerShell background job. You can use the job cmdlets,
such as Get-Job ,
Stop-Job and Receive-Job to manage the job instances.

7 Note
To use the job cmdlets on instances of scheduled jobs, the PSScheduledJob
module must be imported into the session. To import the PSScheduledJob
module,
type Import-Module PSScheduledJob or use any scheduled job cmdlet,
such as Get-
ScheduledJob .

To get all instances of PowerShell scheduled jobs, and all active standard
jobs, use the
Get-Job cmdlet. The Import-Module cmdlet imports the
PSScheduledJob module and

Get-Job gets the jobs on the local computer.

PowerShell

Import-Module PSScheduledJob

Get-Job

Get-Job gets instances of ProcessJob on the local computer.

PowerShell

Get-Job -Name ProcessJob

Output

Id Name PSJobTypeName State HasMoreData Location Command

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

45 ProcessJob PSScheduledJob Completed True localhost Get-


Process

46 ProcessJob PSScheduledJob Completed True localhost Get-


Process

47 ProcessJob PSScheduledJob Completed True localhost Get-


Process

48 ProcessJob PSScheduledJob Completed True localhost Get-


Process

49 ProcessJob PSScheduledJob Completed True localhost Get-


Process

50 ProcessJob PSScheduledJob Completed True localhost Get-


Process

51 ProcessJob PSScheduledJob Completed True localhost Get-


Process

The default display does not show the start time, which typically distinguishes
instances
of the same scheduled job.

The Get-Job cmdlet sends objects down the pipeline. The Format-Table cmdlet
displays
the Name, ID, and BeginTime properties of the scheduled
job.
PowerShell

Get-Job ProcessJob | Format-Table -Property Name, ID, BeginTime

Output

Name Id BeginTime

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

ProcessJob 43 11/2/2011 3:00:02 AM

ProcessJob 44 11/3/2011 3:00:02 AM

ProcessJob 45 11/4/2011 3:00:02 AM

ProcessJob 46 11/5/2011 3:00:02 AM

ProcessJob 47 11/6/2011 3:00:02 AM

ProcessJob 48 11/7/2011 12:00:01 AM

ProcessJob 49 11/7/2011 3:00:02 AM

ProcessJob 50 11/8/2011 3:00:02 AM

Get scheduled job results


To get the results of an instance of a scheduled job, use the Receive-Job
cmdlet.

7 Note

To use the Job cmdlets on instances of scheduled jobs, the PSScheduledJob


module must be imported into the session. To import the PSScheduledJob
module,
type Import-Module PSScheduledJob or use any scheduled job cmdlet,
such as Get-
ScheduledJob .

This examples gets the results of the newest instance of the


ProcessJob scheduled job
(ID = 51).

PowerShell

Import-Module PSScheduledJob

Receive-Job -ID 51 -Keep

The results of scheduled jobs are saved on disk, so the Keep parameter of
Receive-Job
is not required. However, without the Keep parameter, you can
get the results of a
scheduled job only once in each PowerShell session. To
start a new PowerShell session,
type PowerShell or open a new PowerShell
window.

See also
about_Scheduled_Jobs
about_Scheduled_Jobs_Advanced
about_Scheduled_Jobs_Troubleshooting
about_Splatting.md
PSScheduledJob module cmdlets
Task Scheduler
about_Scheduled_Jobs_Troubleshooting
Article • 11/15/2022 • 11 minutes to read

Short description
Explains how to resolve problems with scheduled jobs

Long description
This document describes some of the problems that you might experience when
using
the scheduled job features of PowerShell and it suggests solutions to
these problems.

Before using PowerShell scheduled jobs, see about_Scheduled_Jobs


and the related
scheduled jobs about topics.

For more information about the cmdlets contained in the PSScheduledJob


module, see
PSScheduledJob.

Can't find job results

Basic method for getting job results in PowerShell


When a scheduled job runs, it creates an instance of the scheduled job. To
view,
manage, and get the results of scheduled job instances, use the Job
cmdlets.

7 Note

To use the Job cmdlets on instances of scheduled jobs, the PSScheduledJob


module must be imported into the session. To import the PSScheduledJob
module,
type Import-Module PSScheduledJob or use any scheduled job cmdlet,
such as Get-
ScheduledJob .

To get a list of all instances of a scheduled job, use the Get-Job cmdlet.

PowerShell

Import-Module PSScheduledJob

Get-Job ProcessJob

Output

Id Name PSJobTypeName State HasMoreData Location

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

43 ProcessJob PSScheduledJob Completed False localhost

44 ProcessJob PSScheduledJob Completed False localhost

45 ProcessJob PSScheduledJob Completed False localhost

46 ProcessJob PSScheduledJob Completed False localhost

47 ProcessJob PSScheduledJob Completed False localhost

48 ProcessJob PSScheduledJob Completed False localhost

49 ProcessJob PSScheduledJob Completed False localhost

50 ProcessJob PSScheduledJob Completed False localhost

The Get-Job cmdlet sends ProcessJob objects down the pipeline. The
Format-Table
cmdlet displays the Name, ID, and PSBeginTime
properties of a scheduled job instance
in a table.

PowerShell

Get-Job ProcessJob | Format-Table -Property Name, ID, PSBeginTime -Auto

Output

Name Id PSBeginTime

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

ProcessJob 43 11/2/2011 3:00:02 AM

ProcessJob 44 11/3/2011 3:00:02 AM

ProcessJob 45 11/4/2011 3:00:02 AM

ProcessJob 46 11/5/2011 3:00:02 AM

ProcessJob 47 11/6/2011 3:00:02 AM

ProcessJob 48 11/7/2011 12:00:01 AM

ProcessJob 49 11/7/2011 3:00:02 AM

ProcessJob 50 11/8/2011 3:00:02 AM

To get the results of an instance of a scheduled job, use the Receive-Job


cmdlet. The
following command gets the results of the newest instance of the
ProcessJob (ID = 50).

PowerShell

Receive-Job -ID 50

Basic method for finding job results on disk


To manage scheduled jobs, use the job cmdlets, such as Get-Job and
Receive-Job .
If Get-Job does not get the job instance or Receive-Job does not get the
job results,
you can search the execution history files for the job on disk.
The execution history
contains a record of all triggered job instances.

Verify that there is a timestamp-named directory in the directory for a


scheduled job in
the following path:

$HOME\AppData\Local\Microsoft\Windows\PowerShell\ScheduledJob\

<ScheduledJobName>\Output

For example:

C:\Users<UserName>\AppData\Local\Microsoft\Windows\PowerShell\ScheduledJob\
<ScheduledJobName>\Output

For example, the Get-ChildItem cmdlet gets the on-disk execution history of
the
ProcessJob scheduled job.

PowerShell

$Path = '$HOME\AppData\Local\Microsoft\Windows\PowerShell'

$Path += '\ScheduledJobs\ProcessJob\Output'

Get-ChildItem $Path

Output

Directory: C:\Users\User01\AppData\Local\Microsoft\Windows\PowerShell

\ScheduledJobs\ProcessJob\Output

Mode LastWriteTime Length Name

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

d---- 11/2/2011 3:00 AM 20111102-030002-260

d---- 11/3/2011 3:00 AM 20111103-030002-277

d---- 11/4/2011 3:00 AM 20111104-030002-209

d---- 11/5/2011 3:00 AM 20111105-030002-251

d---- 11/6/2011 3:00 AM 20111106-030002-174

d---- 11/7/2011 12:00 AM 20111107-000001-914

d---- 11/7/2011 3:00 AM 20111107-030002-376

Each timestamp-named directory represents a job instance. The results of each


job
instance are saved in a Results.xml file in the timestamp-named
directory.

For example, the following command gets the Results.xml files for every
saved instance
of the ProcessJob scheduled job. If the Results.xml file
is missing, PowerShell cannot
return or display the job results.
PowerShell

$Path = '$HOME\AppData\Local\Microsoft\Windows\PowerShell'

$Path += '\ScheduledJobs\ProcessJob\Output\*\Results.xml'

Get-ChildItem $Path

Output

Directory: C:\Users\User01\Appdata\Local\Microsoft\Windows\PowerShell

\ScheduledJobs\ProcessJob\Output

The job cmdlet might not be able to get scheduled job instances or their
results because
the PSScheduledJob module is not imported into the session.

7 Note

Before using a job cmdlet on scheduled job instances, verify that the
PSScheduledJob module is included in the session. Without the
PSScheduledJob
module, the job cmdlets cannot get scheduled job instances
or their results.

To import the PSScheduledJob module:

PowerShell

Import-Module PSScheduledJob

Receive-Job cmdlet might already have returned the


results
If Receive-Job does not return job instance results, it might be because a
Receive-Job
command has been run for that job instance in the current session
without the Keep
parameter.

When you use Receive-Job without the Keep parameter, Receive-Job


returns the job
results and sets the job instance's HasMoreData property to
False. The False value
means that Receive-Job returned the job's
results and the instance has no more results
to return. This setting is
appropriate for standard background jobs, but not for instances
of scheduled
jobs, which are saved to disk.

To get the job instance results again, start a new PowerShell session by typing
PowerShell . Import the PSScheduledJob module, and try the Receive-Job
command
again.

PowerShell

Receive-Job -ID 50

Output

#No results

PowerShell

PowerShell.exe

Output

Windows PowerShell

Copyright (C) 2012 Microsoft Corporation. All rights reserved.

PowerShell

Import-Module PSScheduledJob

Receive-Job -ID 50

Output

Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName

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

1213 33 12348 21676 88 25.71 1608 CcmExec

29 4 1168 2920 43 0.02 748 conhost

46 6 2208 4612 45 0.03 1640 conhost

Using Keep parameter to get results more than one time


in a session
To get the result of a job instance more than one time in a session, use the
Keep
parameter of the Receive-Job cmdlet.

PowerShell

Import-Module PSScheduledJob

Receive-Job -ID 50 -Keep

Output

Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName

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

1213 33 12348 21676 88 25.71 1608 CcmExec

29 4 1168 2920 43 0.02 748 conhost

46 6 2208 4612 45 0.03 1640 conhost

PowerShell

Receive-Job -ID 50 -Keep

Output

Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName

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

1213 33 12348 21676 88 25.71 1608 CcmExec

29 4 1168 2920 43 0.02 748 conhost

46 6 2208 4612 45 0.03 1640 conhost

The scheduled job might be corrupted


If a scheduled job becomes corrupted, PowerShell deletes the corrupted
scheduled job
and its results. You cannot recover the results of a corrupted
scheduled job.

To determine if a scheduled job still exists, use the Get-ScheduledJob


cmdlet.

PowerShell

Get-ScheduledJob

The number of results might have exceeded the


ExecutionHistoryLength
The ExecutionHistoryLength property of a scheduled job determines how many
job
instances, and their results, are saved to disk. The default value is 32.
When the number
of instances of a scheduled job exceeds this value, PowerShell
deletes the oldest job
instance to make room for each new job instance.

To get the value of the ExecutionHistoryLength property of a scheduled job,


use the
following command format:

PowerShell
(Get-ScheduledJob <JobName>).ExecutionHistoryLength

For example, the following command gets the value of the


ExecutionHistoryLength
property of the ProcessJob scheduled job.

PowerShell

(Get-ScheduledJob ProcessJob).ExecutionHistoryLength

To set or change the value of the ExecutionHistoryLength property, use the


MaxResultCount parameter of the Register-ScheduledJob and
Set-ScheduledJob
cmdlets.

The following command increases the value of the ExecutionHistoryLength


property to
50.

PowerShell

Get-ScheduledJob ProcessJob | Set-ScheduledJob -MaxResultCount 50

The job instance results might have been deleted


The ClearExecutionHistory parameter of the Set-ScheduledJob cmdlet
deletes the
execution history of a job. You can use this feature to free up
disk space or delete results
that are not needed, or already used, analyzed or
saved in a different location.

To delete the execution history of a scheduled job, use the


ClearExecutionHistory
parameter of the scheduled job.

The following command deletes the execution history of the ProcessJob


scheduled job.

PowerShell

Get-ScheduledJob ProcessJob | Set-ScheduledJob -ClearExecutionHistory

Also, the Remove-Job cmdlet deletes job results. When you use Remove-Job to
delete a
scheduled job, it deletes all instances of the job on disk, including
the execution history
and all job results.

Jobs started by using the Start-Job cmdlet are not saved


to disk
When you use Start-Job to start a scheduled job, instead of using a job
trigger, Start-
Job starts a standard background job. The background job and
its results are not stored
in the execution history of the job on disk.

You can use the Get-Job cmdlet to get the job and the Receive-Job cmdlet to
get the
job results, but the results are available only until you receive them,
unless you use the
Keep parameter of the Receive-Job cmdlet.

Also, background jobs and their results are session-specific; they exist only
in the
session in which they are created. If you delete the job with
Remove-Job , close the
session or close PowerShell, the job instance and its
results are deleted.

Scheduled job doesn't run


Scheduled jobs don't run automatically if the job triggers or the scheduled job
are
disabled.

Use the Get-ScheduledJob cmdlet to get the scheduled job. Verify that the
value of the
Enabled property of the scheduled job is True.

PowerShell

Get-ScheduledJob ProcessJob

Output

Id Name Triggers Command Enabled

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

4 ProcessJob {1, 2} Get-Process True

PowerShell

(Get-ScheduledJob ProcessJob).Enabled

Output

True

Use the Get-JobTrigger cmdlet to get the job triggers of the scheduled job.
Verify that
the value of the Enabled property of the job trigger is
True.

PowerShell
Get-ScheduledJob ProcessJob | Get-JobTrigger

Output

Id Frequency Time DaysOfWeek Enabled

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

1 Weekly 11/7/2011 5:00:00 AM {Monday, Thursday} True

2 Daily 11/7/2011 3:00:00 PM True

PowerShell

Get-ScheduledJob ProcessJob|Get-JobTrigger|Format-Table ID, Enabled -Auto

Output

Id Enabled

-- -------

1 True

2 True

Scheduled jobs don't run automatically if job triggers are


invalid
For example, a job trigger might specify a date in the past or a date that does
not occur,
such as the 5th Monday of the month.

Scheduled jobs do not run automatically if the conditions of the job trigger or
the job
options are not satisfied.

For example, a scheduled job that runs only when a particular user logs on to
the
computer will not run if that user does not log on or only connects
remotely.

Examine the options of the scheduled job and make sure that they are satisfied.
For
example, a scheduled job that requires that the computer be idle or
requires a network
connection, or has a long IdleDuration or a brief
IdleTimeout might never run.

Use the Get-ScheduledJobOption cmdlet to examine the job options and their
values.

PowerShell

Get-ScheduledJobOption -Name ProcessJob

Output
StartIfOnBatteries : False

StopIfGoingOnBatteries : True

WakeToRun : True

StartIfNotIdle : True

StopIfGoingOffIdle : False

RestartOnIdleResume : False

IdleDuration : 00:10:00
IdleTimeout : 01:00:00
ShowInTaskScheduler : True

RunElevated : False

RunWithoutNetwork : True

DoNotAllowDemandStart : False

MultipleInstancePolicy : IgnoreNew

JobDefinition :
Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition

For descriptions of the scheduled job options, see New-ScheduledJobOption.

The scheduled job instance might have failed


If a scheduled job command fails, PowerShell reports it immediately by
generating an
error message. However, if the job fails when Task Scheduler
tries to run it, the error is
not available to PowerShell.

Use the following methods to detect and correct job failures:

Check the Task Scheduler event log for errors. To check the log, use Event
Viewer or a
PowerShell command such as the following:

PowerShell

Get-WinEvent -LogName Microsoft-Windows-TaskScheduler/Operational |

Where {$_.Message -like "fail"}

Check the job record in Task Scheduler. PowerShell scheduled jobs are stored in
the
following Task Scheduled folder:

Task Scheduler Library\Microsoft\Windows\PowerShell\ScheduledJobs

The scheduled job might not run because of insufficient


permission
Scheduled jobs run with the permissions of the user who created the job or the
permissions of the user who is specified by the Credential parameter in the
Register-
ScheduledJob or Set-ScheduledJob command.
If that user does not have permission to run the commands or scripts, the job
fails.

Can't get scheduled job or scheduled job is


corrupted
On rare occasions, scheduled jobs can become corrupted or contain internal
contradictions that cannot be resolved. Typically, this happens when the XML
files for
the scheduled job are manually edited, resulting in invalid XML.

When a scheduled job is corrupted, PowerShell attempts to delete the scheduled


job, its
execution history, and its results from disk.

If it cannot remove the scheduled job, you will get a corrupted job error
message each
time you run the Get-ScheduledJob cmdlet.

To remove a corrupted scheduled job, use either one of the following methods:

Delete the <ScheduledJobName> directory for the scheduled job. Don't delete
the
ScheduledJob directory.

The directory's location:

$env:UserProfile\AppData\Local\Microsoft\Windows\PowerShell\ScheduledJobs<Scheduled

JobName>

For example:

C:\Users<UserName>\AppData\Local\Microsoft\Windows\PowerShell\ScheduledJobs<Schedul
edJobName>.

Use Task Scheduler to delete the scheduled job. PowerShell scheduled tasks
appear in
the following Task Scheduler path:

Task Scheduler

Library\Microsoft\Windows\PowerShell\ScheduledJobs<ScheduledJobName>

Job cmdlets can't consistently find scheduled


jobs
When the PSScheduledJob module isn't in the current session, the job
cmdlets cannot
get scheduled jobs, start them, or get their results.
To import the PSScheduledJob module, type Import-Module PSScheduledJob or
run or
get any cmdlet in the module, such as the Get-ScheduledJob cmdlet.
Beginning in
PowerShell 3.0, modules are imported automatically when you get or
use any cmdlet in
the module.

When the PSScheduledJob module isn't in the current session, the following
command
sequence is possible.

PowerShell

Get-Job ProcessJob

Output

Get-Job : The command cannot find the job because the job name

ProcessJob was not found.

Verify the value of the Name parameter, and then try the command again.

+ CategoryInfo : ObjectNotFound: (ProcessJob:String) [Get-Job],

PSArgumentException

+ FullyQualifiedErrorId : JobWithSpecifiedNameNotFound,Microsoft.PowerShell.

Commands.GetJobCommand

PowerShell

Get-Job

Get-ScheduledJob ProcessJob

Output

Id Name Triggers Command Enabled

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

4 ProcessJob {1} Get-Process True

PowerShell

Get-Job ProcessJob

Output

Id Name PSJobTypeName State HasMoreData Location

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

43 ProcessJob PSScheduledJob Completed True localhost

44 ProcessJob PSScheduledJob Completed True localhost

45 ProcessJob PSScheduledJob Completed True localhost

46 ProcessJob PSScheduledJob Completed True localhost

47 ProcessJob PSScheduledJob Completed True localhost

48 ProcessJob PSScheduledJob Completed True localhost

49 ProcessJob PSScheduledJob Completed True localhost

50 ProcessJob PSScheduledJob Completed True localhost

This behavior occurs because the Get-ScheduledJob command automatically


imports the
PSScheduledJob module, and then runs the command.

See also
about_Scheduled_Jobs
about_Scheduled_Jobs_Basics
about_Scheduled_Jobs_Advanced
PSScheduledJob module cmdlets
Task Scheduler
Add-JobTrigger
Reference
Module: PSScheduledJob

Adds job triggers to scheduled jobs.

Syntax
PowerShell

Add-JobTrigger

[-Trigger] <ScheduledJobTrigger[]>

[-InputObject] <ScheduledJobDefinition[]>

[<CommonParameters>]

PowerShell

Add-JobTrigger

[-Trigger] <ScheduledJobTrigger[]>

[-Id] <Int32[]>

[<CommonParameters>]

PowerShell

Add-JobTrigger

[-Trigger] <ScheduledJobTrigger[]>

[-Name] <String[]>

[<CommonParameters>]

Description
The Add-JobTrigger cmdlet adds job triggers to scheduled jobs. You can use it to add
multiple
triggers to multiple scheduled jobs.

A job trigger starts a scheduled job on a one-time or recurring schedule or when an


event occurs.

Use the Trigger parameter of Add-JobTrigger to identify the job triggers to add. Use the
Name, ID, or InputObject parameters of Add-JobTrigger to identify the scheduled job
to
which the triggers are added.
To create job triggers for the value of the Trigger parameter, use the New-JobTrigger
cmdlet
or use a hash table to specify the job trigger.

Add-JobTrigger is one of a collection of job scheduling cmdlets in the PSScheduledJob

module
that is included in Windows PowerShell.

For more information about Scheduled Jobs, see the About topics in the
PSScheduledJob module. Import
the PSScheduledJob module and then type: Get-Help
about_Scheduled* or see about_Scheduled_Jobs.

This cmdlet was introduced in Windows PowerShell 3.0.

Examples

Example 1: Add a job trigger to a scheduled job


PowerShell

$Daily = New-JobTrigger -Daily -At 3AMPS

Add-JobTrigger -Trigger $Daily -Name "TestJob"

These commands add the Daily job trigger to the TestJob scheduled job.

The first command uses the New-JobTrigger cmdlet to create a job trigger that starts a
scheduled
job every day at 3:00 a.m. The command saves the job trigger in the $Daily
variable.

The second command uses the Add-JobTrigger cmdlet to add the job trigger in the
$Startup variable
to the TestJob scheduled job.

Example 2: Add a job trigger to several scheduled jobs


PowerShell

Get-ScheduledJob | Add-JobTrigger -Trigger (New-JobTrigger -AtStartup)

This command adds an AtStartup job trigger to all scheduled jobs on the local
computer. It uses the
Get-ScheduledJob to get all of the scheduled jobs on the
computer. It uses a pipeline operator
( | ) to send the jobs to the Add-JobTrigger cmdlet,
which adds the job trigger to each of the
scheduled jobs. The value of the Trigger
parameter is a New-JobTrigger command that creates
the AtStartup job trigger.
Example 3: Copy a job trigger
PowerShell

$T = Get-JobTrigger -Name "BackupArchives"

Add-JobTrigger -Name "TestBackup,BackupLogs" -Trigger $T

These commands copy the job trigger from the BackupArchives scheduled job and add
it to the
TestBackup and BackupLogs scheduled jobs.

The first command uses the Get-JobTrigger cmdlet to get the job trigger of the
BackupArchives
scheduled job. The command saves the trigger in the $t variable.

The second command uses the Add-JobTrigger cmdlet to add the job trigger in $t to
the TestBackup
and BackupLogs scheduled jobs.

Parameters
-Id

Specifies the identification numbers of the scheduled jobs. Add-JobTrigger adds the
job trigger to
the specified scheduled jobs.

To get the identification number of scheduled jobs on the local computer or a


remote computer, use
the Get-ScheduledJob cmdlet.

Type: Int32[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies the scheduled jobs. Enter a variable that contains ScheduledJob objects or
type a
command or expression that gets ScheduledJob objects, such as a Get-
ScheduledJob command.
You can also pipe ScheduledJob objects to Add-JobTrigger .

Type: Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition[]
Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies the names of the scheduled jobs. Add-JobTrigger adds the job triggers to
the specified
scheduled jobs. Wildcards are supported.

To get the names of scheduled jobs on the local computer or a remote computer,
use the
Get-ScheduledJob cmdlet.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Trigger

Specifies the job triggers to add. Enter a hash table that specifies job triggers or a
variable that
contains ScheduledJobTrigger objects, or type a command or
expression that gets
ScheduledJobTrigger objects, such as a Get-JobTrigger
command. You can also pipe
ScheduledJobTrigger objects to Add-JobTrigger .

Type: Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger[]

Position: 1

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

Inputs
Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger
You can pipe a job trigger to this cmdlet.

Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition

You can pipe a scheduled job to this cmdlet.

Outputs
None

This cmdlet returns no output.

Related Links
Add-JobTrigger
Disable-JobTrigger
Disable-ScheduledJob
Enable-JobTrigger
Enable-ScheduledJob
Get-JobTrigger
Get-ScheduledJob
Get-ScheduledJobOption
New-JobTrigger
New-ScheduledJobOption
Register-ScheduledJob
Remove-JobTrigger
Set-JobTrigger
Set-ScheduledJob
Set-ScheduledJobOption
Unregister-ScheduledJob
Disable-JobTrigger
Reference
Module: PSScheduledJob

Disables the job triggers of scheduled jobs.

Syntax
PowerShell

Disable-JobTrigger

[-InputObject] <ScheduledJobTrigger[]>

[-PassThru]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Disable-JobTrigger cmdlet temporarily disables the job triggers of scheduled jobs.
Disabling
preserves all job trigger properties, but it prevents the job trigger from
starting the scheduled
job.

To use this cmdlet, use the Get-JobTrigger cmdlet to get the job triggers. Then pipe the
job
triggers to Disable-JobTrigger or use its InputObject parameter.

To disable a job trigger, the Disable-JobTrigger cmdlet sets the Enabled property of the
job
trigger to $False . To re-enable the job trigger, use the Enable-JobTrigger cmdlet,
which sets
the Enabled property of the job trigger to $True. Disabling a job trigger does
not disable the
scheduled job, such as is done by the Disable-ScheduledJob cmdlet, but
if you disable all job
triggers, the effect is the same as disabling the scheduled job.

If you disable a scheduled job or disable all job triggers of a scheduled job, you can still
start
the job by using the Start-Job cmdlet or use the disabled scheduled job as a
template.

Disable-ScheduledJob is one of a collection of job scheduling cmdlets in the

PSScheduledJob module that is included in Windows PowerShell.

For more information about Scheduled Jobs, see the About topics in the
PSScheduledJob module. Import
the PSScheduledJob module and then type: Get-Help
about_Scheduled* or see about_Scheduled_Jobs.

This cmdlet was introduced in Windows PowerShell 3.0.

Examples

Example 1: Disable a job trigger


This example disables the first trigger a scheduled job on the local computer.

PowerShell

PS C:\> Get-JobTrigger -Name "Backup-Archives" -TriggerID 1 | Disable-


JobTrigger

The command uses the Get-JobTrigger cmdlet to get the job trigger. A pipeline
operator ( | )sends
the job trigger to the Disable-JobTrigger cmdlet, which disables it.

Example 2: Disable all job triggers


PowerShell

Get-ScheduledJob -Name "Backup-Archives,Inventory" | Get-JobTrigger |


Disable-JobTrigger

Get-ScheduledJob -Name "Backup-Archives,Inventory" | Get-JobTrigger |

Format-Table -Property ID, Frequency, At, DaysOfWeek, Enabled,


@{Label="JobName";Expression={$_.JobDefinition.Name}} -AutoSize

Id Frequency At DaysOfWeek Enabled JobName

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

1 Weekly 9/28/2011 3:00:00 AM {Monday} False Backup-Archive

2 Daily 9/29/2011 1:00:00 AM False Backup-Archive

1 Weekly 10/20/2011 11:00:00 PM {Friday} False Inventory

1 Weekly 11/2/2011 2:00:00 PM {Monday} False Inventory

The first command uses the Get-ScheduledJob cmdlet to get the Backup-Archives and
Inventory
scheduled jobs. A pipeline operator ( | ) sends the scheduled jobs to the Get-
JobTrigger cmdlet,
which gets all job triggers of the scheduled jobs. Another pipeline

operator sends the job triggers


to the Disable-JobTrigger cmdlet, which disables
them.The first command uses the
Get-ScheduledJob cmdlet to get the jobs, because its
Name parameter takes multiple names.
The second command displays the results. The command repeats the Get-ScheduledJob
and
Get-JobTrigger command. A pipeline operator sends the job triggers to the
Format-Table cmdlet,
which displays the job triggers in a table. The Format-Table

command adds a JobName property that


displays the value of the Name property of the
scheduled job in the JobDefinition property of the
job trigger object.

These commands disable all job triggers on two scheduled jobs and display the results.

Example 3: Disable job trigger of a scheduled job on a


remote computer
This example disables the daily job triggers for a scheduled job on a remote computer

PowerShell

Invoke-Command -ComputerName Server01 {Get-JobTrigger -Name DeployPackage |


Where-Object {$_.Frequency -eq "Daily"} | Disable-JobTrigger}

The command uses the Invoke-Command cmdlet to run the commands on the Server01
computer. The
remote command uses the Get-JobTrigger cmdlet to get the job triggers
of the DeployPackage
scheduled job. A pipeline operator sends the job triggers to the
Where-Object cmdlet, which
returns only daily job triggers. A pipeline operator sends
the daily job triggers to the
Disable-JobTrigger cmdlet, which disables them.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-InputObject
Specifies the job trigger to be disabled. Enter a variable that contains
ScheduledJobTrigger
objects or type a command or expression that gets
ScheduledJobTrigger objects, such as a
Get-JobTrigger command. You can also pipe
a ScheduledJobTrigger object to
Disable-JobTrigger .

Type: Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-PassThru

Returns an object representing the item with which you are working. By default, this
cmdlet does not
generate any output.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger

You can pipe a job trigger to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
Disable-JobTrigger does not generate errors or warnings if you disable a job

trigger that is
already disabled.

Related Links
Add-JobTrigger
Disable-JobTrigger
Disable-ScheduledJob
Enable-JobTrigger
Enable-ScheduledJob
Get-JobTrigger
Get-ScheduledJob
Get-ScheduledJobOption
New-JobTrigger
New-ScheduledJobOption
Register-ScheduledJob
Remove-JobTrigger
Set-JobTrigger
Set-ScheduledJob
Set-ScheduledJobOption
Unregister-ScheduledJob
Disable-ScheduledJob
Reference
Module: PSScheduledJob

Disables a scheduled job.

Syntax
PowerShell

Disable-ScheduledJob

[-InputObject] <ScheduledJobDefinition>

[-PassThru]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Disable-ScheduledJob

[-Id] <Int32>

[-PassThru]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Disable-ScheduledJob

[-Name] <String>

[-PassThru]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Disable-ScheduledJob cmdlet temporarily disables scheduled jobs. Disabling
preserves all job
properties and does not disable the job triggers, but it prevents the
scheduled jobs from starting
automatically when triggered. You can start a disabled
scheduled job by using the Start-Job cmdlet
or use a disabled scheduled job as a
template.
To disable a scheduled job, the Disable-ScheduledJob cmdlet sets the Enabled property
of the
scheduled job to False. To re-enable the scheduled job, use the Enable-
ScheduledJob cmdlet.

Disable-ScheduledJob is one of a collection of job scheduling cmdlets in the


PSScheduledJob
module that is included in Windows PowerShell.

For more information about Scheduled Jobs, see the About topics in the
PSScheduledJob module. Import
the PSScheduledJob module and then type: Get-Help
about_Scheduled* or see about_Scheduled_Jobs.

This cmdlet was introduced in Windows PowerShell 3.0.

Examples

Example 1: Disable a scheduled job


This example disables a scheduled job on the local computer.

PowerShell

Disable-ScheduledJob -ID 2 -Passthru

This command disables the scheduled job with ID 2 on the local computer.

Example 2: Disable all scheduled jobs


This example disables all scheduled jobs on the local computer.

PowerShell

Get-ScheduledJob | Disable-ScheduledJob -Passthru

Id Name Triggers Command


Enabled

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


-------

1 ArchiveProje... {} C:\Scripts\Archive-DxProjects.ps1
False

2 Inventory {1, 2} \\Srv01\Scripts\Get-


FullInventory.ps1 False

4 Test-HelpFiles {1} .\Test-HelpFiles.ps1


False

5 TestJob {1, 2} .\Run-AllTests.ps1


False
The Get-ScheduledJob cmdlet to gets all scheduled job and pipes them to the Disable-
ScheduledJob
cmdlet to disable them.

You can re-enable scheduled job by using the Enable-ScheduledJob cmdlet and run a
disabled
scheduled job by using the Start-Job cmdlet.

Disable-ScheduledJob does not generate warnings or errors if you disable a scheduled


job that is
already disabled, so you can disable all scheduled jobs without conditions.

Example 3: Disable selected scheduled jobs


This example disables scheduled job do not include a credential.

PowerShell

Get-ScheduledJob | Where-Object {!$_.Credential} | Disable-ScheduledJob

Jobs without credentials run with the permission of the user who created them.

The command uses the Get-ScheduledJob cmdlet to get all scheduled jobs on the
computer. A pipeline
operator sends the scheduled jobs to the Where-Object cmdlet,
which selects scheduled jobs that do
not have credentials. The command uses the not
( ! ) operator and references the Credential property
of the scheduled job. Another
pipeline operator sends the selected scheduled jobs to the
Disable-ScheduledJob
cmdlet, which disables them.

Example 4: Disable scheduled jobs on a remote computer


This example disables a scheduled job on two remote computers.

PowerShell

Invoke-Command -ComputerName Srv01, Srv10 -ScriptBlock {Disable-ScheduledJob


-Name TestJob}

The command uses the Invoke-Command cmdlet to run a Disable-ScheduledJob


command on the Srv01
and Srv10 computers. The command uses the Name parameter
of Disable-ScheduledJob to select the
TestJob scheduled job on each computer.

Example 5: Disable a scheduled job by its global ID


This examples shows how to disable a scheduled job by using its global identifier. The
value of the
GlobalID property of a scheduled job is a unique identifier (GUID). Use the
GlobalID value when
precision is required, such as when you are disabling scheduled
jobs on multiple computers.

PowerShell

Get-ScheduledJob | Format-Table -Property Name, GlobalID, Command -Autosize

Name GlobalId Command

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

ArchiveProjects1 a26a0b3d-b4e6-44d3-8b95-8706ef621f7c C:\Scripts\Archive-


DxProjects.ps1

Inventory 3ac37e5d-84c0-4a8f-9661-7e88ebb8f914 \\Srv01\Scripts\Get-


FullInventory.ps1

Backup-Scripts 4d0cc6be-c082-48d1-baec-1bd8278f3c81 Copy-Item


C:\CurrentScripts\*.ps1 -Destination C:\BackupScripts

Test-HelpFiles d77020ca-f20d-42be-86c8-fc64df97db90 .\Test-HelpFiles.ps1

Test-HelpFiles 2f1606d2-c6cf-4bef-8b1c-ae36a9cc9934 .\Test-


DomainHelpFiles.ps1

Get-ScheduledJob | Where-Object {$_.GlobalID = d77020ca-f20d-42be-86c8-


fc64df97db90} | Disable-ScheduledJob

The first command demonstrates one way of finding the GlobalID of a scheduled job.
The command uses
the Get-ScheduledJob cmdlet to get the scheduled jobs on the
computer. A pipeline operator ( | )
sends the scheduled jobs to the Format-Table cmdlet,
which displays the Name, GlobalID, and
Command properties of each job in a table.

The second command uses the Get-ScheduledJob cmdlet to get the scheduled jobs on
the computer. A
pipeline operator ( | ) sends the scheduled jobs to the Where-Object
cmdlet, which selects the
scheduled job with the specified global ID. Another pipeline
operator sends the job to the
Disable-ScheduledJob cmdlet, which disables it.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named
Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Id

Disables the scheduled job with the specified identification number (ID).
Enter the ID
of a scheduled job.

Type: Int32

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies the scheduled job to be disabled. Enter a variable that contains


ScheduledJobDefinition objects or type a command or expression that gets
ScheduledJobDefinition objects, such as a Get-ScheduledJob command. You can also
pipe a
ScheduledJobDefinition object to Disable-ScheduledJob .

Type: Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Disables the scheduled jobs with the specified names. Enter the name of a scheduled
job. Wildcards
are supported.

Type: String

Position: 0

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-PassThru

Returns an object representing the item with which you are working. By default, this
cmdlet does not
generate any output.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition

You can pipe a scheduled job to Disable-ScheduledJob .

Outputs
None

By default, this cmdlet returns no output.


Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition

When you use the PassThru parameter, this cmdlet returns the scheduled job that is
disabled.

Notes
Disable-ScheduledJob does not generate warnings or errors if you use it to disable

a scheduled
job that is already disabled.

Related Links
Add-JobTrigger
Disable-JobTrigger
Disable-ScheduledJob
Enable-JobTrigger
Enable-ScheduledJob
Get-JobTrigger
Get-ScheduledJob
Get-ScheduledJobOption
New-JobTrigger
New-ScheduledJobOption
Register-ScheduledJob
Remove-JobTrigger
Set-JobTrigger
Set-ScheduledJob
Set-ScheduledJobOption
Unregister-ScheduledJob
Enable-JobTrigger
Reference
Module: PSScheduledJob

Enables the job triggers of scheduled jobs.

Syntax
PowerShell

Enable-JobTrigger

[-InputObject] <ScheduledJobTrigger[]>

[-PassThru]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Enable-JobTrigger cmdlet re-enables job triggers of scheduled jobs, such as those
that were
disabled by using the Disable-JobTrigger cmdlet. Enabled and re-enabled job
triggers can start
scheduled jobs immediately; there is no need to restart Windows or
Windows PowerShell.

To use this cmdlet, use the Get-JobTrigger cmdlet to get the job triggers. Then pipe the
job
triggers to Enable-JobTrigger or use its InputObject parameter.

To enable a job trigger, the Enable-JobTrigger cmdlet sets the Enabled property of the
job trigger
to $true .

Enable-ScheduledJob is one of a collection of job scheduling cmdlets in the


PSScheduledJob
module that is included in Windows PowerShell.

For more information about Scheduled Jobs, see the About topics in the
PSScheduledJob module. Import
the PSScheduledJob module and then type: Get-Help
about_Scheduled* or see about_Scheduled_Jobs.

This cmdlet was introduced in Windows PowerShell 3.0.

Examples
Example 1: Enable a job trigger
PowerShell

Get-JobTrigger -Name Backup-Archives -TriggerID 1 | Enable-JobTrigger

This command enables the first trigger (ID=1) of the Backup-Archives scheduled job on
the local
computer.

The command uses the Get-JobTrigger cmdlet to get the job trigger. A pipeline
operator sends the
job trigger to the Enable-JobTrigger cmdlet, which enables it.

Example 2: Enable all job triggers


PowerShell

Get-ScheduledJob | Get-JobTrigger | Enable-JobTrigger

The command uses the Get-ScheduledJob cmdlet to get the scheduled jobs on the local
computer. A
pipeline operator ( | ) sends the scheduled jobs to the Get-JobTrigger
cmdlet, which gets all job
triggers of the scheduled jobs. Another pipeline operator
sends the job triggers to the
Enable-JobTrigger cmdlet, which enables them.

Example 3: Enable the job trigger of a scheduled job on a


remote computer
PowerShell

Invoke-Command -ComputerName Server01 {Get-JobTrigger -Name DeployPackage |


Where-Object {$_.Frequency -eq "AtLogon"} | Enable-JobTrigger}

This command re-enables the AtLogon job triggers on the DeployPackage scheduled
job on the Server01
remote computer.

The command uses the Invoke-Command cmdlet to run the commands on the Server01
computer. The
remote command uses the Get-JobTrigger cmdlet to get the job triggers
of the DeployPackage
scheduled job. A pipeline operator sends the job triggers to the
Where-Object cmdlet which returns
only AtLogon job triggers. A pipeline operator sends

the AtLogon job triggers to the


Enable-JobTrigger cmdlet, which enables them.
Example 4: Display disabled job triggers
PowerShell

Get-ScheduledJob | Get-JobTrigger | where {!$_.Enabled} | Format-Table Id,


Frequency, At, DaysOfWeek, Enabled, @{Label="JobName";Expression=
{$_.JobDefinition.Name}}

Id Frequency At DaysOfWeek Enabled JobName

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

1 Weekly 9/28/2011 3:00:00 AM {Monday} False Backup-Archive

2 Daily 9/29/2011 1:00:00 AM False Backup-Archive

1 Weekly 10/20/2011 11:00:00 PM {Friday} False Inventory

1 Weekly 11/2/2011 2:00:00 PM {Monday} False Inventory

This command displays all disabled job triggers of all scheduled jobs in a table. You can
use a
command like this one to discover job triggers that might need to be enabled.

The command uses the Get-ScheduledJob cmdlet to get the scheduled jobs on the local
computer. A
pipeline operator ( | ) sends the scheduled jobs to the Get-JobTrigger
cmdlet, which gets all job
triggers of the scheduled jobs. Another pipeline operator
sends the job triggers to the
Where-Object cmdlet, which returns only job triggers that
are disabled, that is, where the value
of the Enabled property of the job trigger is not ( ! )
true.

Another pipeline operator sends the disabled job triggers to the Format-Table cmdlet,
which
displays the selected properties of the job triggers in a table. The properties
include a new
JobName property that displays the name of the scheduled job in the
JobDefinition property of the
job trigger.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


-InputObject

Specifies the job trigger to enable. Enter a variable that contains


ScheduledJobTrigger objects
or type a command or expression that gets
ScheduledJobTrigger objects, such as a
Get-JobTrigger command. You can also pipe
a ScheduledJobTrigger object to Enable-JobTrigger .

Type: Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-PassThru

Returns an object representing the item with which you are working. By default, this
cmdlet does not
generate any output.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


Inputs
Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger

You can pipe a job trigger to this cmdlet.

Outputs
None

This cmdlet returns no output.

Notes
Enable-JobTrigger does not generate errors or warnings if you enable a job trigger
that is
already enabled.

Related Links
Add-JobTrigger
Disable-JobTrigger
Disable-ScheduledJob
Enable-JobTrigger
Enable-ScheduledJob
Get-JobTrigger
Get-ScheduledJob
Get-ScheduledJobOption
New-JobTrigger
New-ScheduledJobOption
Register-ScheduledJob
Remove-JobTrigger
Set-JobTrigger
Set-ScheduledJob
Set-ScheduledJobOption
Unregister-ScheduledJob
Enable-ScheduledJob
Reference
Module: PSScheduledJob

Enables a scheduled job.

Syntax
PowerShell

Enable-ScheduledJob

[-InputObject] <ScheduledJobDefinition>

[-PassThru]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Enable-ScheduledJob

[-Id] <Int32>

[-PassThru]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Enable-ScheduledJob

[-Name] <String>

[-PassThru]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Enable-ScheduledJob cmdlet re-enables scheduled jobs that are disabled, such as
those that are
disabled by using the Disable-ScheduledJob cmdlet. Enabled jobs run
automatically when triggered.
To enable a scheduled job, the Enable-ScheduledJob cmdlet sets the Enabled property of
the
scheduled job to $true .

Enabled-ScheduledJob is one of a collection of job scheduling cmdlets in the

PSScheduledJob
module that is included in Windows PowerShell.

For more information about Scheduled Jobs, see the About topics in the
PSScheduledJob module. Import
the PSScheduledJob module and then type: Get-Help
about_Scheduled* or see about_Scheduled_Jobs.

This cmdlet was introduced in Windows PowerShell 3.0.

Examples

Example 1: Enable a scheduled job


This example enables the scheduled job on a local computer.

PowerShell

Enable-ScheduledJob -ID 2 -Passthru

The Enable-ScheduledJob command enables the scheduled job with ID 2 on the local
computer. The
PassThru parameter allows the Job object to be output.

Example 2: Enable all scheduled jobs


This examples enables all scheduled jobs on the local computer.

PowerShell

Get-ScheduledJob | Enable-ScheduledJob

The Get-ScheduledJob cmdlet gets all scheduled jobs and pipes them to Enable-
ScheduledJob cmdlet
to enable them.

Enable-ScheduledJob does not generate warnings or errors if you enable a scheduled


job that is
already enabled, so you can enable all scheduled jobs without conditions.

Example 3: Enable selected scheduled jobs


This example enables scheduled jobs that do not require a network connection.

PowerShell

Get-ScheduledJob | Get-ScheduledJobOption | Where-Object


{$_.RunWithoutNetwork} |

ForEach-Object {Enable-ScheduledJob -InputObject $_.JobDefinition}

The command uses the Get-ScheduledJob cmdlet to get all scheduled jobs on the
computer. A pipeline
operator ( | ) sends the scheduled jobs to the Get-
ScheduledJobOption cmdlet, which gets the job
options of each scheduled job. Each job
options object has a JobDefinition property that contains
the associated scheduled job.
The JobDefinition property is used to complete the command.

The command uses a pipeline operator ( | ) to send the job options to the Where-Object
cmdlet,
which selects scheduled job option objects in which the RunWithoutNetwork
property has a value
of $true . Another pipeline operator sends the selected scheduled
job options objects to the
ForEach-Object cmdlet which runs an Enable-ScheduledJob
command on the scheduled job in the
value of the JobDefinition property of each job
options object.

Example 4: Enable scheduled jobs on a remote computer


PowerShell

Invoke-Command -ComputerName "Srv01,Srv10" -ScriptBlock {Enable-ScheduledJob


-Name "Inventory"}

This command enables scheduled jobs that have "test" in their names on two remote
computers, Srv01
and Srv10.

The command uses the Invoke-Command cmdlet to run an Enable-ScheduledJob


command on the Srv01
and Srv10 computers. The command uses the Name parameter
of Enable-ScheduledJob to enable the
Inventory scheduled job on each computer.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter
Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Id

Enables the scheduled job with the specified identification number (ID). Enter the ID
of a scheduled
job.

Type: Int32

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies the scheduled job to enable. Enter a variable that contains


ScheduledJobDefinition
objects or type a command or expression that gets
ScheduledJobDefinition objects, such as a
Get-ScheduledJob command. You can also
pipe a ScheduledJobDefinition object to
Enable-ScheduledJob .

Type: Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Enables the scheduled jobs with the specified names. Enter the name of a scheduled
job. Wildcards
are supported.
Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-PassThru

Returns an object representing the item with which you are working. By default, this
cmdlet does not
generate any output.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition

You can pipe a scheduled job to Enable-ScheduledJob .


Outputs
None

By default, this cmdlet returns no output.

Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition

When you use the PassThru parameter, this cmdlet returns the scheduled job that it
enabled.

Notes
Enable-ScheduledJob does not generate warnings or errors if you use it to enable a

scheduled job
that is already enabled.

Related Links
Add-JobTrigger
Disable-JobTrigger
Disable-ScheduledJob
Enable-JobTrigger
Enable-ScheduledJob
Get-JobTrigger
Get-ScheduledJob
Get-ScheduledJobOption
New-JobTrigger
New-ScheduledJobOption
Register-ScheduledJob
Remove-JobTrigger
Set-JobTrigger
Set-ScheduledJob
Set-ScheduledJobOption
Unregister-ScheduledJob
Get-JobTrigger
Reference
Module: PSScheduledJob

Gets the job triggers of scheduled jobs.

Syntax
PowerShell

Get-JobTrigger

[[-TriggerId] <Int32[]>]

[-InputObject] <ScheduledJobDefinition>

[<CommonParameters>]

PowerShell

Get-JobTrigger

[[-TriggerId] <Int32[]>]

[-Id] <Int32>

[<CommonParameters>]

PowerShell

Get-JobTrigger

[[-TriggerId] <Int32[]>]

[-Name] <String>

[<CommonParameters>]

Description
The Get-JobTrigger cmdlet gets the job triggers of scheduled jobs. You can use this
command to
examine the job triggers or to pipe the job triggers to other cmdlets.

A job trigger defines a recurring schedule or conditions for starting a scheduled job. Job
triggers
are not saved to disk independently; they are part of a scheduled job. To get a
job trigger, specify
the scheduled job that the trigger starts.

Use the parameters of the Get-JobTrigger cmdlet to identify the scheduled jobs. You
can identify
the scheduled jobs by their names or identification numbers, or by entering
or piping
ScheduledJob objects, such as those that are returned by the Get-
ScheduledJob cmdlet, to
Get-JobTrigger .

Get-JobTrigger is one of a collection of job scheduling cmdlets in the PSScheduledJob

module that
is included in Windows PowerShell.

For more information about Scheduled Jobs, see the About topics in the
PSScheduledJob module. Import
the PSScheduledJob module and then type: Get-Help
about_Scheduled* or see
about_Scheduled_Jobs.

This cmdlet was introduced in Windows PowerShell 3.0.

Examples

Example 1: Get a job trigger by scheduled job name


PowerShell

Get-JobTrigger -Name "BackupJob"

The command uses the Name parameter of Get-JobTrigger to get the job triggers of
the BackupJob
scheduled job.

Example 2: Get a job trigger by ID


The example uses the ID parameter of Get-JobTrigger to get the job triggers of a
scheduled
job.

PowerShell

Get-ScheduledJob

Id Name Triggers Command


Enabled

-- ---- -------- -------


-------

1 ArchiveProjects {1} \\Server\Share\Archive-


Projects.ps1 True

2 Backup {1,2} \\Server\Share\Run-Backup.ps1


True

3 Test-HelpFiles {1} \\Server\Share\Test-HelpFiles.ps1


True

4 TestJob {} \\Server\Share\Run-AllTests.ps1
True

Get-JobTrigger -ID 3

The first command uses the Get-ScheduledJob cmdlet to display the scheduled jobs on
the local
computer. The display includes the IDs of the scheduled jobs.

The second command uses the Get-JobTrigger cmdlet to get the job trigger for the
Test-HelpFiles
job (whose ID is 3 ).

Example 3: Get job triggers by piping a job


This example gets job triggers of jobs that have matching names.

PowerShell

Get-ScheduledJob -Name *Backup*, *Archive* | Get-JobTrigger

This command gets the job triggers of all jobs that have Backup or Archive in their
names.

Example 4: Get the job trigger of a job on a remote


computer
This example gets the triggers of a scheduled job on a remote computer.

PowerShell

Invoke-Command -ComputerName Server01 { Get-ScheduledJob Backup | Get-


JobTrigger -TriggerID 2 }

The command uses the Invoke-Command cmdlet to run a command on the Server01
computer. It uses the
Get-ScheduledJob cmdlet to get the Backup scheduled job, which
it pipes to the Get-JobTrigger
cmdlet. It uses the TriggerID parameter to get only the
second trigger.

Example 5: Get all job triggers


This example gets all job triggers of all scheduled jobs on the local computer.

PowerShell
Get-ScheduledJob | Get-JobTrigger |

Format-Table -Property ID, Frequency, At, DaysOfWeek, Enabled,


@{Label="ScheduledJob";Expression={$_.JobDefinition.Name}} -AutoSize

Id Frequency At DaysOfWeek Enabled ScheduledJob

-- --------- -- ---------- ------- ------------

1 Weekly 9/28/2011 3:00:00 AM {Monday} True Backup

1 Daily 9/27/2011 11:00:00 PM True Test-HelpFiles

The command uses the Get-ScheduledJob to get the scheduled jobs on the local
computer and pipes
them to Get-JobTrigger , which gets the job trigger of each
scheduled job (if any).

To add the name of the scheduled job to the job trigger display, the command uses the
calculated
property feature of the Format-Table cmdlet. In addition to the job trigger
properties that are
displayed by default, the command creates a new ScheduledJob
property that displays the name of
the scheduled job.

Example 6: Get the job trigger property of a scheduled


job
This example shows different methods to view the JobTrigger property of a scheduled
job.

PowerShell

(Get-ScheduledJob Test-HelpFiles).JobTriggers

Get-ScheduledJob | foreach {$_.JobTriggers}

The first command uses the Get-ScheduledJob cmdlet to get the Test-HelpFiles
scheduled job. Then
it uses the dot method ( . ) to get the JobTriggers property of the
Test-HelpFiles scheduled
job.

The second command uses the Get-ScheduledJob cmdlet to get all scheduled jobs on
the local
computer. It uses the ForEach-Object cmdlet to get the value of the
JobTriggers property of
each scheduled job.

The job triggers of a scheduled job are stored in the JobTriggers property of the job.
This
example shows alternatives to using the Get-JobTrigger cmdlet to get job triggers.
The results are
identical to using the Get-JobTrigger cmdlet and the techniques can be
used interchangeably.
Example 7: Compare job triggers
PowerShell

Get-ScheduledJob -Name ArchiveProjects | Get-JobTrigger | Tee-Object -


Variable t1

Id Frequency Time DaysOfWeek


Enabled

-- --------- ---- ---------- --


-----

0 Daily 9/26/2011 3:00:00 AM


True

Get-ScheduledJob -Name "Test-HelpFiles" | Get-JobTrigger | Tee-Object -


Variable t2

Id Frequency Time DaysOfWeek


Enabled

-- --------- ---- ---------- --


-----

0 Daily 9/26/2011 3:00:00 AM


True

$t1| Get-Member -Type Property | ForEach-Object { Compare-Object $t1 $t2 -


Property $_.Name}

RandomDelay SideIndicator

----------- -------------

00:00:00 =>

00:03:00 <=

The first command gets the job trigger of the ArchiveProjects scheduled job. The
command pipes the
job trigger to the Tee-Object cmdlet, which saves the job trigger in
the $t1 variable and
displays it at the command line.

The second command gets the job trigger of the Test-HelpFiles scheduled job. The
command pipes the
job trigger to the Tee-Object cmdlet, which saves the job trigger in
the $t2 variable and
displays it at the command line.

The third command compares the job triggers in the $t1 and $t2 variables. It uses the
Get-Member
cmdlet to get the properties of the job trigger in the $t1 variable. It pipes
the properties to the
ForEach-Object cmdlet, which compares each property to the
properties of the job trigger in the
$t2 variable by name. The command then pipes the
differing properties to the Format-List cmdlet,
which displays them in a list.The output
indicates that, although the job triggers appear to be the
same, the HelpFiles job
trigger includes a random delay of three ( 3 ) minutes.
This example shows how to compare the job triggers of two scheduled jobs.

Parameters
-Id

Specifies the identification number of a scheduled job. Get-JobTrigger gets the job
trigger of the
specified scheduled job.

To get the identification number of scheduled jobs on the local computer or a


remote computer, use
the Get-ScheduledJob cmdlet.

Type: Int32

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies a scheduled job. Enter a variable that contains ScheduledJob objects or


type a command
or expression that gets ScheduledJob objects, such as a Get-
ScheduledJob command. You can also
pipe ScheduledJob objects to Get-JobTrigger .

Type: Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies the name of a scheduled job. Get-JobTrigger gets the job trigger of the
specified
scheduled job. Wildcards are supported.

To get the names of scheduled jobs on the local computer or a remote computer,
use the
Get-ScheduledJob cmdlet.
Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-TriggerId

Gets the specified job triggers. Enter the trigger IDs of one or more job triggers of a
scheduled
job. Use this parameter when the scheduled job that is specified by the
Name, ID, or
InputObject parameters has multiple job triggers.

Type: Int32[]

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition

You can pipe a scheduled job to this cmdlet.

Outputs
Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger

This cmdlet returns the scheduled job's trigger.

Related Links
Add-JobTrigger
Disable-JobTrigger
Disable-ScheduledJob
Enable-JobTrigger
Enable-ScheduledJob
Get-JobTrigger
Get-ScheduledJob
Get-ScheduledJobOption
New-JobTrigger
New-ScheduledJobOption
Register-ScheduledJob
Remove-JobTrigger
Set-JobTrigger
Set-ScheduledJob
Set-ScheduledJobOption
Unregister-ScheduledJob
Get-ScheduledJob
Reference
Module: PSScheduledJob

Gets scheduled jobs on the local computer.

Syntax
PowerShell

Get-ScheduledJob

[[-Id] <Int32[]>]

[<CommonParameters>]

PowerShell

Get-ScheduledJob

[-Name] <String[]>

[<CommonParameters>]

Description
The Get-ScheduledJob cmdlet gets scheduled jobs on the local computer. Get-
ScheduledJob gets
only scheduled jobs that are created by the current user using the

Register-ScheduledJob cmdlet.

Although jobs that are created by using the Register-ScheduledJob cmdlet appear in
Task Scheduler,
Get-ScheduledJob gets only scheduled jobs. It does not get scheduled
tasks created in Task
Scheduler.

Without parameters, Get-ScheduledJob gets all scheduled jobs on the computer. You
can use the
parameters of Get-ScheduledJob to get scheduled jobs by ID or name and
examine them or pipe them
to other cmdlets.

Get-ScheduledJob is one of a collection of job scheduling cmdlets in the

PSScheduledJob module
that is included in Windows PowerShell.

For more information about Scheduled Jobs, see the About topics in the
PSScheduledJob module. Import
the PSScheduledJob module and then type: Get-Help
about_Scheduled* or see about_Scheduled_Jobs.
This cmdlet was introduced in Windows PowerShell 3.0.

Examples

Example 1: Get all scheduled jobs


This example gets all scheduled jobs on the local computer.

PowerShell

Get-ScheduledJob

Example 2: Get scheduled jobs by name


This example gets all scheduled jobs on the computer that have names that include
Backup or Archive.
This command format lets you search for particular jobs.

PowerShell

Get-ScheduledJob -Name *Backup*, *Archive*

Example 3: Get scheduled jobs on remote computers


This example gets all scheduled jobs on the computers that are listed in a text file.

PowerShell

Invoke-Command -ComputerName (Get-Content Servers.txt) {Get-ScheduledJob}

The command uses the Invoke-Command cmdlet to run a Get-ScheduleJob command on


each computer.

Example 4: Pipe scheduled jobs to other cmdlets


This example gets the job triggers of specified scheduled jobs

PowerShell

Get-ScheduledJob DailyBackup, WeeklyBackup | Get-JobTrigger


It uses the Get-ScheduledJob cmdlet to get the scheduled jobs and pipes them to the
Get-JobTrigger cmdlet to get the job triggers of the scheduled jobs.

Parameters
-Id

Gets only the scheduled jobs with the specified identification number (ID). Enter one
or more IDs of
scheduled jobs on the computer. By default, Get-ScheduledJob gets
all scheduled jobs on the
computer.

Type: Int32[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Name

Gets only the scheduled jobs with the specified names. Enter one or more names of
scheduled jobs on
the computer. Wildcards are supported. By default, Get-
ScheduledJob gets all scheduled jobs on the
computer.

Type: String[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You cant pipe objects to this cmdlet.


Outputs
Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition

This cmdlet returns the definition of a scheduled job.

Notes
Each scheduled job is saved in a subdirectory of the
$HOME\AppData\Local\Microsoft\Windows\PowerShell\ScheduledJobs directory on
the local computer.
The subdirectory is named for the scheduled job and contains
the XML file for the scheduled job
and records of its execution history. For more
information about scheduled jobs on disk, see about_Scheduled_Jobs_Advanced.
Scheduled jobs that you create in Windows PowerShell appear in Task Scheduler in
the Task
Scheduler Library\Microsoft\Windows\PowerShell\ScheduledJobs folder.
You can use Task Scheduler
to view and edit the scheduled job.
You can use Task Scheduler, the SchTasks.exe command-line tool, and the Task
Scheduler cmdlets
to manage scheduled jobs that you create with the Scheduled
Job cmdlets. However, you cannot use
the Scheduled Job cmdlets to manage tasks
that you create in Task Scheduler.

Related Links
Add-JobTrigger
Disable-JobTrigger
Disable-ScheduledJob
Enable-JobTrigger
Enable-ScheduledJob
Get-JobTrigger
Get-ScheduledJob
Get-ScheduledJobOption
New-JobTrigger
New-ScheduledJobOption
Register-ScheduledJob
Remove-JobTrigger
Set-JobTrigger
Set-ScheduledJob
Set-ScheduledJobOption
Unregister-ScheduledJob
Get-ScheduledJobOption
Reference
Module: PSScheduledJob

Gets the job options of scheduled jobs.

Syntax
PowerShell

Get-ScheduledJobOption

[-InputObject] <ScheduledJobDefinition>

[<CommonParameters>]

PowerShell

Get-ScheduledJobOption

[-Id] <Int32>

[<CommonParameters>]

PowerShell

Get-ScheduledJobOption

[-Name] <String>

[<CommonParameters>]

Description
The Get-ScheduledJobOption cmdlet gets the job options of scheduled jobs. You can use
this command
to examine the job options or to pipe the job options to other cmdlets.

Job options are not saved to disk independently; they are part of a scheduled job. To get
the job
options of a scheduled job, specify the scheduled job.

Use the parameters of the Get-ScheduledJobOption cmdlet to identify the scheduled job.
You can
identify scheduled jobs by their names or identification numbers, or by entering
or piping
ScheduledJob objects, such as those that are returned by the Get-
ScheduledJob cmdlet, to
Get-ScheduledJobOption .
Get-ScheduledJobOption is one of a collection of job scheduling cmdlets in the

PSScheduledJob
module that is included in Windows PowerShell.

For more information about Scheduled Jobs, see the About topics in the
PSScheduledJob module. Import
the PSScheduledJob module and then type: Get-Help
about_Scheduled* or see about_Scheduled_Jobs.

This cmdlet was introduced in Windows PowerShell 3.0.

Examples

Example 1: Get job options


This example gets the job options of scheduled jobs matching a specified name.

PowerShell

Get-ScheduledJobOption -Name "*Backup*"

Example 2: Get all job options


This example gets the job options of all scheduled jobs on the local computer.

PowerShell

Get-ScheduledJob | Get-ScheduledJobOption

The example uses the Get-ScheduledJob cmdlet to get the scheduled jobs on the local
computer. A
pipeline operator ( | ) sends the scheduled jobs to the Get-
ScheduledJobOption cmdlet, which gets
the job options of each scheduled job.

Example 3: Get selected job options


This example shows how to find job options object with particular values.

PowerShell

Get-ScheduledJob | Get-ScheduledJobOption | Where {$_.RunElevated -and


!$_.WaketoRun}

Get-ScheduledJob | Get-ScheduledJobOption | Where {$_.RunElevated -and


!$_.WaketoRun} |

ForEach-Object {$_.JobDefinition}

The first command gets job options in which the RunElevated property has a value of
$True and the
RunWithoutNetwork property has a value of $false . The output shows
the JobOptions object
that was selected.

The second command shows how to find to which scheduled job the job options
belong. This command
uses a pipeline operator ( | ) to send the selected job options to
the ForEach-Object cmdlet,
which gets the JobDefinition property of each options
object. The JobDefinition property
contains the originating job object.

Example 4: Use job options to create a new job


This example shows how to use the job options that Get-ScheduledJobOption gets in a
new scheduled
job.

PowerShell

$Opts = Get-ScheduledJobOption -Name "BackupTestLogs"

Register-ScheduledJob -Name "Archive-Scripts" -FilePath


"\\Srv01\Scripts\ArchiveScripts.ps1" -ScheduledJobOption $Opts

The first command uses Get-ScheduledJobOption to get the jobs options of the
BackupTestLogs
scheduled job. The command saves the options in the $Opts variable.

The second command uses Register-ScheduledJob cmdlet to create a new scheduled


job.
The value of the ScheduledJobOption parameter is the options object in the $Opts
variable.

Example 5: Get job options from a remote computer


PowerShell

$O = Invoke-Command -ComputerName "Srv01" -ScriptBlock {Get-ScheduledJob -


Name "DataDemon" }

This command uses the Invoke-Command cmdlet to get the scheduled job options of the
DataDemon job
on the Srv01 computer. The command saves the options in the $O
variable.
Parameters
-Id

Specifies the identification number of a scheduled job. Get-ScheduledJobOption gets


the job
options of the specified scheduled job.

To get the identification numbers of scheduled jobs on the local computer or a


remote computer, use
the Get-ScheduledJob cmdlet.

Type: Int32

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies a scheduled job. Enter a variable that contains a ScheduledJob object or


type a
command or expression that gets a ScheduledJob object, such as a Get-
ScheduledJob command. You
can also pipe a ScheduledJob object to Get-
ScheduledJobOption .

Type: Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies the names of scheduled jobs. Get-ScheduledJobOption gets the job options
of the
specified scheduled job. Wildcards are supported.

To get the names of scheduled jobs on the local computer or a remote computer,
use the
Get-ScheduledJob cmdlet.

Type: String
Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

Inputs
Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition

You can pipe a scheduled job object to this cmdlet.

Outputs
Microsoft.PowerShell.ScheduledJob.ScheduledJobOptions

This cmdlet returns a ScheduledJobOptions object.

Related Links
Add-JobTrigger
Disable-JobTrigger
Disable-ScheduledJob
Enable-JobTrigger
Enable-ScheduledJob
Get-JobTrigger
Get-ScheduledJob
Get-ScheduledJobOption
New-JobTrigger
New-ScheduledJobOption
Register-ScheduledJob
Remove-JobTrigger
Set-JobTrigger
Set-ScheduledJob
Set-ScheduledJobOption
Unregister-ScheduledJob
New-JobTrigger
Reference
Module: PSScheduledJob

Creates a job trigger for a scheduled job.

Syntax
PowerShell

New-JobTrigger

[-RandomDelay <TimeSpan>]

-At <DateTime>

[-Once]

[-RepetitionInterval <TimeSpan>]

[-RepetitionDuration <TimeSpan>]

[-RepeatIndefinitely]

[<CommonParameters>]

PowerShell

New-JobTrigger

[-DaysInterval <Int32>]

[-RandomDelay <TimeSpan>]

-At <DateTime>

[-Daily]

[<CommonParameters>]

PowerShell

New-JobTrigger

[-WeeksInterval <Int32>]

[-RandomDelay <TimeSpan>]

-At <DateTime>

-DaysOfWeek<DayOfWeek[]>

[-Weekly]

[<CommonParameters>]

PowerShell

New-JobTrigger

[-RandomDelay <TimeSpan>]

[-AtStartup]

[<CommonParameters>]
PowerShell

New-JobTrigger

[-RandomDelay <TimeSpan>]

[-User <String>]

[-AtLogOn]

[<CommonParameters>]

Description
The New-JobTrigger cmdlet creates a job trigger that starts a scheduled job on a one-
time or
recurring schedule, or when an event occurs.

You can use the ScheduledJobTrigger object that New-JobTrigger returns to set a job
trigger
for a new or existing scheduled job. You can also create a job trigger with the
Get-JobTrigger
cmdlet to get the job trigger of an existing scheduled job, or with a
hash table value to represent
a job trigger.

When creating a job trigger, review the default values of the options specified by the
New-ScheduledJobOption cmdlet. These options, which have the same valid and default
values as the
corresponding options in Task Scheduler, affect the scheduling and timing
of scheduled jobs.

New-JobTrigger is one of a collection of job scheduling cmdlets in the PSScheduledJob

module that
is included in Windows PowerShell.

For more information about Scheduled Jobs, see the About topics in the
PSScheduledJob module. Import
the PSScheduledJob module and then type: Get-Help
about_Scheduled* or see
about_Scheduled_Jobs.

This cmdlet was introduced in Windows PowerShell 3.0.

Examples

Example 1: Once Schedule


This example creates a job trigger to start a scheduled job only once.

PowerShell

New-JobTrigger -Once -At "1/20/2012 3:00 AM"


The New-JobTrigger cmdlet to create a job trigger that starts a scheduled job only one
time. The
value of the At parameter is a string that Windows PowerShell converts into a
DateTime
object.

The At parameter value includes an explicit date, not just a time. If the date were
omitted, the
trigger would be created with the current date and 3:00 AM time, which is
likely to represent a time
in the past.

Example 2: Daily Schedule


This example creates a new job trigger to start a scheduled job every third day.

PowerShell

New-JobTrigger -Daily -At "4:15 AM" -DaysInterval 3

This command creates a job trigger that starts a scheduled job every 3 days at 4:15 a.m.

Because the value of the At parameter does not include a date, the current date is used
as the
date value in the DateTime object. If the date and time is in the past, the
scheduled job is
started at the next occurrence, which is 3 days later from the At
parameter value.

Example 3: Weekly Schedule


This example creates a job trigger that starts a scheduled job every fourth week on
specified days
of that week.

PowerShell

New-JobTrigger -Weekly -DaysOfWeek Monday, Wednesday, Friday -At "23:00" -


WeeksInterval 4

Id Frequency Time DaysOfWeek Enabled

-- --------- ---- ---------- -------

0 Weekly 9/21/2012 11:00:00 PM {Monday, Wednesday, Friday} True

This command creates a job trigger to start a scheduled job on Monday, Wednesday,
and Friday at 2300
hours (11:00 PM) every 4 weeks.

You can also enter the DaysOfWeek parameter value in integers, such as -DaysOfWeek 1,
5.
Example 4: Logon Schedule
This example creates a job trigger to start a scheduled job at logon of a specific user.

PowerShell

New-JobTrigger -AtLogOn -User Domain01\Admin01

This command creates a job trigger to start a scheduled job whenever the domain
administrator logs
onto the computer.

Example 5: Using a Random Delay


This example creates a new job trigger with a random time-span delay.

PowerShell

New-JobTrigger -Daily -At 1:00 -RandomDelay 00:20:00

This command creates a job trigger to start a scheduled job every day at 1:00 in the
morning. The
command uses the RandomDelay parameter to set the maximum delay to
20 minutes. As a result, the
job runs every day between 1:00 AM and 1:20 AM, with the
interval varying pseudo-randomly.

You can use a random delay for sampling, load balancing, and other administrative
tasks. When
setting the delay value, review the effective and default values of the New-
ScheduledJobOption
cmdlet and coordinate the delay with the option settings.

Example 6: Create a Job Trigger for a New Scheduled Job


These example uses a job trigger to create a new scheduled job.

PowerShell

$t = New-JobTrigger -Weekly -DaysOfWeek 1,3,5 -At 12:01AM

Register-ScheduledJob -Name Test-HelpFiles -FilePath C:\Scripts\Test-


HelpFiles.ps1 -Trigger $t

The first command uses the New-JobTrigger cmdlet to create a job trigger that starts a
job every
Monday, Wednesday, and Friday at 12:01 AM. The command saves the job
trigger in the $t variable.
The second command uses the Register-ScheduledJob cmdlet to create a scheduled job
that starts a
job every Monday, Wednesday, and Friday at 12:01 AM. The value of the
Trigger parameter is the
trigger that is stored in the $t variable.

Example 7: Add a Job Trigger to a Scheduled Job


This example shows how to add a job trigger to an existing scheduled job.

PowerShell

Add-JobTrigger -Name SynchronizeApps -Trigger (New-JobTrigger -Daily -At


3:10AM)

You can add multiple job triggers to any scheduled job.

The command uses the Add-JobTrigger cmdlet to add the job trigger to the
SynchronizeApps
scheduled job. The value of the Trigger parameter is a New-JobTrigger
command that runs the
job every day at 3:10 AM.

When the command completes, SynchronizeApps is a scheduled job that runs at the
times specified
by the job trigger.

Example 8: Create a repeating job trigger


This example creates a repeating job trigger to only run for a specific amount of time.

PowerShell

New-JobTrigger -Once -At "09/12/2013 1:00:00" -RepetitionInterval (New-


TimeSpan -Hours 1) -RepetitionDuration (New-Timespan -Hours 48)

This command creates a job trigger that runs a job every 60 minutes for 48 hours
beginning on
September 12, 2013 at 1:00 AM.

Example 9: Stop a repeating job trigger


This example stops a repeating job trigger.

PowerShell

Get-JobTrigger -Name SecurityCheck | Set-JobTrigger -RepetitionInterval 0:00


-RepetitionDuration 0:00
This command forcibly stops the SecurityCheck job, which is triggered to run every 60
minutes
until its job trigger expires.

To prevent the job from repeating, the command uses the Get-JobTrigger to get the job
trigger of
the SecurityCheck job and the Set-JobTrigger cmdlet to change the
repetition interval and
repetition duration of the job trigger to zero ( 0 ).

Example 10: Create an hourly job trigger


This example creates a repeating job trigger that runs indefinitely.

PowerShell

New-JobTrigger -Once -At "9/21/2012 0am" -RepetitionInterval (New-TimeSpan -


Hour 12) -RepetitionDuration ([TimeSpan]::MaxValue)

The following command creates a job trigger that runs a scheduled job once every 12
hours for an
indefinite period of time. The schedule begins tomorrow (9/21/2012) at
midnight (0:00 AM).

Parameters
-At

Starts the job at the specified date and time. Enter a DateTime object, such as one
that the
Get-Date cmdlet returns, or a string that can be converted to a date and
time, such as
April 19, 2012 15:00 , 12/31 , or 3am . If you don't specify an element of
the date, such as the
year, the date in the trigger has the corresponding element
from the current date.

When using the Once parameter, set the value of the At parameter to a future date
and time.
Because the default date in a DateTime object is the current date, if you
specify a time before
the current time without an explicit date, the job trigger is
created for a time in the past.

DateTime objects, and strings that are converted to DateTime objects, are
automatically
adjusted to be compatible with the date and time formats selected for
the local computer in Region
and Language in Control Panel.

Type: DateTime

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-AtLogOn

Starts the scheduled job when the specified users log on to the computer. To specify
a user, use the
User parameter.

Type: SwitchParameter

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-AtStartup

Starts the scheduled job when Windows starts.

Type: SwitchParameter

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Daily

Specifies a recurring daily job schedule. Use the other parameters in the Daily
parameter set to
specify the schedule details.

Type: SwitchParameter

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-DaysInterval

Specifies the number of days between occurrences on a daily schedule. For example,
a value of 3
starts the scheduled job on days 1 , 4 , 7 and so on. The default value is
1.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-DaysOfWeek

Specifies the days of the week on which a weekly scheduled job runs. Enter day
names, such as
Monday or integers 0 - 6 , where 0 represents Sunday. This parameter
is required in the
Weekly parameter set.

Day names are converted to their integer values in the job trigger. When you enclose
day names in
quotation marks in a command, enclose each day name in separate
quotation marks, such as
"Monday", "Tuesday" . If you enclose multiple day names in
a single quotation mark pair, the
corresponding integer values are summed. For
example, "Monday, Tuesday" ( 1 + 2 ) results in a
value of Wednesday ( 3 ).

Type: DayOfWeek[]

Accepted values: Sunday, Monday, Tuesday, Wednesday, Thursday, Friday,


Saturday

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Once

Specifies a non-recurring (one time) or custom repeating schedule. To create a


repeating schedule,
use the Once parameter with the RepetitionDuration and
RepetitionInterval parameters.
Type: SwitchParameter

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RandomDelay

Enables a random delay that begins at the scheduled start time, and sets the
maximum delay value.
The length of the delay is set pseudo-randomly for each start
and varies from no delay to the time
specified by the value of this parameter. The
default value, zero ( 00:00:00 ), disables the random
delay.

Enter a timespan object, such as one returned by the New-TimeSpan cmdlet, or enter a
value in
<hours>:<minutes>:<seconds> format, which is automatically converted to a
TimeSpan object.

Type: TimeSpan

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RepeatIndefinitely

This parameter, available starting in Windows PowerShell 4.0, eliminates the


necessity of specifying
a TimeSpan.MaxValue value for the RepetitionDuration
parameter to run a scheduled job
repeatedly, for an indefinite period.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-RepetitionDuration

Repeats the job until the specified time expires. The repetition frequency is
determined by the
value of the RepetitionInterval parameter. For example, if the
value of RepetitionInterval
is 5 minutes and the value of RepetitionDuration is 2
hours, the job is triggered every five
minutes for two hours.

Enter a timespan object, such as one that the New-TimeSpan cmdlet returns or a string
that can be
converted to a timespan object, such as 1:05:30 .

To run a job indefinitely, add the RepeatIndefinitely parameter instead.

To stop a job before the job trigger repetition duration expires, use the Set-
JobTrigger cmdlet to
set the RepetitionDuration value to zero ( 0 ).

This parameter is valid only when the Once, At, and RepetitionInterval parameters
are
used in the command.

Type: TimeSpan

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RepetitionInterval

Repeats the job at the specified time interval. For example, if the value of this
parameter is 2
hours, the job is triggered every two hours. The default value, 0 , does
not repeat the job.

Enter a timespan object, such as one that the New-TimeSpan cmdlet returns or a string
that can be
converted to a timespan object, such as 1:05:30 .

This parameter is valid only when the Once, At, and RepetitionDuration parameters
are
used in the command.

Type: TimeSpan

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-User

Specifies the users who trigger an AtLogon start of a scheduled job. Enter the name
of a user in
<UserName> or <Domain\Username> format or enter an asterisk ( * ) to
represent all users. The
default value is all users.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Weekly

Specifies a recurring weekly job schedule. Use the other parameters in the Weekly
parameter set
to specify the schedule details.

Type: SwitchParameter

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WeeksInterval

Specifies the number of weeks between occurrences on a weekly job schedule. For
example, a value of
3 starts the scheduled job on weeks 1 , 4 , 7 and so on. The
default value is 1 .

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger

This cmdlet returns a ScheduledJobTrigger object representing the created trigger.

Notes
Job triggers are not saved to disk. However, scheduled jobs are saved to disk, and
you can use the
Get-JobTrigger to get the job trigger of any scheduled job.

New-JobTrigger does not prevent you from creating a job trigger that will not run a

scheduled
job, such as one-time trigger for a date in the past.

The Register-ScheduledJob cmdlet accepts a ScheduledJobTrigger object, such as


one returned
by the New-JobTrigger or Get-JobTrigger cmdlets, or a hash table
with trigger values.

To submit a hash table, use the following keys.


Frequency: Once , Daily , Weekly , AtStartup , or AtLogon
At: any valid time string, such as 3am
DaysOfWeek: any combination of day names as strings, such as "Monday",
"Wednesday"
Interval: any valid frequency interval as an integer
RandomDelay: any valid timespan string, such as 30minutes
User: any valid user, such as Domain1\User01 ; used only with the AtLogon
frequency
value

Related Links
Add-JobTrigger
Disable-JobTrigger
Disable-ScheduledJob
Enable-JobTrigger
Enable-ScheduledJob
Get-JobTrigger
Get-ScheduledJob
Get-ScheduledJobOption
New-JobTrigger
New-ScheduledJobOption
Register-ScheduledJob
Remove-JobTrigger
Set-JobTrigger
Set-ScheduledJob
Set-ScheduledJobOption
Unregister-ScheduledJob
New-ScheduledJobOption
Reference
Module: PSScheduledJob

Creates an object that contains advanced options for a scheduled job.

Syntax
PowerShell

New-ScheduledJobOption

[-RunElevated]

[-HideInTaskScheduler]

[-RestartOnIdleResume]

[-MultipleInstancePolicy <TaskMultipleInstancePolicy>]

[-DoNotAllowDemandStart]

[-RequireNetwork]

[-StopIfGoingOffIdle]

[-WakeToRun]

[-ContinueIfGoingOnBattery]

[-StartIfOnBattery]

[-IdleTimeout <TimeSpan>]

[-IdleDuration <TimeSpan>]

[-StartIfIdle]

[<CommonParameters>]

Description
The New-ScheduledJobOption cmdlet creates an object that contains advanced options
for a scheduled
job.

You can use the ScheduledJobOptions object that New-ScheduledJobOption returns to


set job
options for a new or existing scheduled job. Alternatively, you can set job
options by using the
Get-ScheduledJobOption cmdlet to get the job options of an
existing scheduled job or by using a
hash table value to represent the job options.

Without parameters, New-ScheduledJobOption generates an object that contains the


default values
for all of the options. Because all of the properties except for the
JobDefinition property can be
edited, you can use the resulting object as a template,
and create standard option objects for your
enterprise.

When creating scheduled jobs and setting scheduled job options, review the default
values of all
scheduled job options. Scheduled jobs run only when all conditions set for
their execution are
satisfied.

New-ScheduledJobOption is one of a collection of job scheduling cmdlets in the


PSScheduledJob
module that is included in Windows PowerShell.

For more information about Scheduled Jobs, see the About topics in the
PSScheduledJob module. Import
the PSScheduledJob module and then type: Get-Help
about_Scheduled* or see about_Scheduled_Jobs.

This cmdlet was introduced in Windows PowerShell 3.0.

Examples

Example 1: Create a scheduled job option object with


default values
This example creates a scheduled job option object with the default values.

PowerShell

New-ScheduledJobOption

Example 2: Create a scheduled job option object with


custom values
This example creates a scheduled job option object with custom values

PowerShell

New-ScheduledJobOption -RequireNetwork -StartIfOnBattery

StartIfOnBatteries : True

StopIfGoingOnBatteries : True

WakeToRun : False

StartIfNotIdle : True

StopIfGoingOffIdle : False

RestartOnIdleResume : False

IdleDuration : 00:10:00

IdleTimeout : 01:00:00

ShowInTaskScheduler : True

RunElevated : False

RunWithoutNetwork : False

DoNotAllowDemandStart : False

MultipleInstancePolicy : Ignore

NewJobDefinition :
The following command creates a scheduled job object that requires the network and
runs the
scheduled job even if the computer is not connected to AC power.

The output shows that the RequireNetwork parameter changed the value of the
RunWithoutNetwork
property to $false and the StartIfOnBattery parameter changed
the value of the
StartIfOnBatteries property to $true .

Example 3: Set options for a new scheduled job


This example shows how to use the ScheduledJobOptions object that New-
ScheduledJobOption
returns to set the options for a new scheduled job.

PowerShell

$runAsAdmin = New-ScheduledJobOption -RunElevated

Register-ScheduledJob -Name Backup -FilePath D:\Scripts\Backup.ps1 -Trigger


$Mondays -ScheduledJobOption $RunAsAdmin

Get-ScheduledJobOption -Name Backup

StartIfOnBatteries : False

StopIfGoingOnBatteries : True

WakeToRun : False

StartIfNotIdle : True

StopIfGoingOffIdle : False

RestartOnIdleResume : False

IdleDuration : 00:10:00

IdleTimeout : 01:00:00

ShowInTaskScheduler : True

RunElevated : True

RunWithoutNetwork : True

DoNotAllowDemandStart : False

MultipleInstancePolicy : IgnoreNew

JobDefinition :
Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition

The first command creates a ScheduledJobOptions object with the RunElevated


parameter. It
saves the object in the $runAsAdmin variable.

The second command uses the Register-ScheduledJob cmdlet to create a new


scheduled job. The value
of the ScheduledJobOption parameter is the option object in
the value of the $runAsAdmin
variable.

The third command uses the Get-ScheduledJobOption cmdlet to get the job options of
the Backup
scheduled job.The cmdlet output shows that the RunElevated property is set
to $true and the
JobDefinition property of the job option object is now populated with
the scheduled job object
for the Backup scheduled job.

Example 4: Sort the properties of a scheduled job option


object
This example shows how to sort the properties of a ScheduledJobOptions object in
alphabetical
order for easy reading.

PowerShell

$options = New-ScheduledJobOption -WakeToRun

$options.PSObject.Properties | Sort-Object -Property Name | Format-Table -


Property Name, Value -Autosize

Name Value

---- -----

DoNotAllowDemandStart False

IdleDuration 00:10:00

IdleTimeout 01:00:00

JobDefinition

MultipleInstancePolicy IgnoreNew

RestartOnIdleResume False

RunElevated False

RunWithoutNetwork True

ShowInTaskScheduler True

StartIfNotIdle True

StartIfOnBatteries False

StopIfGoingOffIdle False

StopIfGoingOnBatteries True

WakeToRun True

The first command uses the New-ScheduledJobOption cmdlet to create a


ScheduledJobOptions
object. The command uses the WakeToRun parameter and saves
the resulting object in the
$options variable.

To get the properties of $Options as objects, the second command uses the PSObject
property of
all Windows PowerShell objects and its Properties property. The command
then pipes the property
objects to the Sort-Object cmdlet, which sorts the properties in
alphabetical order by name, and
then to the Format-Table cmdlet, which displays the
names and values of the properties in a table.

This format makes it much easier to find the WakeToRun property of the
ScheduledJobOptions
object in $options and to verify that its value was changed from
$false to $true .
Parameters
-ContinueIfGoingOnBattery

Do not stop the scheduled job if the computer switches to battery power
(disconnects from AC power)
while the job is running. By default, scheduled jobs
stop when the computer disconnects from AC
power.

The ContinueIfGoingOnBattery parameter sets the value of the


StopIfGoingOnBatteries property
of scheduled jobs to $true .

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-DoNotAllowDemandStart

Start the job only when it is triggered. Users cannot start the job manually, such as
by using the
Run feature in Task Scheduler.

This parameter only affects Task Scheduler. It does not prevents users from using the
Start-Job
cmdlet to start the job.

The DoNotAllowDemandStart parameter sets the value of the


DoNotAllowDemandStart property of
scheduled jobs to $true .

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-HideInTaskScheduler

Do not display the job in Task Scheduler. This value affects only the computer on
which the job
runs. By default, scheduled tasks appear in Task Scheduler.
Even if a task is hidden, users can display the task by selecting the Show hidden tasks
view option
in Task Scheduler.

The HideInTaskScheduler parameter sets the value of the ShowInTaskScheduler


property of
scheduled jobs to $false .

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-IdleDuration

Specifies how long the computer must be idle before the job starts. The default value
is 10 minutes.
If the computer is not idle for the specified duration before the value
of IdleTimeout expires,
the scheduled job does not run until the next scheduled
time, if any.

Enter a TimeSpan object, such as one generated by the New-TimeSpan cmdlet, or


enter a value in
<hours>:<minutes>:<seconds> format that is automatically
converted to a TimeSpan object.

To enable this value, use the StartIfIdle parameter. By default, the StartIfNotIdle
property of
scheduled jobs is set to $true and Windows PowerShell ignores the
IdleDuration and
IdleTimeout values.

Type: TimeSpan

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-IdleTimeout

Specifies how long the scheduled job waits for the computer to be idle. If this
timeout expires
before the computer remains idle for the time period that is
specified by the IdleDuration
parameter, the job does not run until the next
scheduled time, if any. The default value is one
hour.

Enter a TimeSpan object, such as one generated by the New-TimeSpan cmdlet, or


enter a value in
<hours>:<minutes>:<seconds> format that is automatically
converted to a TimeSpan object.

To enable this value, use the StartIfIdle parameter. By default, the StartIfNotIdle
property
of scheduled jobs is set to $true and Windows PowerShell ignores the
IdleDuration and
IdleTimeout values.

Type: TimeSpan

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-MultipleInstancePolicy

Determines how the system responds to a request to start an instance of a


scheduled job while
another instance of the job is running. The default value is
IgnoreNew . The acceptable values for
this parameter are:

IgnoreNew - The new job instance is ignored.

Parallel - The new job instance starts immediately.

Queue - The new job instance starts as soon as the current instance completes.
StopExisting - The current instance of the job stops and the new instance

starts.

To run the job, all conditions for the job schedule must be met. For example, if the
conditions that
are set by the RequireNetwork, IdleDuration, and IdleTimeout
parameters are not
satisfied, the job instance is not started, regardless of the value of
this parameter.

Type: Microsoft.PowerShell.ScheduledJob.TaskMultipleInstancePolicy

Accepted values: None, IgnoreNew, Parallel, Queue, StopExisting

Position: Named

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-RequireNetwork

Runs the scheduled job only when network connections are available.

If you specify this parameter and the network is not available at the scheduled start
time, the job
does not run until the next scheduled start time, if any.

The RequireNetwork parameter sets the value of the RunWithoutNetwork property


of scheduled
jobs to $false .

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RestartOnIdleResume

Restarts a scheduled job when the computer becomes idle. This parameter works
with the
StopIfGoingOffIdle parameter, which suspends a running scheduled job if
the computer becomes
active (leaves the idle state).

The RestartOnIdleResume parameter sets the value of the RestartOnIdleResume


property of
scheduled jobs to $true .

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RunElevated

Runs the scheduled job with the permissions of a member of the Administrators
group on the computer
on which the job runs.
To enable a scheduled job to run with Administrator permissions, use the Credential
parameter of
Register-ScheduledJob to provide explicit credential for the job.

The RunElevated parameter sets the value of the RunElevated property of scheduled
jobs to
$true .

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-StartIfIdle

Starts the scheduled job if the computer has been idle for the time specified by the
IdleDuration parameter before the time specified by the IdleTimeout parameter
expires.

By default, the IdleDuration and IdleTimeout parameters are ignored and the job
starts at
the scheduled start time even if the computer is busy.

If you specify this parameter and the computer is busy (not idle) at the scheduled
start time, the
job does not run until the next scheduled start time, if any.

The StartIfIdle parameter sets the value of the StartIfNotIdle property of scheduled
jobs to
$false .

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-StartIfOnBattery

Starts the scheduled job even if the computer is running on batteries at the
scheduled start time.
The default value is $false .
The StartIfOnBattery parameter sets the value of the StartIfOnBatteries property of
scheduled jobs to $true .

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-StopIfGoingOffIdle

Suspends a running scheduled job if the computer becomes active (not idle) while
the job is running.

By default, a scheduled job that is suspended when the computer becomes active
resumes when the
computer becomes idle again. To change this default behavior,
use the RestartOnIdleResume
parameter.

The StopIfGoingOffIdle parameter sets the value of the StopIfGoingOffIdle property


of scheduled
jobs to $true .

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WakeToRun

Wakes the computer from a Hibernate or Sleep state at the scheduled start time so it
can run the
job. By default, if the computer is in a Hibernate or Sleep state at the
scheduled start time, the
job does not run.

The WakeToRun parameter sets the value of the WakeToRun property of scheduled
jobs to
$true .

Type: SwitchParameter

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
None

You can't pipe objects to this cmdlet.

Outputs
Microsoft.PowerShell.ScheduledJob.ScheduledJobOptions

This cmdlet returns a ScheduledJobOptions object representing the created options.

Notes
You can use the ScheduledJobOptions object that New-ScheduledJobOption creates
as the value
of the ScheduledJobOption parameter of the Register-ScheduledJob
cmdlet. However, the
ScheduledJobOption parameter can also take a hash table
value that specifies the properties of
the ScheduledJobOptions object and their
values, such as:

@{ShowInTaskScheduler=$False; RunElevated=$True; IdleDuration="00:05"}

Related Links
Add-JobTrigger
Disable-JobTrigger
Disable-ScheduledJob
Enable-JobTrigger
Enable-ScheduledJob
Get-JobTrigger
Get-ScheduledJob
Get-ScheduledJobOption
New-JobTrigger
New-ScheduledJobOption
Register-ScheduledJob
Remove-JobTrigger
Set-JobTrigger
Set-ScheduledJob
Set-ScheduledJobOption
Unregister-ScheduledJob
Register-ScheduledJob
Reference
Module: PSScheduledJob

Creates a scheduled job.

Syntax
PowerShell

Register-ScheduledJob

[-ScriptBlock] <ScriptBlock>

[-Name] <String>

[-Trigger <ScheduledJobTrigger[]>]

[-InitializationScript <ScriptBlock>]

[-RunAs32]

[-Credential <PSCredential>]

[-Authentication <AuthenticationMechanism>]

[-ScheduledJobOption <ScheduledJobOptions>]

[-ArgumentList <Object[]>]

[-MaxResultCount <Int32>]
[-RunNow]

[-RunEvery <TimeSpan>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Register-ScheduledJob

[-FilePath] <String>

[-Name] <String>

[-Trigger <ScheduledJobTrigger[]>]

[-InitializationScript <ScriptBlock>]

[-RunAs32]

[-Credential <PSCredential>]

[-Authentication <AuthenticationMechanism>]

[-ScheduledJobOption <ScheduledJobOptions>]

[-ArgumentList <Object[]>]

[-MaxResultCount <Int32>]
[-RunNow]

[-RunEvery <TimeSpan>]

[-WhatIf]

[-Confirm]

[<CommonParameters>]
Description
The Register-ScheduledJob cmdlet creates scheduled jobs on the local computer.

A scheduled job is a Windows PowerShell background job that can be started


automatically on a
one-time or recurring schedule. Scheduled jobs are stored on disk
and registered in Task Scheduler.
The jobs can be managed in Task Scheduler or by
using the Scheduled Job cmdlets in Windows
PowerShell.

When a scheduled job starts, it creates an instance of the scheduled job. Scheduled job
instances
are identical to Windows PowerShell background jobs, except that the results
are saved on disk. Use
the Job cmdlets, such as Start-Job , Get-Job , and Receive-Job to
start, view, and get the
results of the job instances.

Use Register-ScheduledJob to create a new scheduled job. To specify the commands


that the
scheduled job runs, use the ScriptBlock parameter. To specify a script that the
job runs, use
the FilePath parameter.

Windows PowerShell-scheduled jobs use the same job triggers and job options that Task
Scheduler uses
for scheduled tasks.

The Trigger parameter of Register-ScheduledJob adds one or more job triggers that
start the
job. The Trigger parameter is optional, so you can add triggers when you
create the scheduled
job, add job triggers later, add the RunNow parameter to start the
job immediately, use the
Start-Job cmdlet to start the job immediately at any time, or
save the untriggered scheduled job
as a template for other jobs.

The Options parameter lets you customize the options settings for the scheduled job.
The
Options parameter is optional, so you can set job options when you create the
scheduled job or
change them at any time. Because job option settings can prevent the
scheduled job from running,
review the job options and set them carefully.

Register-ScheduledJob is one of a collection of job scheduling cmdlets in the

PSScheduledJob
module that is included in Windows PowerShell.

For more information about Scheduled Jobs, see the About articles in the
PSScheduledJob module.
Import the PSScheduledJob module and then type: Get-Help
about_Scheduled* or see
about_Scheduled_Jobs.

This cmdlet was introduced in Windows PowerShell 3.0.

Examples
Example 1: Create a scheduled job
This example creates a scheduled job on the local computer.

PowerShell

Register-ScheduledJob -Name "Archive-Scripts" -ScriptBlock {

Get-ChildItem $HOME\*.ps1 -Recurse |

Copy-Item -Destination "\\Server\Share\PSScriptArchive"

Register-ScheduledJob uses the Name parameter to create the Archive-Scripts

scheduled job.
The ScriptBlock parameter runs Get-ChildItem that searches the $HOME
directory recursively
for .ps1 files. The Copy-Item cmdlet copies the files to a directory
specified by the
Destination parameter.

Because the scheduled job doesn't contain a trigger, it's not started automatically. You
can add job
triggers with Add-JobTrigger , use the Start-Job cmdlet to start the job on
demand, or use the
scheduled job as a template for other scheduled jobs.

Example 2: Create a scheduled job with triggers and


custom options
This example shows how to create a scheduled job that has a job trigger and custom job
options.

PowerShell

$O = New-ScheduledJobOption -WakeToRun -StartIfIdle -MultipleInstancePolicy


Queue

$T = New-JobTrigger -Weekly -At "9:00 PM" -DaysOfWeek Monday -WeeksInterval


2

$path = "\\Srv01\Scripts\UpdateVersion.ps1"

Register-ScheduledJob -Name "UpdateVersion" -FilePath $path -


ScheduledJobOption $O -Trigger $T

The $O variable stores the job option object that the New-ScheduledJobOption cmdlet
created. The
options start the scheduled job even if the computer isn't idle, wakes the
computer to run the job,
if necessary, and allows multiple instances of the job to run in a
series.

The $T variable stores the result from the New-JobTrigger cmdlet to create job trigger
that
starts a job every other Monday at 9:00 PM.
The $path variable stores the path to the UpdateVersion.ps1 script file.

Register-ScheduledJob uses the Name paramter to create the UpdateVersion scheduled


job.
The FilePath parameter uses $path to specify the script that the job runs. The
ScheduledJobOption parameter uses the job options stored in $O . The Trigger
parameter uses
the job triggers stored in $T .

Example 3: Use hash tables to specify a trigger and


scheduled job options
This example has the same effect as the command in Example 2. It creates a scheduled
job, using hash
tables to specify the values of the Trigger and ScheduledJobOption
parameters. The $O and
$T variables defined in Example 2 are replaced with hash tables.

PowerShell

$T = @{

Frequency="Weekly"

At="9:00PM"

DaysOfWeek="Monday"

Interval=2

$O = @{

WakeToRun=$true

StartIfNotIdle=$false

MultipleInstancePolicy="Queue"

Register-ScheduledJob -Trigger $T -ScheduledJobOption $O -Name UpdateVersion


-FilePath "\\Srv01\Scripts\Update-Version.ps1"

Example 4: Create scheduled jobs on remote computers


In this example, the EnergyData scheduled job is created on multiple remote computers.
The
scheduled job runs a script that gathers raw data and saves it in a running log on
the remote
computer.

PowerShell

$Cred = Get-Credential

$O = New-ScheduledJobOption -WakeToRun -StartIfIdle -MultipleInstancePolicy


Queue

$T = New-JobTrigger -Weekly -At "9:00 PM" -DaysOfWeek Monday -WeeksInterval


2

Invoke-Command -ComputerName (Get-Content Servers.txt) -Credential $Cred -


ScriptBlock {

$params = @{

Name = "Get-EnergyData"

FilePath = "\\Srv01\Scripts\Get-EnergyData.ps1"

ScheduledJobOption = $using:O

Trigger = $using:T

Register-ScheduledJob @params

The $Cred variable stores credentials in a PSCredential object for a user with
permissions to
create scheduled jobs. The $O variable stores the job options created
with
New-ScheduledJobOption . The $T variable stores the job triggers created with New-
JobTrigger .

The Invoke-Command cmdlet uses the ComputerName parameter to get a list of server
names from
the Servers.txt file. The Credential parameter gets the credential object
stored in $Cred .
The ScriptBlock parameter runs a Register-ScheduledJob command on
the computers in the
Servers.txt file.

The parameters for Register-ScheduledJob are defined by $params . The Name


parameters
specifies the job is named Get-EnergyData on each remote computer.
FilePath provides the
location of the EnergyData.ps1 script. The script is located on a file
server that is available to
all participating computers.The job runs on the schedule
specified by the job triggers in $T and
the job options in $O .

The Register-ScheduledJob @params command creates the scheduled job with the
parameters from the
script block.

Example 5: Create a scheduled job that runs a script on


remote computers
This example creates the CollectEnergyData scheduled job on the local computer. The
job runs on
multiple remote computers.

PowerShell

$Admin = Get-Credential
$T = New-JobTrigger -Weekly -At "9:00 PM" -DaysOfWeek Monday -WeeksInterval
2

Register-ScheduledJob -Name "CollectEnergyData" -Trigger $T -MaxResultCount


99 -ScriptBlock {

$params = @{

AsJob = $true

ComputerName = (Get-Content Servers.txt)

FilePath = '\\Srv01\Scripts\Get-EnergyData.ps1'

Credential = $using:Admin

Authentication = 'CredSSP'

Invoke-Command @params

The $Admin variable stores credentials for a user with permissions to run the commands
in a
PSCredential object. The $T variable stores the job triggers created with New-
JobTrigger .

The Register-ScheduledJob cmdlet uses the Name parameter to create the


CollectEnergyData
scheduled job on the local computer. The Trigger parameter
specifies the job triggers in $T
and the MaxResultCount parameter increases the
number of saved results to 99.

The ScriptBlock parameter defines the Invoke-Command parameters with $params . The
AsJob
parameter creates the background job object on the local computer, even though
the Energydata.ps1
script runs on the remote computers. The ComputerName
parameter gets a list of server names from
the Servers.txt file. The Credential
parameter specifies a user account that has permission to
run scripts on the remote
computers. And, the Authentication parameter specifies a value of
CredSSP to allow
delegated credentials.

The Invoke-Command @params runs the command with the parameters from the script
block.

Parameters
-ArgumentList

Specifies values for the parameters of the script that is specified by the FilePath
parameter or
for the command that is specified by the ScriptBlock parameter.

Type: Object[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Authentication
Specifies the mechanism that is used to authenticate the user's credentials. The
default value is
Default.

The acceptable values for this parameter are:

Default
Basic

Credssp

Digest
Kerberos

Negotiate
NegotiateWithImplicitCredential

For more information about the values of this parameter, see


AuthenticationMechanism.

U 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.

Type: AuthenticationMechanism

Accepted values: Default, Basic, Negotiate, NegotiateWithImplicitCredential,


Credssp, Digest, Kerberos

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter
Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Credential

Specifies a user account that has permission to run the scheduled job. 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. If you enter only a user name,
you're prompted for a
password.

Credentials are stored in a PSCredential


object and the password is stored as a
SecureString.

7 Note

For more information about SecureString data protection, see


How secure is
SecureString?.

Type: PSCredential

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-FilePath

Specifies a script that the scheduled job runs. Enter the path to a .ps1 file on the
local
computer. To specify default values for the script parameters, use the
ArgumentList parameter.
Every Register-ScheduledJob command must use either
the ScriptBlock or FilePath
parameters.

Type: String
Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InitializationScript

Specifies the fully qualified path to a Windows PowerShell script ( .ps1 ). The
initialization
script runs in the session that is created for the background job before
the commands that are
specified by the ScriptBlock parameter or the script that is
specified by the FilePath
parameter. You can use the initialization script to configure
the session, such as adding files,
functions, or aliases, creating directories, or
checking for prerequisites.

To specify a script that runs the primary job commands, use the FilePath parameter.

If the initialization script generates an error, even a non-terminating error, the


current instance
of the scheduled job doesn't run and its status is Failed.

Type: ScriptBlock

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-MaxResultCount

Specifies how many job result entries are maintained for the scheduled job. The
default value is 32.

Windows PowerShell saves the execution history and results of each triggered
instance of the
scheduled job on disk. The value of this parameter determines the
number of job instance results
that are saved for this scheduled job. When the
number of job instance results exceeds this value,
Windows PowerShell deletes the
results of the oldest job instance to make room for the results of
the newest job
instance.

The job execution history and job results are saved in the
$HOME\AppData\Local\Microsoft\Windows\PowerShell\ScheduledJobs\
<JobName>\Output\<Timestamp>
directories on the computer on which the job is

created. To see the execution history, use the


Get-Job cmdlet. To get the job results,
use the Receive-Job cmdlet.

The MaxResultCount parameter sets the value of the ExecutionHistoryLength


property of the
scheduled job.

To delete the current execution history and job results, use the
ClearExecutionHistory parameter
of the Set-ScheduledJob cmdlet.

Type: Int32

Position: Named

Default value: 32

Accept pipeline input: False

Accept wildcard characters: False

-Name

Specifies a name for the scheduled job. The name is also used for all started
instances of the
scheduled job. The name must be unique on the computer. This
parameter is required.

Type: String

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RunAs32

Runs the scheduled job in a 32-bit process.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-RunEvery

Used to specify how often to run the job. For example, use this option to run a job
every 15
minutes.

Type: TimeSpan

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RunNow

Starts a job immediately, as soon as the Register-ScheduledJob cmdlet is run. This


parameter
eliminates the need to trigger Task Scheduler to run a Windows
PowerShell script immediately after
registration, and doesn't require users to create a
trigger that specifies a starting date and time.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ScheduledJobOption

Sets options for the scheduled job. Enter a ScheduledJobOptions object, such as one
that you
create by using the New-ScheduledJobOption cmdlet, or a hash table value.

You can set options for a scheduled job when you register the schedule job or use
the
Set-ScheduledJobOption or Set-ScheduledJob cmdlets to change the options.

Many of the options and their default values determine whether and when a
scheduled job runs. Be
sure to review these options before scheduling a job. For a
description of the scheduled job
options, including the default values, see New-
ScheduledJobOption .
To submit a hash table, use the following keys. In the following hash table, the keys
are shown with
their default values.

@{StartIfOnBattery=$False; StopIfGoingOnBattery=$True; WakeToRun=$False;

StartIfNotIdle=$False; IdleDuration="00:10:00"; IdleTimeout="01:00:00";


StopIfGoingOffIdle=$True; RestartOnIdleResume=$False; ShowInTaskScheduler=$True;

RunElevated=$False; RunWithoutNetwork=$False; DoNotAllowDemandStart=$False;

MultipleInstancePolicy="IgnoreNew"}

Type: Microsoft.PowerShell.ScheduledJob.ScheduledJobOptions

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ScriptBlock

Specifies the commands that the scheduled job runs. Enclose the commands in curly
braces ( {} ) to
create a script block. To specify default values for command
parameters, use the ArgumentList
parameter.

Every Register-ScheduledJob command must use either the ScriptBlock or FilePath


parameters.

Type: ScriptBlock

Position: 1

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Trigger

Specifies the triggers for the scheduled job. Enter one or more ScheduledJobTrigger
objects,
such as the objects that the New-JobTrigger cmdlet returns, or a hash table
of job trigger keys
and values.

A job trigger starts the schedule job. The trigger can specify a one-time or recurring
scheduled or
an event, such as when a user logs on or Windows starts.
The Trigger parameter is optional. You can add a trigger when you create the
scheduled job, use
the Add-JobTrigger , Set-JobTrigger , or Set-ScheduledJob
cmdlets to add or change job triggers
later, or use the Start-Job cmdlet to start the
scheduled job immediately. You can also create and
maintain a scheduled job
without a trigger that is used as a template.

To submit a hash table, use the following keys:

Frequency: Daily, Weekly, AtStartup, AtLogon


At: Any valid time string
DaysOfWeek - Any combination of day names
Interval - Any valid frequency interval
RandomDelay: Any valid timespan string
User: Any valid user. Used only with the AtLogon frequency value

For example:

@{Frequency="Once"; At="3am"; DaysOfWeek="Monday", "Wednesday"; Interval=2;


RandomDelay="30minutes"; User="Domain1\User01"}

Type: Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet isn't run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False


Inputs
None

You can't pipe objects to this cmdlet.

Outputs
Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition

This cmdlet returns a ScheduledJobDefinition object representing the registered job.

Notes
Each scheduled job is saved in a subdirectory of the
$HOME\AppData\Local\Microsoft\Windows\PowerShell\ScheduledJobs directory on the local

computer.
The subdirectory is named for the scheduled job and contains an XML file for
the scheduled job and
records of its execution history. For more information about
scheduled jobs on disk, see
about_Scheduled_Jobs_Advanced.

Scheduled jobs that you create in Windows PowerShell appear in Task Scheduler in the
Task Scheduler
Library\Microsoft\Windows\PowerShell\ScheduledJobs folder. You can
use Task Scheduler to view and
edit the scheduled job.

You can use Task Scheduler, the schtasks.exe command-line tool, and the Task
Scheduler cmdlets
to manage scheduled jobs that you create with the Scheduled Job
cmdlets. However, you can't use the
Scheduled Job cmdlets to manage tasks that you
create in Task Scheduler.

If a scheduled job command fails, Windows PowerShell returns an error message.


However, if the job
fails when Task Scheduler tries to run it, the error isn't available to
Windows PowerShell.

If a scheduled job doesn't run, use the following methods to find the reason:

Verify that the job trigger is set properly.


Verify that the conditions set in the job options are satisfied.
Verify that the user account under which the job runs has permission to run the
commands or
scripts in the job.
Check the Task Scheduler history for errors.
Check the Task Scheduler event log for errors.
For more information, see
about_Scheduled_Jobs_Troubleshooting.

Related Links
Add-JobTrigger
Disable-JobTrigger
Disable-ScheduledJob
Enable-JobTrigger
Enable-ScheduledJob
Get-JobTrigger
Get-ScheduledJob
Get-ScheduledJobOption
New-JobTrigger
New-ScheduledJobOption
Register-ScheduledJob
Remove-JobTrigger
Set-JobTrigger
Set-ScheduledJob
Set-ScheduledJobOption
Unregister-ScheduledJob
Remove-JobTrigger
Reference
Module: PSScheduledJob

Delete job triggers from scheduled jobs.

Syntax
PowerShell

Remove-JobTrigger

[-TriggerId <Int32[]>]

[-InputObject] <ScheduledJobDefinition[]>

[<CommonParameters>]

PowerShell

Remove-JobTrigger

[-TriggerId <Int32[]>]

[-Id] <Int32[]>

[<CommonParameters>]

PowerShell

Remove-JobTrigger

[-TriggerId <Int32[]>]

[-Name] <String[]>

[<CommonParameters>]

Description
The Remove-JobTrigger cmdlet deletes job triggers from scheduled jobs.

A job trigger defines a recurring schedule or conditions for starting a scheduled job. To
manage job
triggers, use the New-JobTrigger, Add-JobTrigger, Set-JobTrigger, and Set-
ScheduledJob cmdlets.

Use the Name, ID, or InputObject parameters of Remove-JobTrigger to identify the


scheduled jobs from which the triggers are removed. Use the TriggerID parameter to
identify the
job triggers to delete. By default, Remove-JobTrigger deletes all job triggers
of a scheduled job.
Remove-JobTrigger is one of a collection of job scheduling cmdlets in the

PSScheduledJob module
that is included in Windows PowerShell.

For more information about Scheduled Jobs, see the About topics in the
PSScheduledJob module. Import
the PSScheduledJob module and then type: Get-Help
about_Scheduled* or see about_Scheduled_Jobs.

This cmdlet was introduced in Windows PowerShell 3.0.

Examples

Example 1: Delete all job triggers


PowerShell

Remove-JobTrigger -Name "Test*"

This command deletes all job triggers from scheduled job that have names that begin
with Test.

Example 2: Delete selected job triggers


PowerShell

Remove-JobTrigger -Name "BackupArchive" -TriggerID 3

This command deletes only the third trigger (ID = 3) from the BackupArchive scheduled
job.

Example 3: Delete AtStartup job triggers from all


scheduled jobs
PowerShell

function Delete-AtStartup

Get-ScheduledJob | Get-JobTrigger | Where-Object {$_.Frequency -eq


"AtStartup"} | ForEach-Object { Remove-JobTrigger -InputObject
$_.JobDefinition -TriggerID $_.ID}

}
This function deletes all AtStartup job triggers from all jobs on the local computer.
To
use the function, run the function in your session and then type Delete-AtStartup .

The Delete-AtStartup function contains a single command. The command uses the Get-
ScheduledJob
cmdlet to get the scheduled jobs on the local computer. A pipeline
operator ( | ) sends the
scheduled jobs to the Get-JobTrigger cmdlet, which gets all of
the job triggers from each of the
scheduled jobs. A pipeline operator sends the job
triggers to the Where-Object cmdlet, which
selects job triggers where the value of the
Frequency property of the job trigger equals AtStartup.

JobTrigger objects have a JobDefinition property that contains the scheduled job that
they
trigger. The remainder of the command uses that valuable feature.

A pipeline operator sends the AtStartup job triggers to the ForEach-Object cmdlet,
which runs a
Remove-JobTrigger command on each AtStartup trigger. The value of the
InputObject parameter of
Remove-JobTrigger is the scheduled job in the JobDefinition
property of the job trigger. The value
of the TriggerID parameter is the identifier in the
ID property of the job trigger.

Example 4: Delete a job trigger from a remote scheduled


job
PowerShell

Invoke-Command -ComputerName "Server01" { Remove-JobTrigger -ID 38 -


TriggerID 1 }

This command deletes the first job trigger from the Inventory job on the Server01
computer.

The command uses the Invoke-Command cmdlet to run the Remove-JobTrigger cmdlet on
the Server01
computer. The Remove-JobTrigger cmdlet uses the ID parameter to identify
the Inventory
scheduled job and the TriggerID parameter to specify the first trigger. The
ID parameter is
especially useful when multiple scheduled jobs have the same or similar
names.

Parameters
-Id
Specifies the identification numbers of the scheduled jobs. Remove-JobTrigger
deletes job triggers
from the specified scheduled jobs.

To get the identification number of scheduled jobs on the local computer or a


remote computer, use
the Get-ScheduledJob cmdlet.

Type: Int32[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies the scheduled jobs. Enter a variable that contains ScheduledJob objects or
type a
command or expression that gets ScheduledJob objects, such as a Get-
ScheduledJob command. You
can also pipe ScheduledJob objects to Remove-

JobTrigger .

Type: Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Specifies the names of the scheduled jobs. Remove-JobTrigger deletes the job
triggers from the
specified scheduled jobs. Wildcards are supported.

To get the names of scheduled jobs on the local computer or a remote computer,
use the
Get-ScheduledJob cmdlet.

Type: String[]

Position: 0

Default value: None


Accept pipeline input: False

Accept wildcard characters: False

-TriggerId

Deletes only the specified job triggers. By default, Remove-JobTrigger deletes all
triggers from
the scheduled jobs. Use this parameter when the scheduled jobs have
multiple job triggers.

Enter the trigger IDs of one or more job triggers of a scheduled job. If you specify
multiple
scheduled jobs, Remove-JobTrigger deletes the job trigger with the specified
ID from all scheduled
jobs.

Type: Int32[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition

You can pipe a scheduled job to this cmdlet.

Outputs
None

This cmdlet returns no output.

Related Links
Add-JobTrigger
Disable-JobTrigger
Disable-ScheduledJob
Enable-JobTrigger
Enable-ScheduledJob
Get-JobTrigger
Get-ScheduledJob
Get-ScheduledJobOption
New-JobTrigger
New-ScheduledJobOption
Register-ScheduledJob
Remove-JobTrigger
Set-JobTrigger
Set-ScheduledJob
Set-ScheduledJobOption
Unregister-ScheduledJob
Set-JobTrigger
Reference
Module: PSScheduledJob

Changes the job trigger of a scheduled job.

Syntax
PowerShell

Set-JobTrigger

[-InputObject] <ScheduledJobTrigger[]>

[-DaysInterval <Int32>]

[-WeeksInterval <Int32>]

[-RandomDelay <TimeSpan>]

[-At <DateTime>]

[-User <String>]

[-DaysOfWeek <DayOfWeek[]>]

[-AtStartup]

[-AtLogOn]

[-Once]

[-RepetitionInterval <TimeSpan>]

[-RepetitionDuration <TimeSpan>]

[-RepeatIndefinitely]

[-Daily]

[-Weekly]

[-PassThru]

[<CommonParameters>]

Description
The Set-JobTrigger cmdlet changes the properties of the job triggers of scheduled jobs.
You can
use it to change the time or frequency at which the jobs start or to change from
a time-based
schedules to schedules that are triggered by a logon or startup.

A job trigger defines a recurring schedule or conditions for starting a scheduled job.
Although job
triggers are not saved to disk, you can change the job triggers of
scheduled jobs, which are saved
to disk.

To change a job trigger of a scheduled job, begin by using the Get-JobTrigger cmdlet to
get the
job trigger of a scheduled job. Then, pipe the trigger to Set-JobTrigger or save
the trigger in a
variable and use the InputObject parameter of Set-JobTrigger cmdlet to
identify the trigger.
Use the remaining parameters of Set-JobTrigger to change the job
trigger.

When you change the type of a job trigger, such as changing a job trigger from a daily
or weekly
trigger to an AtLogon trigger, the original trigger properties are deleted.
However, if you
change the values of the trigger, but not its type, such as changing the
days in a weekly trigger,
only the properties that you specify are changed. All other
properties of the original job trigger
are retained.

Set-JobTrigger is one of a collection of job scheduling cmdlets in the PSScheduledJob

module that
is included in Windows PowerShell.

For more information about Scheduled Jobs, see the About topics in the
PSScheduledJob module. Import
the PSScheduledJob module and then type: Get-Help
about_Scheduled* or see
about_Scheduled_Jobs.

This cmdlet was introduced in Windows PowerShell 3.0.

Examples

Example 1: Change the days in a job trigger


This example shows how to change the days in a weekly job trigger.

PowerShell

Get-JobTrigger -Name "DeployPackage"

Id Frequency Time DaysOfWeek


Enabled

-- --------- ---- ---------- --


-----

1 Weekly 9/29/2011 12:00:00 AM {Wednesday, Saturday}


True

Get-JobTrigger -Name "DeployPackage" | Set-JobTrigger -DaysOfWeek


"Wednesday", "Sunday" -Passthru

Id Frequency Time DaysOfWeek


Enabled

-- --------- ---- ---------- --


-----

1 Weekly 9/29/2011 12:00:00 AM {Wednesday, Sunday}


True
The first command uses the Get-JobTrigger cmdlet to get the job trigger of the
DeployPackage
scheduled job. The output shows that the trigger starts the job at
midnight on Wednesdays and
Saturdays.

The second command uses the Get-JobTrigger cmdlet to get the job trigger of the
DeployPackage
scheduled job. A pipeline operator ( | ) sends the trigger to the Set-

JobTrigger cmdlet, which


changes the job trigger so that it starts the DeployPackage job

on Wednesdays and Sundays. The


command uses the Passthru parameter to return the
trigger after the change.

This command is not required; it is included only to show the effect of the trigger
change.

Example 2: Change the job trigger type


This example shows how to change the type of job trigger that starts a job. The
commands in this
example replace an AtStartup job trigger with a weekly trigger.

PowerShell

Get-JobTrigger -Name "Inventory"

Id Frequency Time DaysOfWeek


Enabled

-- --------- ---- ---------- --


-----

1 Daily 9/27/2011 11:00:00 PM


True

2 AtStartup
True

Get-JobTrigger -Name "Inventory" -TriggerID 2 | Set-JobTrigger -Weekly -


WeeksInterval 4 -DaysOfWeek Monday -At "12:00 AM"

Id Frequency Time DaysOfWeek


Enabled

-- --------- ---- ---------- --


-----

1 Daily 9/27/2011 11:00:00 PM


True

2 Weekly 10/31/2011 12:00:00 AM {Monday}


True

The first command uses the Get-JobTrigger cmdlet to get the job trigger of the
Inventory
scheduled job. The output shows that the job has two triggers a daily trigger

and an AtStartup
trigger.
The second command uses the Get-JobTrigger cmdlet to get the AtStartup job trigger
of the
Inventory job. The command uses the TriggerID parameter to identify the job
trigger. A
pipeline operator ( | ) sends the job trigger to the Set-JobTrigger cmdlet,
which changes it to a
weekly job trigger that runs every four weeks on Monday at
midnight. The command uses the
Passthru parameter to return the trigger after the
change.

This command is not required; it is included only to show the effect of the trigger
change.

Example 3: Change the user on a remote job trigger


PowerShell

Invoke-Command -ComputerName "Server01" -ScriptBlock {Get-ScheduledJob |


Get-JobTrigger | Where-Object {$_.User} | Set-JobTrigger -User
"Domain01/Admin02"}

This command changes the user in all AtLogon job triggers of scheduled jobs on the
Server01
computer.

The command uses the Invoke-Command cmdlet to run a command on the Server01
computer.

The remote command begins with a Get-ScheduledJob command that gets all scheduled
jobs on the
computer. The scheduled jobs are piped to the Get-JobTrigger cmdlet,
which gets the job triggers
of the scheduled jobs. Each job trigger contains a
JobDefinition property that contains the
scheduled job, so the trigger remains
associated with the scheduled job even when it is changed.

The job triggers are piped to the Where-Object cmdlet, which gets job triggers that have
the
User property. The selected job triggers are piped to the Set-JobTrigger cmdlet,
which changes
the user to Domain01\Admin02 .

Example 4: Change one of many job triggers


PowerShell

Get-JobTrigger -Name "SecurityCheck"

Id Frequency Time DaysOfWeek


Enabled

-- --------- ---- ---------- --


-----

1 Daily 4/24/2013 3:00:00 AM


True

2 Weekly 4/24/2013 4:00:00 PM {Sunday}


True

3 Once 4/24/2013 4:00:00 PM


True

Get-JobTrigger -Name "SecurityCheck" -TriggerID 3 | Format-List -Property *

At : 4/24/2012 4:00:00 PM

DaysOfWeek :

Interval : 1

Frequency : Once

RandomDelay : 00:00:00

RepetitionInterval : 01:00:00

RepetitionDuration : 1.00:00:00

User :

Id : 3

Enabled : True

JobDefinition :
Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition

Get-JobTrigger -Name "SecurityCheck" -TriggerId 3 | Set-JobTrigger -


RepetitionInterval (New-TimeSpan -Minutes 90)

Get-JobTrigger -Name "SecurityCheck" -TriggerID 3 | Format-List -Property *

At : 4/24/2012 4:00:00 PM

DaysOfWeek :

Interval : 1

Frequency : Once

RandomDelay : 00:00:00

RepetitionInterval : 01:30:00

RepetitionDuration : 1.00:00:00

User :

Id : 3

Enabled : True

JobDefinition :
Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition

The commands in this example changes the repetition interval of the Once job trigger of
SecurityCheck scheduled job from every 60 minutes to every 90 minutes. The

SecurityCheck
scheduled job has three job triggers, so the commands use the TriggerId
parameter of the
Get-JobTrigger cmdlet to identify the job trigger that is being
changed.

The first command uses the Get-JobTrigger cmdlet to get all job triggers of the
SecurityCheck
scheduled job. The output, which displays the IDs of the job triggers,

reveals that the Once job


trigger has an ID of 3 .
The second command uses the TriggerID parameter of the Get-JobTrigger cmdlet to
get the
Once trigger of the SecurityCheck scheduled job. The command pipes the
trigger to the
Format-List cmdlet, which displays all of the properties of the Once job
trigger. The output
shows that the trigger starts the job once every hour
(RepetitionInterval is 1 hour) for one day
(RepetitionDuration is 1 day).

The third command changes the repetition interval of the job trigger from one hour to
90 minutes.
The command does not return any output.

The fourth command displays the effect of the change.The output shows that the trigger
starts the
job once every 90 minutes (RepetitionInterval is 1 hour, 30 minutes) for one
day
(RepetitionDuration is 1 day).

Parameters
-At

Starts the job at the specified date and time. Enter a DateTime object, such as one
that the
Get-Date cmdlet returns, or a string that can be converted to a time, such as
April 19, 2012 15:00 , 12/31/2013 9:00 PM , or 3am .

If you don't specify an element of the DateTime object, such as seconds, that
element of the job
trigger is not changed. If the original job trigger didn't include a
DateTime object and you
omit an element, the job trigger is created with the
corresponding element from the current date and
time.

When using the Once parameter, set the value of the At parameter to a particular
date and
time. Because the default date in a DateTime object is the current date,
setting a time before
the current time without an explicit date results in a job trigger
for a time in the past.

DateTime objects, and strings that are converted to DateTime objects, are
automatically
adjusted to be compatible with the date and time formats selected for
the local computer in Region
and Language in Control Panel.

Type: DateTime

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-AtLogOn

Starts the scheduled job when the specified users log on to the computer. To specify
a user, use the
User parameter.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-AtStartup

Starts the scheduled job when Windows starts.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Daily

Specifies a recurring daily job schedule. Use the other parameters in the Daily
parameter set to
specify the schedule details.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-DaysInterval

Specifies the number of days between occurrences on a daily schedule. For example,
a value of 3
starts the scheduled job on days 1 , 4 , 7 and so on. The default value is
1.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-DaysOfWeek

Specifies the days of the week on which a weekly scheduled job runs. Enter day
names, such as
Monday , Thursday , integers 0 - 6 , where 0 represents Sunday, or an
asterisk ( * ) to
represent every day. This parameter is required in the Weekly
parameter set.

Day names are converted to their integer values in the job trigger. When you enclose
day names in
quotation marks in a command, enclose each day name in separate
quotation marks, such as
"Monday", "Tuesday" . If you enclose multiple day names in
a single quotation mark pair, the
corresponding integer values are summed. For
example, "Monday, Tuesday" ( 1 + 2 ) results in a
value of Wednesday ( 3 ).

Type: DayOfWeek[]

Accepted values: Sunday, Monday, Tuesday, Wednesday, Thursday, Friday,


Saturday

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies the job triggers. Enter a variable that contains ScheduledJobTrigger objects
or type a
command or expression that gets ScheduledJobTrigger objects, such as a
Get-JobTrigger command.
You can also pipe a ScheduledJobTrigger object to Set-
JobTrigger .
If you specify multiple job triggers, Set-JobTrigger makes the same changes to all
job triggers.

Type: Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Once

Specifies a non-recurring (one time) schedule.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-PassThru

Returns the job triggers that changed. By default, this cmdlet does not generate any
output.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RandomDelay

Enables a random delay that begins at the scheduled start time, and sets the
maximum delay value.
The length of the delay is set pseudo-randomly for each start
and varies from no delay to the time
specified by the value of this parameter. The
default value, zero ( 00:00:00 ), disables the random
delay.

Enter a timespan object, such as one returned by the New-TimeSpan cmdlet, or enter a
value in
<hours>:<minutes>:<seconds> format, which is automatically converted to a
timespan object.

Type: TimeSpan

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RepeatIndefinitely

This parameter, available starting in Windows PowerShell 4.0, eliminates the


necessity of specifying
a TimeSpan.MaxValue value for the RepetitionDuration
parameter to run a scheduled job
repeatedly, for an indefinite period.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RepetitionDuration

Repeats the job until the specified time expires. The repetition frequency is
determined by the
value of the RepetitionInterval parameter. For example, if the
value of RepetitionInterval
is 5 minutes and the value of RepetitionDuration is 2
hours, the job is triggered every five
minutes for two hours.

Enter a timespan object, such as one that the New-TimeSpan cmdlet returns or a string
that can be
converted to a timespan object, such as 1:05:30 .

To run a job indefinitely, add the RepeatIndefinitely parameter instead.


To stop a job before the job trigger repetition duration expires, set the
RepetitionDuration
value to zero ( 0 ).

To change the repetition duration or repetition interval of a Once job trigger, the
command must
include both the RepetitionInterval and RepetitionDuration
parameters. To change the
repetition duration or repetition intervals of other types
of job triggers, the command must include
the Once, At, RepetitionInterval and
RepetitionDuration parameters.

Type: TimeSpan

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RepetitionInterval

Repeats the job at the specified time interval. For example, if the value of this
parameter is 2
hours, the job is triggered every two hours. The default value, 0 , does
not repeat the job.

Enter a timespan object, such as one that the New-TimeSpan cmdlet returns or a string
that can be
converted to a timespan object, such as 1:05:30 .

To change the repetition duration or repetition interval of a Once job trigger, the
command must
include both the RepetitionInterval and RepetitionDuration
parameters. To change the
repetition duration or repetition intervals of other types
of job triggers, the command must include
the Once, At, RepetitionInterval and
RepetitionDuration parameters.

Type: TimeSpan

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-User
Specifies the users who trigger an AtLogon start of a scheduled job. Enter the name
of a user in
<UserName> or <Domain>\<Username> format or enter an asterisk ( * ) to
represent all users. The
default value is all users.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Weekly

Specifies a recurring weekly job schedule. Use the other parameters in the Weekly
parameter set
to specify the schedule details.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WeeksInterval

Specifies the number of weeks between occurrences on a weekly job schedule. For
example, a value of
3 starts the scheduled job on weeks 1 , 4 , 7 and so on. The
default value is 1 .

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger

You can pipe a job trigger to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger

When you use the PassThru parameter, this cmdlet returns the job triggers that it
changed.

Notes
Job triggers have a JobDefinition property that associates them with the
scheduled job. When
you change the job trigger of a scheduled job, the job is
changed. You do not need to use a
Set-ScheduledJob command to apply the
changed trigger to the scheduled job.

Related Links
Add-JobTrigger
Disable-JobTrigger
Disable-ScheduledJob
Enable-JobTrigger
Enable-ScheduledJob
Get-JobTrigger
Get-ScheduledJob
Get-ScheduledJobOption
New-JobTrigger
New-ScheduledJobOption
Register-ScheduledJob
Remove-JobTrigger
Set-JobTrigger
Set-ScheduledJob
Set-ScheduledJobOption
Unregister-ScheduledJob
Set-ScheduledJob
Reference
Module: PSScheduledJob

Changes scheduled jobs.

Syntax
PowerShell

Set-ScheduledJob

[-Name <String>]

[-ScriptBlock <ScriptBlock>]

[-Trigger <ScheduledJobTrigger[]>]

[-InitializationScript <ScriptBlock>]

[-RunAs32]

[-Credential <PSCredential>]

[-Authentication <AuthenticationMechanism>]

[-ScheduledJobOption <ScheduledJobOptions>]

[-InputObject] <ScheduledJobDefinition>

[-MaxResultCount <Int32>]

[-PassThru]

[-ArgumentList <Object[]>]

[-RunNow]

[-RunEvery <TimeSpan>]

[<CommonParameters>]

PowerShell

Set-ScheduledJob

[-Name <String>]

[-FilePath <String>]

[-Trigger <ScheduledJobTrigger[]>]

[-InitializationScript <ScriptBlock>]

[-RunAs32]

[-Credential <PSCredential>]

[-Authentication <AuthenticationMechanism>]

[-ScheduledJobOption <ScheduledJobOptions>]

[-InputObject] <ScheduledJobDefinition>

[-MaxResultCount <Int32>]

[-PassThru]

[-ArgumentList <Object[]>]

[-RunNow]

[-RunEvery <TimeSpan>]

[<CommonParameters>]

PowerShell
Set-ScheduledJob

[-InputObject] <ScheduledJobDefinition>

[-ClearExecutionHistory]

[-PassThru]

[<CommonParameters>]

Description
The Set-ScheduledJob cmdlet changes the properties of scheduled jobs, such as the
commands that
the jobs run or the credentials required to run the job. You can also use
it to clear the execution
history of the scheduled job.

To use this cmdlet, begin by using the Get-ScheduledJob cmdlet to get the scheduled
job. Then,
pipe the scheduled job to Set-ScheduledJob or save the job in a variable and
use the
InputObject parameter to identify the job. Use the remaining parameters of
Set-ScheduledJob to
change the job properties or clear the execution history.

Although you can use Set-ScheduledJob to change the triggers and options of a
scheduled job, the
Add-JobTrigger , Set-JobTrigger , and Set-ScheduledJobOption
cmdlets provide much easier ways to
accomplish those tasks. To create a new scheduled
job, use the Register-ScheduledJob cmdlet.

The Trigger parameter of Set-ScheduledJob adds one or more job triggers that start the
job.
The Trigger parameter is optional, so you can add triggers when you create the
scheduled job,
add job triggers later, add the RunNow parameter to start the job
immediately, use the
Start-Job cmdlet to start the job immediately at any time, or save
the untriggered scheduled job
as a template for other jobs.

Set-ScheduledJob is one of a collection of job scheduling cmdlets in the


PSScheduledJob module
that is included in Windows PowerShell.

For more information about Scheduled Jobs, see the About topics in the
PSScheduledJob module. Import
the PSScheduledJob module and then type: Get-Help
about_Scheduled* or see about_Scheduled_Jobs.

This cmdlet was introduced in Windows PowerShell 3.0.

Examples

Example 1: Change the script that a job runs


This example shows how to change the script that is run in a scheduled job.

PowerShell

Get-ScheduledJob -Name "Inventory"

Id Name Triggers Command


Enabled

-- ---- -------- -------


-------

1 Inventory {1} C:\Scripts\Get-Inventory.ps1


True

Get-ScheduledJob -Name "Inventory" | Set-ScheduledJob -FilePath


"C:\Scripts\Get-FullInventory.ps1" -Passthru

Id Name Triggers Command


Enabled

-- ---- -------- -------


-------

1 Inventory {1} C:\Scripts\Get-FullInventory.ps1


True

The first command uses the Get-ScheduledJob cmdlet to get the Inventory scheduled
job. The output
shows that the job runs the Get-Inventory.ps1 script.

The second command uses the Get-ScheduledJob cmdlet to get the Inventory scheduled
job. A pipeline
operator ( | ) sends the scheduled job to the Set-ScheduledJob cmdlet.
The Set-ScheduledJob
cmdlet uses the Script parameter to specify a new script, Get-
FullInventory.ps1 . The command
uses the Passthru parameter to return the scheduled

job after the change.

This command is not required; it is included only to show the effect of the script change.

Example 2: Delete the execution history of a scheduled


job
This example deletes the current execution history and saved job results for a scheduled
job.

PowerShell

Get-ScheduledJob BackupArchive | Set-ScheduledJob -ClearExecutionHistory

The command uses the Get-ScheduledJob cmdlet to get the BackupArchive scheduled
job. A pipeline
operator ( | ) sends the job to the Set-ScheduledJob cmdlet to change it.
The Set-ScheduledJob
cmdlet uses the ClearExecutionHistory parameter to delete the
execution history and saved
results.

For more information about the execution history and saved job results of scheduled
jobs, see about_Scheduled_Jobs.

Example 3: Change scheduled jobs on a remote computer


This command changes the initialization script in all scheduled jobs on remote
computers.

PowerShell

Invoke-Command -Computer "Server01, Server02" -ScriptBlock {Get-ScheduledJob


|

Set-ScheduledJob -InitializationScript \\SrvA\Scripts\SetForRun.ps1}

The command uses the Invoke-Command cmdlet to run a command on the Server01 and
Server02
computers.

The remote command begins with a Get-ScheduledJob command that gets all scheduled
jobs on the
computer. The scheduled jobs are piped to the Set-ScheduledJob cmdlet,
which changes the
initialization script to SetForRun.ps1 .

Parameters
-ArgumentList

Specifies values for the parameters of the script that is specified by the FilePath
parameter or
for the command that is specified by the ScriptBlock parameter.

Type: Object[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Authentication
Specifies the mechanism that is used to authenticate the user's credentials. The
acceptable values
for this parameter are:

Default

Basic
Credssp

Digest

Kerberos
Negotiate

NegotiateWithImplicitCredential

The default value is Default . For more information about the values of this
parameter, see AuthenticationMechanism Enumeration
in the PowerShell SDK.

U Caution

Credential Security Support 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.

Type: AuthenticationMechanism

Accepted values: Default, Basic, Negotiate, NegotiateWithImplicitCredential,


Credssp, Digest, Kerberos

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ClearExecutionHistory

Deletes the current execution history and the saved results of the scheduled job.

The job execution history and job results are saved with the scheduled job in the
$HOME\AppData\Local\Microsoft\Windows\PowerShell\ScheduledJobs directory on the
computer on which
the job is created. To see the execution history, use the Get-Job
cmdlet. To get the job results,
use the Receive-Job cmdlet.

This parameter does not affect the events that Task Scheduler writes to the Windows
event logs and
it does not stop Windows PowerShell from saving job results. To
manage the number of job results
that are saved, use the MaxResultCount
parameter.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Credential

Specifies a user account that has permission to run the scheduled job. 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. If you enter only a user name,
you will be prompted for a
password.

Type: PSCredential

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-FilePath

Specifies a script that the scheduled job runs. Enter the path to a .ps1 file on the local
computer.
To specify default values for the script parameters, use the ArgumentList
parameter. Every
scheduled job must have either a ScriptBlock or FilePath value.

Type: String

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InitializationScript

Specifies the fully qualified path to a Windows PowerShell script ( .ps1 ). The
initialization
script runs in the session that is created for the background job before
the commands that are
specified by the ScriptBlock parameter or the script that is
specified by the FilePath
parameter. You can use the initialization script to configure
the session, such as adding files,
functions, or aliases, creating directories, or
checking for prerequisites.

To specify a script that runs the primary job commands, use the FilePath parameter.

If the initialization script generates an error, including a non-terminating error, the


current
instance of the scheduled job does not run and its status is Failed.

Type: ScriptBlock

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies the scheduled job to be changed. Enter a variable that contains


ScheduledJobDefinition
objects or type a command or expression that gets
ScheduledJobDefinition objects, such as a
Get-ScheduledJob command. You can also
pipe a ScheduledJobDefinition object to
Set-ScheduledJob .

If you specify multiple scheduled jobs, Set-ScheduledJob makes the same changes to
all jobs.

Type: Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition

Position: 0

Default value: None

Accept pipeline input: True


Accept wildcard characters: False

-MaxResultCount

Specifies how many job result entries are maintained for the scheduled job. The
default value is 32.

Windows PowerShell saves the execution history and results of each triggered
instance of the
scheduled job on disk. The value of this parameter determines the
number of job instance results
that are saved for this scheduled job. When the
number of job instance results exceeds this value,
Windows PowerShell deletes the
results of the oldest job instance to make room for the results of
the newest job
instance.

The job execution history and job results are saved in the
$HOME\AppData\Local\Microsoft\Windows\PowerShell\ScheduledJobs\
<JobName>\Output\<Timestamp>
directories on the computer on which the job is

created. To see the execution history, use the


Get-Job cmdlet. To get the job results,
use the Receive-Job cmdlet.

The MaxResultCount parameter sets the value of the ExecutionHistoryLength


property of the
scheduled job.

To delete the current execution history and job results, use the
ClearExecutionHistory
parameter.

Type: Int32

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Name

Specifies a new name for the scheduled job and instances of the scheduled job. The
name must be
unique on the local computer.

To identify the scheduled job to be changed, use the InputObject parameter or pipe
a scheduled
job from Get-ScheduledJob to Set-ScheduledJob .
This parameter does not change the names of job instances on disk. It affects only
job instances
that are started after this command completes.

Type: String

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-PassThru

Returns an object representing the item with which you are working. By default, this
cmdlet does not
generate any output.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RunAs32

Runs the scheduled job in a 32-bit process.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RunEvery

Used to specify how often to run the job. For example, use this option to run a job
every 15
minutes.

Type: TimeSpan
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RunNow

Starts a job immediately, as soon as the Set-ScheduledJob cmdlet is run. This


parameter eliminates
the need to trigger Task Scheduler to run a Windows
PowerShell script immediately after
registration, and does not require users to create
a trigger that specifies a starting date and
time.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ScheduledJobOption

Sets options for the scheduled job. Enter a ScheduledJobOptions object, such as one
that you
create by using the New-ScheduledJobOption cmdlet, or a hash table value.

You can set options for a scheduled job when you register the scheduled job or use
the
Set-ScheduledJobOption or Set-ScheduledJob cmdlets to set or change options.

Many of the options and their default values determine whether and when a
scheduled job runs. Be
sure to review these options before scheduling a job. For a
description of the scheduled job
options, including the default values, see New-
ScheduledJobOption .

To submit a hash table, use the following keys.


In the following hash table, the keys
are shown with their default values.

@{# Power SettingsStartIfOnBattery=$False;StopIfGoingOnBattery=$True;

WakeToRun=$False; # Idle SettingsStartIfNotIdle=$False; IdleDuration="00:10:00";

IdleTimeout="01:00:00"; StopIfGoingOffIdle=$True; RestartOnIdleResume=$False;#


Security settingsShowInTaskScheduler=$TrueRunElevated=$False;#
MiscRunWithoutNetwork=$False;DoNotAllowDemandStart=$False;MultipleInstancePolicy

=IgnoreNew# Can be IgnoreNew, Parallel, Queue, StopExisting}

Type: Microsoft.PowerShell.ScheduledJob.ScheduledJobOptions

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-ScriptBlock

Specifies the commands that the scheduled job runs. Enclose the commands in
braces ( {} ) to create
a script block. To specify default values for command
parameters, use the ArgumentList
parameter.

Every Register-ScheduledJob command must use either the ScriptBlock or FilePath


parameters.

Type: ScriptBlock

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Trigger

Specifies the triggers for the scheduled job. Enter one or more ScheduledJobTrigger
objects,
such as the objects that the New-JobTrigger cmdlet returns, or a hash table
of job trigger keys
and values.

A job trigger starts a scheduled job automatically on a one-time or recurring


scheduled or when an
event occurs.

Job triggers are optional. You can add a trigger when you create the scheduled job,
use the
Add-JobTrigger or Set-ScheduledJob cmdlets to add triggers later, or use the
Start-Job cmdlet
to start the scheduled job immediately. You can also create and

maintain a scheduled job that has no


job triggers.
To submit a hash table, use the following keys.

@{Frequency="Once" (or Daily, Weekly, AtStartup, AtLogon);At="3am" (or any valid


time string);
DaysOfWeek="Monday", "Wednesday" (or any combination of day names);
Interval=2 (or any valid frequency interval);
RandomDelay="30minutes" (or any valid
timespan string);
User="Domain1\User01" (or any valid user; used only with the
AtLogon frequency value)

Type: Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger[]

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition

You can pipe a scheduled job to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition

When you use the PassThru parameter, this cmdlet returns the scheduled job that it
changed.

Related Links
Add-JobTrigger
Disable-JobTrigger
Disable-ScheduledJob
Enable-JobTrigger
Enable-ScheduledJob
Get-JobTrigger
Get-ScheduledJob
Get-ScheduledJobOption
New-JobTrigger
New-ScheduledJobOption
Register-ScheduledJob
Remove-JobTrigger
Set-JobTrigger
Set-ScheduledJob
Set-ScheduledJobOption
Unregister-ScheduledJob
Set-ScheduledJobOption
Reference
Module: PSScheduledJob

Changes the job options of a scheduled job.

Syntax
PowerShell

Set-ScheduledJobOption

[-InputObject] <ScheduledJobOptions>

[-PassThru]

[-RunElevated]

[-HideInTaskScheduler]

[-RestartOnIdleResume]

[-MultipleInstancePolicy <TaskMultipleInstancePolicy>]

[-DoNotAllowDemandStart]

[-RequireNetwork]

[-StopIfGoingOffIdle]

[-WakeToRun]

[-ContinueIfGoingOnBattery]

[-StartIfOnBattery]

[-IdleTimeout <TimeSpan>]

[-IdleDuration <TimeSpan>]

[-StartIfIdle]

[<CommonParameters>]

Description
The Set-ScheduledJobOptions cmdlet changes the job options of scheduled jobs.

To change the options of a scheduled job, begin by using the Get-ScheduledJobOption


cmdlet to get
the job options of a scheduled job. Then, pipe the options to Set-
ScheduledJobOption or save the
options in a variable and use the InputObject parameter

of Set-ScheduledJobOption cmdlet to
identify the options. Use the remaining parameters
of Set-ScheduledJobOption to change the job
options.

To turn on a job option, use the parameter that sets that option. To turn off an option,
type the
parameter name, a colon ( : ), and $false . For example, to turn off the
RunElevated option,
type -RunElevated:$false .
Each job options object includes a JobDefinition property that contains the scheduled
job, so the
association with the scheduled job is retained when the job options are
changed.

The scheduled job options determine how the job runs when it is started by Task
Scheduler. These
options to not apply when you use the Start-Job cmdlet to start a
scheduled job.

Set-ScheduledJobOption is one of a collection of job scheduling cmdlets in the


PSScheduledJob
module that is included in Windows PowerShell.

For more information about Scheduled Jobs, see the About topics in the
PSScheduledJob module. Import
the PSScheduledJob module and then type: Get-Help
about_Scheduled* or see about_Scheduled_Jobs.

This cmdlet was introduced in Windows PowerShell 3.0.

Examples

Example 1: Change job options


PowerShell

Get-ScheduledJobOption -Name "DeployPackage"

StartIfOnBatteries : False

StopIfGoingOnBatteries : True

WakeToRun : False

StartIfNotIdle : True

StopIfGoingOffIdle : False

RestartOnIdleResume : False

IdleDuration : 00:10:00

IdleTimeout : 01:00:00

ShowInTaskScheduler : True

RunElevated : False

RunWithoutNetwork : False

DoNotAllowDemandStart : False

MultipleInstancePolicy : IgnoreNew

JobDefinition :

Get-ScheduledJobOption -Name "DeployPackage" |

Set-ScheduledJobOption -WakeToRun -RequireNetwork:$false -Passthru

StartIfOnBatteries : False

StopIfGoingOnBatteries : True

WakeToRun : True

StartIfNotIdle : True

StopIfGoingOffIdle : False

RestartOnIdleResume : False

IdleDuration : 00:10:00

IdleTimeout : 01:00:00

ShowInTaskScheduler : True

RunElevated : False

RunWithoutNetwork : True

DoNotAllowDemandStart : False

MultipleInstancePolicy : IgnoreNewJobDefinition :

This example shows how to change the options of a scheduled job on the local
computer.

The first command uses the Get-ScheduledJobOption cmdlet to get the job options of
the
DeployPackage scheduled job. The output shows that the WakeToRun and
RunElevated properties are set
to $false .

The second command uses the Set-ScheduledJobOpton cmdlet to change the job
options so the values
of the WakeToRun and RunWithoutNetwork properties are $True.
The command uses the Passthru
parameter to return the trigger after the change.

This command is not required; it is included only to show the effect of the option
change.

Example 2: Change an option on all remote scheduled


jobs
PowerShell

Invoke-Command -Computer "Server01" -ScriptBlock {

Get-ScheduledJob |

Get-ScheduledJobOption |

Set-ScheduledJobOption -IdleTimeout 2:00:00

This command changes the value of the IdleTimeout from one hour (the default value)
to two hours
on all scheduled jobs on the Server01 computer.

The command uses the Invoke-Command cmdlet to run a command on the Server01
computer.

The remote command begins with a Get-ScheduledJob command that gets all scheduled
jobs on the
computer. The scheduled jobs are piped to the Get-ScheduledJobOption
cmdlet, which gets the job
options of the scheduled jobs. Each job options object
contains a JobDefinition property that
contains the scheduled job, so the options object
remains associated with the scheduled job even
when it is changed.

The job triggers are piped to the Set-ScheduledJobOption cmdlet, which changes the
value of the
IdleTimeout option to two hours (2:00:00).

Parameters
-ContinueIfGoingOnBattery

Do not stop the scheduled job if the computer switches to battery power
(disconnects from AC power)
while the job is running. By default, scheduled jobs
stop when the computer disconnects from AC
power.

The ContinueIfGoingOnBattery parameter sets the value of the


StopIfGoingOnBatteries property of
scheduled jobs to $true .

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-DoNotAllowDemandStart

Start the job only when it is triggered. Users cannot start the job manually, such as
by using the
Run feature in Task Scheduler.

This parameter only affects Task Scheduler. It does not prevents users from using the
Start-Job
cmdlet to start the job.

The DoNotAllowDemandStart parameter sets the value of the


DoNotAllowDemandStart property of
scheduled jobs to $true .

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False


Accept wildcard characters: False

-HideInTaskScheduler

Do not display the job in Task Scheduler. This value affects only the computer on
which the job
runs. By default, scheduled tasks appear in Task Scheduler.

Even if a task is hidden, users can display the task by selecting the Show hidden
tasks view
option in Task Scheduler.

The HideInTaskScheduler parameter sets the value of the ShowInTaskScheduler


property of
scheduled jobs to $false .

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-IdleDuration

Specifies how long the computer must be idle before the job starts. The default value
is 10 minutes.
If the computer is not idle for the specified duration before the value
of IdleTimeout expires,
the scheduled job does not run until the next scheduled
time, if any.

Enter a timespan object, such as one generated by the New-TimeSpan cmdlet, or enter
a value in
<hours>:<minutes>:<seconds> format that is automatically converted to a
TimeSpan object.

To enable this value, use the StartIfIdle parameter. By default, the StartIfNotIdle
property
of scheduled jobs is set to $true and Windows PowerShell ignores the
IdleDuration and
IdleTimeout values.

Type: TimeSpan

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-IdleTimeout

Specifies how long the computer must be idle before the job starts. The default value
is 10 minutes.
If the computer is not idle for the specified duration before the value
of IdleTimeout expires,
the scheduled job does not run until the next scheduled
time, if any.

Enter a timespan object, such as one generated by the New-TimeSpan cmdlet, or enter
a value in
<hours>:<minutes>:<seconds> format that is automatically converted to a
TimeSpan object.

To enable this value, use the StartIfIdle parameter. By default, the StartIfNotIdle
property of
scheduled jobs is set to $True and Windows PowerShell ignores the
IdleDuration and
IdleTimeout values.

Type: TimeSpan

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies the job options. Enter a variable that contains ScheduledJobOptions


objects or type a
command or expression that gets ScheduledJobOptions objects,
such as a Get-ScheduledJobOption
command. You can also pipe a
ScheduledJobOptions object to Set-ScheduledJobOption .

Type: Microsoft.PowerShell.ScheduledJob.ScheduledJobOptions

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-MultipleInstancePolicy
Determines how the system responds to a request to start an instance of a
scheduled job while
another instance of the job is running. The acceptable values for
this parameter are:

IgnoreNew - The new job instance is ignored. This is the default value.
Parallel - The new job instance starts immediately.

Queue - The new job instance starts as soon as the current instance completes.

StopExisting - The current instance of the job stop and the new instance starts.

To run the job, all conditions for the job schedule must be met. For example, if the
conditions that
are set by the RequireNetwork, IdleDuration, and IdleTimeout
parameters are not
satisfied, the job instance is not started, regardless of the value of
this parameter.

Type: Microsoft.PowerShell.ScheduledJob.TaskMultipleInstancePolicy

Accepted values: None, IgnoreNew, Parallel, Queue, StopExisting

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-PassThru

Returns an object representing the item with which you are working. By default, this
cmdlet does not
generate any output.

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RequireNetwork

Runs the scheduled job only when network connections are available.

If you specify this parameter and the network is not available at the scheduled start
time, the job
does not run until the next scheduled start time, if any.
The RequireNetwork parameter sets the value of the RunWithoutNetwork property
of scheduled jobs
to $false .

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RestartOnIdleResume

Restarts a scheduled job when the computer becomes idle. This parameter works
with the
StopIfGoingOffIdle parameter, which suspends a running scheduled job if
the computer becomes
active (leaves the idle state).

The RestartOnIdleResume parameter sets the value of the RestartOnIdleResume


property of
scheduled jobs to $true .

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-RunElevated

Runs the scheduled job with the permissions of a member of the Administrators
group on the computer
on which the job runs.

To enable a scheduled job to run with Administrator permissions, use the Credential
parameter of
Register-ScheduledJob to provide explicit credential for the job.

The RunElevated parameter sets the value of the RunElevated property of scheduled
jobs to
$true .

Type: SwitchParameter

Position: Named
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-StartIfIdle

Starts the scheduled job if the computer has been idle for the time specified by the
IdleDuration parameter before the time specified by the IdleTimeout parameter
expires.

By default, the IdleDuration and IdleTimeout parameters are ignored and the job
starts at
the scheduled start time even if the computer is busy.

If you specify this parameter and the computer is busy (not idle) at the scheduled
start time, the
job does not run until the next scheduled start time, if any.

The StartIfIdle parameter sets the value of the StartIfNotIdle property of scheduled
jobs to
$false .

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-StartIfOnBattery

Starts the scheduled job even if the computer is running on batteries at the
scheduled start time.
The default value is $false .

The StartIfOnBattery parameter sets the value of the StartIfOnBatteries property of


scheduled jobs to $true .

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False


-StopIfGoingOffIdle

Suspends a running scheduled job if the computer becomes active (not idle) while
the job is running.

By default, a scheduled job that is suspended when the computer becomes active
resumes when the
computer becomes idle again. To change this default behavior,
use the RestartOnIdleResume
parameter.

The StopIfGoingOffIdle parameter sets the value of the StopIfGoingOffIdle property


of
scheduled jobs to $true .

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WakeToRun

Wakes the computer from a Hibernate or Sleep state at the scheduled start time so it
can run the
job. By default, if the computer is in a Hibernate or Sleep state at the
scheduled start time, the
job does not run.

The WakeToRun parameter sets the value of the WakeToRun property of scheduled
jobs to $true .

Type: SwitchParameter

Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

Inputs
Microsoft.PowerShell.ScheduledJob.ScheduledJobOptions
You can pipe a scheduled job options object to this cmdlet.

Outputs
None

By default, this cmdlet returns no output.

Microsoft.PowerShell.ScheduledJob.ScheduledJobOptions

When you use the PassThru parameter, this cmdlet returns the job options that were
changed.

Related Links
Add-JobTrigger
Disable-JobTrigger
Disable-ScheduledJob
Enable-JobTrigger
Enable-ScheduledJob
Get-JobTrigger
Get-ScheduledJob
Get-ScheduledJobOption
New-JobTrigger
New-ScheduledJobOption
Register-ScheduledJob
Remove-JobTrigger
Set-JobTrigger
Set-ScheduledJob
Set-ScheduledJobOption
Unregister-ScheduledJob
Unregister-ScheduledJob
Reference
Module: PSScheduledJob

Deletes scheduled jobs on the local computer.

Syntax
PowerShell

Unregister-ScheduledJob

[-InputObject] <ScheduledJobDefinition[]>

[-Force]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Unregister-ScheduledJob

[-Id] <Int32[]>

[-Force]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

PowerShell

Unregister-ScheduledJob

[-Name] <String[]>

[-Force]

[-WhatIf]

[-Confirm]

[<CommonParameters>]

Description
The Unregister-ScheduledJob cmdlet deletes scheduled jobs from the local computer.

When it deletes or unregisters a scheduled job, Unregister-ScheduledJob deletes the


directory for
the scheduled job (in the
$HOME\AppData\Local\Microsoft\Windows\PowerShell\ScheduledJobs directory ), which
contains the XML
file that defines the scheduled job, the job execution history, and all
job results. This action
also deletes the job from Task Scheduler.

Unregister-ScheduledJob deletes only the scheduled jobs that are created by using the

Register-ScheduledJob cmdlet. It does not delete scheduled jobs that are created in
Task
Scheduler.

You can use the parameters of Unregister-ScheduledJob to delete scheduled jobs by ID


or name, or
pipe scheduled jobs from Get-ScheduledJob to Unregister-ScheduledJob .

Unregister-ScheduledJob is one of a collection of job scheduling cmdlets in the

PSScheduledJob
module that is included in Windows PowerShell.

For more information about Scheduled Jobs, see the About topics in the
PSScheduledJob module. Import
the PSScheduledJob module and then type: Get-Help
about_Scheduled* or see about_Scheduled_Jobs.

This cmdlet was introduced in Windows PowerShell 3.0.

Examples

Example 1: Delete a scheduled job


PowerShell

Unregister-ScheduledJob TestJob

This command deletes the TestJob scheduled job on the local computer.

Example 2: Delete all scheduled jobs


PowerShell

Get-ScheduledJob | Unregister-ScheduledJob -Force

Unregister-ScheduledJob -Name "*" -Force

This example shows two different commands that delete all scheduled jobs on the local
computer.

The first command uses the Get-ScheduledJob cmdlet to get all scheduled jobs on the
local
computer. A pipeline operator ( | ) sends the scheduled jobs to Unregister-
ScheduleJob , which
deletes them.

The second command uses the Name parameter of Unregister-ScheduledJob with a


value of all
( * ) to delete all scheduled jobs.

Both commands use the Force parameter, which deletes a scheduled job even if an
instance of the
job is running.

Example 3: Delete a scheduled job on a remote computer


PowerShell

Invoke-Command -ComputerName "Server01" { Unregister-ScheduledJob -Name


"Test*"}

This command deletes scheduled jobs with names that begin with Test on the Server01
remote computer.
The command uses the Invoke-Command cmdlet to run the
Unregister-ScheduledJob command on the
Server02 computer.

Parameters
-Confirm

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter

Aliases: cf

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

-Force

Deletes the scheduled job even if an instance of the job is running. By default,
Unregister-ScheduledJob does not interrupt running jobs.

Type: SwitchParameter
Position: Named

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-Id

Deletes the scheduled jobs with the specified identification numbers (ID). Enter the
IDs of
scheduled jobs on the computer.

Type: Int32[]

Position: 0

Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-InputObject

Specifies a scheduled job. Enter a variable that contains ScheduledJob objects or


type a command
or expression that gets ScheduledJob objects, such as a Get-
ScheduledJob command. You can also
pipe ScheduledJob objects to Unregister-

JobTrigger .

Type: Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition[]

Position: 0

Default value: None

Accept pipeline input: True

Accept wildcard characters: False

-Name

Deletes the scheduled jobs with the specified names. Enter the names of one or
more scheduled jobs
on the computer. Wildcards are supported.

Type: String[]

Position: 0
Default value: None

Accept pipeline input: False

Accept wildcard characters: False

-WhatIf

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter

Aliases: wi

Position: Named

Default value: False

Accept pipeline input: False

Accept wildcard characters: False

Inputs
Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition

You can pipe a scheduled job to this cmdlet.

Outputs
None

This cmdlet returns no output.

Related Links
Add-JobTrigger
Disable-JobTrigger
Disable-ScheduledJob
Enable-JobTrigger
Enable-ScheduledJob
Get-JobTrigger
Get-ScheduledJob
Get-ScheduledJobOption
New-JobTrigger
New-ScheduledJobOption
Register-ScheduledJob
Remove-JobTrigger
Set-JobTrigger
Set-ScheduledJob
Set-ScheduledJobOption
Unregister-ScheduledJob
PSWorkflow
Reference

This section contains the help topics for the cmdlets that are installed with Windows
PowerShell
PSWorkflow module, which contains cmdlets that support the Windows
PowerShell Workflow feature.

PSWorkflow
New- Creates an object that contains session configuration options for
PSWorkflowExecutionOption workflow sessions.

New-PSWorkflowSession Creates a workflow session.


about_ActivityCommonParameters
Article • 09/19/2022 • 16 minutes to read

SHORT DESCRIPTION
Describes the parameters that Windows PowerShell Workflow adds to activities.

LONG DESCRIPTION
Windows PowerShell Workflow adds the activity common parameters to activities
that
are derived from the PSActivity base class. This category includes the
InlineScript
activity and Windows PowerShell cmdlets that are implemented as
activities, such as
Get-Process and Get-WinEvent .

The activity common parameters are not valid on the Suspend-Workflow and
Checkpoint-
Workflow activities and they are not added to cmdlets or
expressions that Windows

PowerShell Workflow automatically runs in an


InlineScript script block or similar activity.
The activity common
parameters are available on the InlineScript activity, but not on
commands
in the InlineScript script block.

Several of the activity common parameters are also workflow common parameters
or
Windows PowerShell common parameters. Other activity common parameters are
unique to activities.

For information about the workflow common parameters, see


about_WorkflowCommonParameters. For
information about the Windows PowerShell
common parameters, see
about_CommonParameters.

LIST OF ACTIVITY COMMON PARAMETERS

AppendOutput PSDebug

Debug PSDisableSerialization

DisplayName PSDisableSerializationPreference

ErrorAction PSError

Input PSPersist

MergeErrorToOutput PSPort

PSActionRetryCount PSProgress

PSActionRetryIntervalSec PSProgressMessage

PSActionRunningTimeoutSec PSRemotingBehavior

PSApplicationName PSRequiredModules

PSAuthentication PSSessionOption

PSCertificateThumbprint PSUseSSL

PSComputerName PSVerbose

PSConfigurationName PSWarning

PSConnectionRetryCount Result

PSConnectionRetryIntervalSec UseDefaultInput

PSConnectionURI Verbose

PSCredential WarningAction

PARAMETER DESCRIPTIONS
This section describes the activity common parameters.

AppendOutput <Boolean>

A value of $True adds the output of the activity to the value of the variable.
A value of
$False has no effect. By default, assigning a value to a variable
replaces the variable

value.

For example, the following commands add a process object to the service object
in the
$x variable.

PowerShell

Workflow Test-Workflow

$x = Get-Service

$x = Get-Process -AppendOutput $true

This parameter is designed for XAML-based workflows. In script workflows, you


can also
use the += assignment operator to add output to the value of a
variable, as shown in
the following example.

PowerShell

Workflow Test-Workflow

$x = Get-Service

$x += Get-Process

Debug <SwitchParameter>
Displays programmer-level detail about the operation performed by the command.
The
Debug parameter overrides the value of the $DebugPreference variable
for the current
command. This parameter works only when the command generates
debugging
messages. This parameter is also a Windows PowerShell common
parameter.

DisplayName <String>

Specifies a friendly name for the activity. The DisplayName value appears in
the
progress bar while the workflow runs and in the value of the Progress
property of the
workflow job. When the PSProgressMessage parameter is also
included in the
command, the progress bar content appears in
<DisplayName>:<PSProgressMessage>
format.

ErrorAction <ActionPreference>
Determines how the activity responds to a non-terminating error from the
command. It
has no effect on termination errors. This parameter works only when
the command
generates a non-terminating error, such as those from the
Write-Error cmdlet. The
ErrorAction parameter overrides the value of the
$ErrorActionPreference variable for
the current command. This parameter is
also a Windows PowerShell common
parameter.

Valid values:

Continue . Displays the error message and continues executing the command.

Continue is the default value.

Ignore . Suppresses the error message and continues executing the command.
Unlike SilentlyContinue , Ignore does not add the error message to the
$Error
automatic variable. The Ignore value is introduced in Windows
PowerShell 3.0.

Inquire . Displays the error message and prompts you for confirmation before

continuing execution. This value is rarely used.

Suspend . Automatically suspends a workflow job to allow for further


investigation.
After investigation, the workflow can be resumed.

SilentlyContinue . Suppresses the error message and continues executing the


command.

Stop . Displays the error message and stops executing the command.
Input <Object[]>
Submits a collection of objects to

You might also like