Powershell Module Psdocs Powershell 5.1
Powershell Module Psdocs Powershell 5.1
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-CimSession Gets the CIM session objects from the current session.
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.
Examples
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
-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
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:
Examples
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.
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
$c.CimClasName
Win32_LoadOrderGroupServiceDependencies
Win32_DependentService
Win32_SystemServices
Win32_LoadOrderGroupServiceMembers
Win32_ServiceSpecificationService
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
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
-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[]
Position: Named
-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
-KeyOnly
Returns objects with only key properties populated. This reduces the amount of data
that is
transferred over the network.
Type: SwitchParameter
Position: Named
-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
-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.
Type: UInt32
Aliases: OT
Position: Named
-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.
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
-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
Inputs
None
Related Links
Get-CimClass
Get-CimInstance
Get-CimClass
Reference
Module: CimCmdlets
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
PowerShell
PowerShell
PowerShell
PowerShell
Get-CimClass -ClassName Win32*Disk* -QualifierName Association
PowerShell
PowerShell
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
Position: Named
-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
-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[]
Position: Named
-MethodName
Finds the classes that have a method matching this name. You can use wildcard
characters with this
parameter.
Type: String
Position: Named
-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
-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.
Aliases: OT
Position: Named
-PropertyName
Finds the classes which have a property matching this name. You can use wildcard
characters with
this parameter.
Type: String
Position: Named
-QualifierName
Filters the classes by class level qualifier name. You can use wildcard characters with
this
parameter.
Type: String
Position: Named
Inputs
None
Related Links
New-CimSession
Get-CimInstance
Reference
Module: CimCmdlets
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 the InputObject parameter is specified, the cmdlet works in one of the following ways:
Examples
PowerShell
PowerShell
PowerShell
PowerShell
PowerShell
$x = New-CimInstance -ClassName Win32_Process -Namespace root\cimv2 -
Property @{ "Handle"=0 } -Key Handle -ClientOnly
Get-CimInstance -CimInstance $x
PowerShell
Name KernelModeTime
---- --------------
PowerShell
PowerShell
PowerShell
The instance retrieved with the Property parameter can be used to perform other CIM
operations,
for example Set-CimInstance or Invoke-CimMethod .
PowerShell
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
-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
-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[]
Position: Named
-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
-InputObject
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.
If the CIM class does not implement the get operation, then specifying the
InputObject parameter
returns an error.
Type: CimInstance
Aliases: CimInstance
Position: 0
-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
-Namespace
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
-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.
Type: UInt32
Aliases: OT
Position: Named
-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
-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
-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
-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.
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
-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
Inputs
CimInstance
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
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
Examples
PowerShell
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
PowerShell
Id : 2
Name : CimSession2
InstanceId : c0095981-52c5-4e7f-a5bb-c4c680541710
ComputerName : Server02
Protocol : WSMAN
PowerShell
ComputerName InstanceId
------------ ----------
Server01 d1413bc3-162a-4cb8-9aec-4d2c61253d59
Server02 c0095981-52c5-4e7f-a5bb-c4c680541710
PowerShell
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
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[]
Position: 0
-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.
Type: UInt32[]
Position: 0
-InstanceId
Type: Guid[]
Position: Named
-Name
Gets one or more CIM sessions which contain the specified friendly names. Wildcard
characters are
permitted.
Type: String[]
Position: Named
Inputs
None
Outputs
CimSession
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
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
Inputs
None
Outputs
Object
Invoke-CimMethod
Reference
Module: CimCmdlets
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 the InputObject parameter is specified, the cmdlet works in one of the following ways:
Examples
PowerShell
PowerShell
PowerShell
PowerShell
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
-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.
Type: CimClass
Position: 0
-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
-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
-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[]
Position: Named
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-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
-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
-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.
Type: UInt32
Aliases: OT
Position: Named
-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
Specifies the query language used for the Query parameter. The acceptable values
for this parameter
are: WQL or CQL.
Type: String
Position: Named
-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.
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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
CimClass
CimInstance
Outputs
PSCustomObject
Related Links
Get-CimClass
Get-CimInstance
Get-CimSession
New-CimSession
New-CimInstance
Reference
Module: CimCmdlets
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
PowerShell
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.
PowerShell
PowerShell
Get-CimInstance -CimInstance $a
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.
PowerShell
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
Type: CimClass
Position: 0
Default value: None
-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
-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
-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
-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[]
Position: Named
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-Key
Specifies the properties that are used as keys. CimSession and ComputerName
cannot be used
when Key is specified.
Type: String[]
Position: Named
-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
-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
-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
-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.
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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
None
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
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
PowerShell
New-CimSession
PowerShell
PowerShell
PowerShell
PowerShell
PowerShell
PowerShell
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
Type: PasswordAuthenticationMechanism
Position: Named
-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.
Type: String
Position: Named
-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 the computer is in a different domain than the user, you must specify the fully
qualified domain
name.
Type: String[]
Position: 1
-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: "[email protected]"
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
-Name
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
-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.
Aliases: OT
Position: Named
-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:
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
-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
-SkipTestConnection
Type: SwitchParameter
Position: Named
Inputs
None
Outputs
CimSession
Related Links
Get-ChildItem
Get-Credential
Get-Item
Get-CimSession
Remove-CimSession
New-CimSessionOption
about_CimSession
New-CimSessionOption
Reference
Module: CimCmdlets
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
PowerShell
PowerShell
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:
Type: CultureInfo
Position: Named
-EncodePortInServicePrincipalName
Type: SwitchParameter
Position: Named
-Encoding
Specifies the encoding used for the WsMan protocol. The acceptable values for this
parameter are:
Default, Utf8, or Utf16.
Type: PacketEncoding
Position: Named
-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
-Impersonation
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.
Type: ImpersonationType
Position: Named
-MaxEnvelopeSizeKB
Specifies the size limit of WsMan XML messages for either direction.
Type: UInt32
Position: Named
-NoEncryption
Type: SwitchParameter
Position: Named
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
-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
-Protocol
Specifies the protocol to use. The acceptable values for this parameter are: DCOM,
Default,
or Wsman.
Type: ProtocolType
Position: 1
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
Position: Named
-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.
Type: String
Position: Named
-ProxyCredential
Specifies the credentials to use for proxy authentication. Enter one of the following:
If this option is not set, then you cannot specify any credentials.
Type: PSCredential
Position: Named
-ProxyType
Specifies the host name resolution mechanism to use. The acceptable values for this
parameter are:
None, WinHttp, Auto, or InternetExplorer.
Type: ProxyType
Position: Named
-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
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
-SkipRevocationCheck
Indicates that the revocation check for server certificates is skipped. Use this
parameter only for
trusted computers.
Type: SwitchParameter
Position: Named
-UICulture
Specifies the user interface culture to use for the CIM session. Specify the value for
this
parameter using one of the following formats:
Type: CultureInfo
Position: Named
-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
Inputs
None
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
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
PowerShell
7 Note
PowerShell
PowerShell
$action = {
$name = $event.SourceEventArgs.NewEvent.ProcessName
$id = $event.SourceEventArgs.NewEvent.ProcessId
ID = $id"
PowerShell
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
Type: ScriptBlock
Position: 1
-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
-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
-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
Position: Named
-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
-MaxTriggerCount
Type: Int32
Position: Named
-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
-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
-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.
Type: UInt32
Aliases: OT
Position: Named
-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
-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
-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
-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
Inputs
None
Outputs
Object
Related Links
Get-Event
Remove-Event
Unregister-Event
Write-Host
Get-CimSession
New-CimSession
Remove-CimInstance
Reference
Module: CimCmdlets
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:
Examples
PowerShell
PowerShell
notepad.exe
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
-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[]
Position: Named
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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.
Type: CimInstance
Aliases: CimInstance
Position: 1
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
Type: String
Position: 2
-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.
Type: UInt32
Aliases: OT
Position: Named
-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
-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
-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.
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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
None
Outputs
None
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
PowerShell
Get-CimSession | Remove-CimSession
PowerShell
Remove-CimSession -Id 5
PowerShell
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
-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[]
Position: 0
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
Default value: 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.
Type: UInt32[]
Position: 0
-InstanceId
The InstanceId is stored in the InstanceId property of the object that represents a
CIM session.
Type: Guid[]
Position: Named
-Name
Specifies the friendly name of the CIM session to remove. You can use wildcard
characters with this
parameter.
Type: String[]
Position: Named
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
None
Outputs
Object
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 the InputObject parameter is specified, the cmdlet works in one of the following ways:
Examples
PowerShell
PowerShell
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
PowerShell
$x.VariableValue = "Change"
PowerShell
PowerShell
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
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
-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[]
Position: Named
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-InputObject
Type: CimInstance
Aliases: CimInstance
Position: 0
-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
-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.
Type: UInt32
Aliases: OT
Position: Named
-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
-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
-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
-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
-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.
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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Default value: False
Inputs
CimInstance
Outputs
None
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.
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.
Examples
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
pipeline
operator ( | ) sends the snippet files to the Copy-Item cmdlet, which copies
them to the directory
that is specified by the Destination parameter.
PowerShell
#Parse-Snippet Function
function Parse-Snippet {
$SnippetFiles = Get-IseSnippet
$SnippetNamespace =
@{x="http://schemas.microsoft.com/PowerShell/Snippets"}
Write-Host ""
ForEach-Object {$_.Node.InnerXML}
ForEach-Object {$_.Node.InnerText}
Title: Mandatory
Text:
Param
[parameter(Mandatory=True)]
[String[]]
$<ParameterName>
Title: Copyright
PowerShell
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 Format-Table cmdlet displays the DisplayTitle and Description properties of the
snippets in a table.
Inputs
None
Outputs
FileInfo
Related Links
New-IseSnippet
Import-IseSnippet
Import-IseSnippet
Reference
Module: ISE
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
The Get-IseSnippet cmdlet, which gets user-created snippets in the local snippets
directory, does
not get imported snippets.
Examples
PowerShell
PowerShell
PowerShell
($env:PSModulePath).split(";") |
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 {$psise.CurrentPowerShellTab.Snippets.Load($_)}
PowerShell
($env:PSModulePath).split(";") |
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
-Module
Imports snippets from the specified module into the current session. Wildcard
characters are not
supported.
Type: String
Position: Named
-Path
Specifies the path to the snippets directory in which this cmdlet imports snippets.
Type: String
Position: 1
-Recurse
Indicates that this cmdlet imports snippets from all subdirectories of the value of the
Path
parameter.
Type: SwitchParameter
Position: Named
Inputs
None
Outputs
None
Notes
You cannot use the Get-IseSnippet cmdlet to get imported snippets. Get-
IseSnippet gets only
snippets in the $HOME\Documents\WindowsPowerShell\Snippets
directory.
Related Links
Get-IseSnippet
New-IseSnippet
New-IseSnippet
Reference
Module: ISE
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.
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.
.SYNOPSIS
.DESCRIPTION
.PARAMETER <Parameter-Name>
.INPUTS
.OUTPUTS
.EXAMPLE
.LINK
#>"
$M = @'
Param
[parameter(Mandatory=$true)]
[String[]]
$<ParameterName>
'@
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
-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
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
-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
-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
-Title
Specifies a title or name for the snippet. The title also names the snippet file. This
parameter is
required.
Type: String
Position: 1
Inputs
None
Outputs
None
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.
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.
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.
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
PowerShell
$compress = @{
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.
PowerShell
$compress = @{
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 .
PowerShell
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.
PowerShell
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.
PowerShell
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.
PowerShell
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 .
PowerShell
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.
PowerShell
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 .
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.
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.
Type: String
Position: Named
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
Default value: 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
-Force
Type: SwitchParameter
Position: Named
-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
-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.
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
-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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet isn't run.
Type: SwitchParameter
Aliases: wi
Position: Named
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
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
In this example, the LiteralPath parameter is used because the filename contains
characters that
could be interpreted as wildcards.
PowerShell
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-Force
Type: SwitchParameter
Position: Named
-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
-Path
Type: String
Position: 0
Default value: None
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
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.
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.
Out-Default Sends the output to the default formatter and to the default
output cmdlet.
Receive-Job Gets the results of the PowerShell background jobs in the current
session.
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.
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.
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
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
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:
PowerShell
PowerShell
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
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
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.
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 output
Get-Alias returns only one type of object, an AliasInfo object
PowerShell
Get-Alias ac
Output
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.
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
You can now type "syslog" instead of the command. And, you can create aliases
for the
new function.
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 *
The Alias provider exposes the Alias: drive. To go into the Alias: drive,
type:
PowerShell
Set-Location Alias:
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
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
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.
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
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.
PowerShell
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
PowerShell
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
Creating aliases
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.
PowerShell
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}
Changing aliases
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
PowerShell
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
Rename an alias
This command uses the Rename-Item cmdlet to change the popd alias to pop .
PowerShell
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
Deleting an alias
This command deletes the serv alias from the current session.
You can use this
command in any PowerShell drive.
PowerShell
This command deletes aliases that begin with "s". It does not delete read-only
aliases.
PowerShell
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.
Cmdlets supported
New-Item
Set-Item
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
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.
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.
PowerShell
6 + 2 # result = 8
PowerShell
6 - 2 # result = 4
- -6 # result = 6
PowerShell
6 * 2 # result = 12
PowerShell
6 / 2 # result = 3
PowerShell
7 % 2 # result = 1
PowerShell
5 -band 3 # result = 1
PowerShell
-bnot 5 # result = -6
Bitwise OR ( -bor )
PowerShell
5 -bxor 3 # result = 6
PowerShell
PowerShell
Operator precedence
PowerShell processes arithmetic operators in the following order:
1 () Parentheses
PowerShell
3+6/3*4 # result = 11
(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++]
PowerShell
$a = 0
$b = @(1,2)
$c = @(-1,-2)
$tmp = $c[$a]
$a = $a + 1
$b[$a] = $tmp
The following example shows the effect of rounding to the nearest even integer.
PowerShell
You can use the [Math] class to get different rounding behavior.
PowerShell
PS> [int][Math]::Ceiling(5 / 2)
PS> [int][Math]::Floor(5 / 2)
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
PowerShell
PS> "file" + 16
file16
PS> 16 + "file"
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 + $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 + $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
$array2
Output
Hello World
Key : a
Value : 1
Name : a
Key : b
Value : 2
Name : b
PowerShell
$hash1 + 2
Output
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
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
PowerShell
PS> [Decimal]::maxvalue
79228162514264337593543950335
PS> [Decimal]::maxvalue + 1
RuntimeException: Value was either too large or too small for a Decimal.
PowerShell
PS> $intA = 6
PS> $intB = 4
10
PS> $a = "Power"
PS> $b = "Shell"
PS> $a + $b
PowerShell
The following examples show how to use the arithmetic operators in expressions
with
PowerShell commands:
PowerShell
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
Output
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.
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)
1010 (10)
0011 ( 3)
1011 (11)
1010 (10)
0011 ( 3)
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
------------------------- bNOT
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.
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.
-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.
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
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
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
@( ... )
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)
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
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
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
PowerShell
$a = 0..9
$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
$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
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)
Output
$a rank: 1
$a length: 3
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
PowerShell
$a = "red",$true
$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.
PowerShell
$a = 1, 2, 3
$a.Clear()
$a | % { $null -eq $_ }
Output
True
True
True
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(type convertToType)
ForEach(string propertyName)
ForEach(string methodName)
ForEach(scriptblock expression)
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
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
ForEach(string propertyName)
PowerShell
# View the newly set LastAccessTime of all items, and find Unique entries.
Output
ForEach(string methodName)
PowerShell
Output
ONE
TWO
THREE
7 Note
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.
[, 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.
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 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
Output
hi
there
Default
PowerShell
# Get the zip files in the current users profile, sorted by LastAccessTime
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)
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.
PowerShell
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.
PowerShell
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
Output
...
PowerShell
$stopped
Output
...
7 Note
Both ForEach() and Where() methods are intrinsic members. For more
information
about intrinsic members, see about_Instrinsic_Members.
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
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
$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
Zero objects
PowerShell
$a = $null
$a.Count
$a.Length
Output
One object
PowerShell
$a = 4
$a.Count
$a.Length
$a[0]
$a[-1]
Output
By contrast, if you call the type's true indexer using Item(<key>) , the
method throws an
exception when the key doesn't exist.
PowerShell
# No output ($null)
Exception getting "Item": "The given key 'nosuchkey' was not present in the
dictionary."
At line:1 char:1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ 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.LastWriteTime
Output
PowerShell
$files.LastWriteTime = (Get-Date).AddDays(-1)
Output
The property 'LastWriteTime' cannot be found on this object. Verify that the
At line:1 char:1
+ $files.LastWriteTime = (Get-Date).AddDays(-1)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ FullyQualifiedErrorId : PropertyAssignmentException
PowerShell
$files.set_LastWriteTime((Get-Date).AddDays(-1))
$files.LastWriteTime
Output
PowerShell
$files | Get-Member | Where-Object Definition -like '*set;*'
Output
TypeName: System.IO.FileInfo
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:
The increment and decrement operators are unary operators. Each has prefix and
postfix
versions.
<assignable-expression><operator>
<operator><assignable-expression>
PowerShell
$MyShell = "PowerShell"
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
You can also assign the value created by a statement to a variable, as in the
following
example:
PowerShell
PowerShell
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
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
$a = 10kb
) Important
PowerShell
$x = 1 # Global scope
& { $x += 1; $x }
Output
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
+ ~~~~~~~
+ FullyQualifiedErrorId : AddHashTableToNonHashTable
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
PowerShell
$a = 1,2,3
$a
Output
PowerShell
$a[1] = $null
$a
Output
Remove-Variable -Name a
PowerShell
$a = 3
$a *= 4
$a
Output
12
PowerShell
$a *= 2
$a = ($a * 2)
PowerShell
$a = "file"
$a *= 4
$a
Output
filefilefilefile
PowerShell
$a[0] *= 2
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 %= 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
PowerShell
$a = 7
++$a
$a
Output
PowerShell
$a = 7
(++$a)
Output
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
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
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
PowerShell
$a = "6"
$a.GetType().FullName
Output
System.String
PowerShell
$a = "file"
$a += 3
$a
Output
file3
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
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
At line:4 char:1
+ $a = "string"
+ ~~~~~~~~~~~~~
+ FullyQualifiedErrorId : RuntimeException
PowerShell
[string]$a = "string"
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
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"
Output
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.
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
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.
$$
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() .
PowerShell
function Test-WriteError
Write-Error "Bad"
Test-WriteError
Output
Test-WriteError : Bad
At line:7 char:1
+ Test-WriteError
+ ~~~~~~~~~~~~~~~
+ FullyQualifiedErrorId :
Microsoft.PowerShell.Commands.WriteErrorException,Test-WriteError
7 Note
$^
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.
$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.
$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 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.
Enumerators contain properties and methods you can use to retrieve loop values
and
change the current loop iteration. For more information, see
Using Enumerators.
CMD
$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:
$LASTEXITCODE is set to value the specified by the exit keyword. For more
to $true
$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
$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.
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.
$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
PowerShell
$a.count
Output
PowerShell
Output
Hello one
Hello
Hello three
PowerShell
$days = "Sunday","Monday","Tuesday","Wednesday","Thursday",
"Friday","Saturday"
$currentDay = 0
foreach($day in $calendar)
$currentDay++
Output
$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
PowerShell
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.
PowerShell
function Test1 {
param($a, $b)
$PSBoundParameters
function Test2 {
param($a, $b)
Test1 @PSBoundParameters
PowerShell
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.
$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
$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.
$PSScriptRoot
Contains the full path of the executing script's parent directory.
$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.
$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:
$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
TypeName : System.IO.FileInfo
Name : BaseName
MemberType : ScriptProperty
{$this.Name.Remove($this.Name.Length - $this.Extension.Length
)}else{$this.Name};}
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 functions that accept pipeline input, it's best practice to use
parameters
with the ValueFromPipeline or
ValueFromPipelineByPropertyName attributes.
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
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.
Examples
PowerShell
function Test
begin
$i = 0
process
"Iteration: $i"
$i++
"`tInput: $input"
$input.Reset()
"one","two" | Test
Output
Iteration: 0
Input: one
Access Again:
Iteration: 1
Input: two
Access Again:
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
PowerShell
Function All
$input.Reset()
$input.MoveNext() | Out-Null
"one","two","three" | All
Output
Access Again:
After MoveNext:
function Current
begin
$i = 0
process
"Iteration: $i"
$i++
$input.MoveNext() | Out-Null
"one","two" | Current
Output
Iteration: 0
Before MoveNext:
Iteration: 1
Before MoveNext:
7 Note
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
"Iteration: $i"
$i++
"`tNum: $num"
"`tCurrent: $($foreach.Current)"
$foreach.MoveNext() | Out-Null
Output
Iteration: 0
Num: one
Current: one
Iteration: 1
Num: two
Current: 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
PowerShell
$stopLoop = 0
$foreach.Reset() | Out-Null
$stopLoop++
Output
Current: one
Current: two
Reset Loop: 0
Current: one
Current: two
Reset Loop: 1
Current: one
Current: two
Current: three
7 Note
Note how the NotEvaluated case is never executed, even though there's
no break
statement after the MoveNext method.
PowerShell
$stopInfinite = $false
switch ($values)
"MoveNext" {
"`tMoveNext"
$switch.MoveNext() | Out-Null
"NotEvaluated" {
"`tAfterMoveNext: $($switch.Current)"
"Reset" {
if (!$stopInfinite)
"`tReset"
$switch.Reset()
$stopInfinite = $true
default {
Output
MoveNext
Reset
MoveNext
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.
Examples:
PowerShell
True
False
False
False
False
Non-empty strings
Instances of any other non-collection type
Examples:
PowerShell
# a non-collection type
PS> [bool]@{value = 0}
True
# non-empty strings
True
PS> [bool]'False'
True
PowerShell
PS> [bool]::Parse('false')
False
PS> [bool]::Parse('True')
True
Examples:
PowerShell
# Empty collections
PS> [bool]@()
False
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.
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
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.
PowerShell
$i=0
$varB = 10,20,30,40
break
$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.
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
if (<condition 2>) {
break myLabel
You can nest many labeled loops, as shown in the following example.
PowerShell
:red while (<condition1>) {
while (<condition3>) {
if ($a) {break}
PowerShell does not limit how far labels can resume execution. The label can
even pass
control across script and function call boundaries.
The break keyword is used to leave the switch construct. For example, the
following
switch statement uses break statements to test for the most
specific condition:
PowerShell
$var = "word2"
"word2" {
Write-Host "Exact" $_
break
"word.*" {
break
"w.*" {
default {
break
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.
PowerShell
function test {
trap [DivideByZeroException] {
break
$i = 3
'Before loop'
while ($true) {
'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
At line:10 char:6
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ FullyQualifiedErrorId : RuntimeException
This means that functions and scripts that inadvertently use a break outside
of an
enclosing construct that supports it can inadvertently terminate their
callers.
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.
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
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
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
Sort-Object
expression
ascending / descending - optional
7 Note
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
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
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
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'
} |
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
PowerShell
Output
class DateTime
$_.Date =
class DateTime
DayOfWeek = Friday
DayOfYear = 220
Hour = 0
Kind = Local
Millisecond = 0
Minute = 0
Month = 8
Second = 0
Ticks = 637323552000000000
TimeOfDay = 00:00:00
Year = 2020
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
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 |
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 |
Output
.openpublishing.publish.config.json (2.25kb)
.openpublishing.redirection.json (324.60kb)
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 |
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
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 |
Output
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
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
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.
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 .
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.
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.
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.
(usually ANSI).
Oem Uses the encoding that corresponds to the system's current OEM code
page.
7 Note
Out-File and the redirection operators > and >> create UTF-16LE, which
notably
differs from Set-Content and Add-Content .
Export-Csv creates Ascii files but uses different encoding when using
Append
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.
ANSI is also what the PowerShell engine uses when it reads source
code from files.
BOM.
ascii : Uses the encoding for the ASCII (7-bit) character set.
bigendianunicode : Encodes in UTF-16 format using the big-endian byte order.
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.
$PSDefaultParameterValues
$OutputEncoding
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
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.
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.
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.
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.
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-name>([<constructor-argument-list>])
{<constructor-statement-list>} ...]
syntax
[-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.
PowerShell
class Device {
[string]$Brand
$dev = [Device]::new()
$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.Model = "Fbk5040"
$device.VendorSku = "5072641000"
$device
Output
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 :
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.
PowerShell
class Device {
[string]$Brand
[string]$Model
[string]$VendorSku
[string]ToString(){
class Rack {
[int]$Slots = 8
[string]$Brand
[string]$Model
[string]$VendorSku
[string]$AssetId
[Device[]]$Devices = [Device[]]::new($this.Slots)
$this.Devices[$slot] = $dev
[void]RemoveDevice([int]$slot){
$this.Devices[$slot] = $null
[int[]] GetAvailableSlots(){
[int]$i = 0
$rack = [Rack]::new()
$device = [Device]::new()
$device.Model = "Fbk5040"
$device.VendorSku = "5072641000"
$rack.AddDevice($device, 2)
$rack
$rack.GetAvailableSlots()
Output
Slots : 8
Brand :
Model :
VendorSku :
AssetId :
7 Note
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(){
[void] GetEvenIntegers(){
[string]SayHello(){
"Good Morning"
$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.
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
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
Undefined
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.
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 {
[string]$Brand
[string]$Model
[Device[]]$Devices = [Device[]]::new($this.Slots)
$this.Brand = $b
$this.Model = $m
$this.Slots = $capacity
$this.Devices = [Device[]]::new($this.Slots)
$r1
$r1.Devices.Length
$r1.Slots
Output
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.
PowerShell
class Device {
[string]$Brand
[string]$Model
class Rack {
[string]$Brand
[string]$Model
[string]$AssetId
[Device[]]$Devices = [Device[]]::new($this.Slots)
$this.Brand = $b
$this.Model = $m
$this.AssetId = $id
$this.Slots = $capacity
$this.Devices = [Device[]]::new($this.Slots)
[Rack]::InstalledRacks += $this
static [void]PowerOffRacks(){
foreach ($rack in [Rack]::InstalledRacks) {
PS> [Rack]::InstalledRacks.Length
0
PS> [Rack]::PowerOffRacks()
PS> [Rack]::InstalledRacks.Length
10
PS> [Rack]::InstalledRacks[3]
PS> [Rack]::PowerOffRacks()
Notice that the number of racks increases each time you run this example.
class Device {
[ValidateNotNullOrEmpty()][string]$Brand
[ValidateNotNullOrEmpty()][string]$Model
[Device]$dev = [Device]::new()
$dev
$dev.Brand = ""
Output
Testing dev
Brand Model
----- -----
argument that is not null or empty, and then try the command again."
At C:\tmp\Untitled-5.ps1:11 char:1
+ $dev.Brand = ""
+ ~~~~~~~~~~~~~~~
+ FullyQualifiedErrorId : ExceptionWhenSetting
PowerShell does not support multiple inheritance. Classes cannot inherit from
more than
one class. However, you can use interfaces for that purpose.
PowerShell
This example shows inheritance with an interface declaration coming after the
base
class.
PowerShell
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
[string]$Status
[DeviceType] GetDeviceType(){
return $this.devtype
[string]$ProcessorIdentifier
[string]$Hostname
hidden [int]$Slots = 8
[string]$Datacenter
[string]$Location
[Device[]]$Devices = [Device[]]::new($this.Slots)
Rack (){
Rack ([int]$s){
$this.Devices = [Device[]]::new($s)
$this.Devices[$slot] = $dev
[void] RemoveDevice([int]$slot){
$this.Devices[$slot] = $null
$FirstRack = [Rack]::new(16)
$FirstRack.Status = "Operational"
$FirstRack.Datacenter = "PNW"
$FirstRack.Location = "F03R02.J10"
(0..15).ForEach({
$ComputeServer = [ComputeServer]::new()
$FirstRack.AddDevice($ComputeServer, $_)
})
$FirstRack
$FirstRack.Devices
Output
Datacenter : PNW
Location : F03R02.J10
Status : Operational
Brand :
Model :
ProcessorIdentifier : x64
Hostname : r1s000
Status : Installed
Model : Fbk5040
ProcessorIdentifier : x64
Hostname : r1s001
Status : Installed
Model : Fbk5040
ProcessorIdentifier : x64
Hostname : r1s015
Status : Installed
Model : Fbk5040
PowerShell
class Person {
[int]$Age
Person([int]$a)
$this.Age = $a
[string]$School
$this.School = $s
$littleOne.Age
Output
10
PowerShell
class BaseClass
[int]days() {return 1}
[int]days () {return 2}
[ChildClass1]::new().days()
Output
PowerShell
class BaseClass
[int]days() {return 1}
[int]days () {return 2}
[ChildClass1]::new().days()
[ChildClass1]::new().basedays()
Output
PowerShell
return 0;
return 0;
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.
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.
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
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.
PowerShell
Get-Command Get-Date
Output
Function Get-Date
PowerShell
Output
Function Get-Date
PowerShell
Output
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
Microsoft.PowerShell.Utility\Get-Date
Output
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
PowerShell
(Get-Command Get-Date).ModuleName
Output
Microsoft.PowerShell.Utility
7 Note
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
or
PowerShell
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)
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.
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.
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
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.
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
PowerShell
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.
For example, to use the Name parameter of New-Alias , you type the following:
PowerShell
-Name
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
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.
PowerShell
[<CommonParameters>]
[<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 .
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.
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
PowerShell
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
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
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
The following commands correctly use the New-Alias cmdlet. The commands
produce
the same result.
PowerShell
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.
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
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.
# .<help keyword>
# <help content>
or
<#
.<help keyword>
<help content>
#>
<#
.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.
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 { }
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>
#>
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>
...
.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.
PowerShell
<#
.SYNOPSIS
#>
function Verb-Noun {
[CmdletBinding()]
param (
[string]$Computername
.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.
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
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
<ScriptModule.psm1>-help.xml
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
PowerShell
function Add-Extension
$name
<#
.SYNOPSIS
.DESCRIPTION
.PARAMETER Name
.PARAMETER Extension
.INPUTS
.OUTPUTS
or file name.
.EXAMPLE
File.txt
.EXAMPLE
File.doc
.EXAMPLE
File.doc
.LINK
http://www.fabrikam.com/extension.html
.LINK
Set-Item
#>
PowerShell
Output
NAME
Add-Extension
SYNOPSIS
SYNTAX
[<CommonParameters>]
DESCRIPTION
Adds a file name extension to a supplied name. Takes any strings for the
PARAMETERS
-Name
Required? false
Position? 0
Default value
-Extension
Required? false
Position? 1
Default value
<CommonParameters>
"get-help about_commonparameters".
INPUTS
OUTPUTS
file name.
Example 1
File.txt
Example 2
File.doc
Example 3
File.doc
RELATED LINKS
http://www.fabrikam.com/extension.html
Set-Item
PowerShell
function Add-Extension
param
[string]
$name,
[string]
$extension = "txt"
$name
<#
.SYNOPSIS
.DESCRIPTION
Adds a file name extension to a supplied name. Takes any strings for the
.INPUTS
.OUTPUTS
file name.
.EXAMPLE
File.txt
.EXAMPLE
File.doc
.EXAMPLE
File.doc
.LINK
http://www.fabrikam.com/extension.html
.LINK
Set-Item
#>
PowerShell
<#
.SYNOPSIS
.DESCRIPTION
The Update-Month.ps1 script updates the registry with new data generated
.PARAMETER InputPath
.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
.INPUTS
.OUTPUTS
.EXAMPLE
PS> .\Update-Month.ps1
.EXAMPLE
.EXAMPLE
C:\Reports\2009\January.csv
#>
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
Output
# NAME
C:\ps-test\Update-Month.ps1
# SYNOPSIS
# SYNTAX
<String>] [<CommonParameters>]
# DESCRIPTION
# PARAMETERS
-InputPath
Required? true
Position? 0
Default value
-OutputPath
Specifies the name and path for the CSV-based output file. By
and time it runs, and saves the output in the local directory.
Required? false
Position? 1
Default value
<CommonParameters>
"get-help about_commonparameters".
# INPUTS
# OUTPUTS
Example 1
PS> .\Update-Month.ps1
Example 2
Example 3
C:\Reports\2009\January.csv
# RELATED LINKS
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
function Get-Data { }
...
PowerShell
function Add-Extension
# .ExternalHelp C:\ps-test\Add-Extension.xml
$name
PowerShell
function Add-Extension
$name
# .ExternalHelp C:\ps-test\Add-Extension.xml
PowerShell
# .ExternalHelp C:\ps-test\Add-Extension.xml
function Add-Extension
$name
PowerShell
function help
<#
.FORWARDHELPTARGETNAME Get-Help
.FORWARDHELPCATEGORY Cmdlet
#>
[CmdletBinding(DefaultParameterSetName='AllUsersView')]
param(
[Parameter(Position=0, ValueFromPipelineByPropertyName=$true)]
[System.String]
${Name},
...
PowerShell
Output
NAME
Get-Help
SYNOPSIS
...
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.
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.
WhatIf (wi)
Confirm (cf)
-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
$DebugPreference to Continue.
-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
Required: False
Position: Named
the command.
-ErrorAction:Stop displays the error message and stops executing the command.
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
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
PowerShell
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.
YAML
Type: ActionPreference
Aliases: ia
Required: False
Position: Named
Information command.
7 Note
-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
YAML
Type: String
Aliases: iv
Required: False
Position: Named
-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
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 .
PowerShell
1..4 | ForEach-Object {
} -OutBuffer 1 | ForEach-Object {
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
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
The following command adds the process object to the $out variable:
PowerShell
$out
7 Note
-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.
7 Note
YAML
Type: String
Aliases: pv
Required: False
Position: Named
Valid values are strings, the same as for any variable names.
U Caution
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 results of the first Foreach-Object command are piped into a second
Foreach-
Object command, which displays the current values of $temp and
$_ .
PowerShell
$temp=8
Get-Variable temp
Write-Host "Step1[BEGIN]:`$temp=$temp"
} -Process {
Write-Output $_
} | ForEach-Object {
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
At line:1 char:1
+ Get-Variable temp
+ ~~~~~~~~~~~~~~~~~
+ 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
-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
Required: False
Position: Named
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
All generated warnings are saved in the variable even if the warnings aren't
displayed to
the user.
For example, the following command creates the $a variable and then stores any
warnings in it:
PowerShell
PowerShell
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
-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
-WhatIf:$false suppresses the automatic WhatIf behavior that results when the
value of
PowerShell
Output
Target "C:\ps-test\date.csv".
-Confirm
Prompts you for confirmation before executing the command.
YAML
Type: SwitchParameter
Aliases: cf
Required: False
Position: Named
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.
Confirm
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend
Response Result
Yes to All ( A ) Perform all actions and suppress subsequent Confirm queries
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.
Confirm
C:\ps-test\test.txt".
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default
is "Y"): s
-ItemType <string>
Required? false
Position? named
Default value
PS C:\ps-test> exit
Confirm
.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
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
Matching
Replacement
Containment
Type
-is - both objects are 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 .
PowerShell
$a = (1, 2) -eq 3
$a.GetType().Name
$a.Count
Output
Object[]
Equality operators
Example:
PowerShell
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
PowerShell
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.
True
PowerShell
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 -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
[String]$File
[Int64]$Size
$a -eq $b
Output
True
PowerShell
$a = 1, 2, $null, 4, $null, 6
PowerShell
$null -ne $a
Output
True
PowerShell
Output
PowerShell
7 Note
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
$a
$a -gt 7
$a -ge 7
$a -lt 7
$a -le 7
Output
Test collection:
Examples:
PowerShell
# Date comparison
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).
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.
Example:
PowerShell
"PowerShell" -like "*shell" # Output: True
Scalar examples:
PowerShell
# Partial match test, showing how differently -match and -like behave
If the input is a collection, the operators return the matching members of that
collection.
Collection examples:
PowerShell
# Output: PowerShell
-match and -notmatch support regex capture groups. Each time they run on
scalar
It's important to note that the $Matches hashtable contains only the first
occurrence of
any matching pattern.
Example:
PowerShell
$Matches
$Matches.domain
$Matches.user
Output
True
Name Value
---- -----
domain CONTOSO
user jsmith
0 was CONTOSO\jsmith
Domain name:
CONTOSO
User name:
jsmith
Example:
PowerShell
$Matches
Replacement operator
Syntax:
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
Examples:
PowerShell
Output
Cook
book
PowerShell
$SearchExp = '^(?<DomainName>[\w-.]+)\\(?<Username>[\w-.]+)$'
$ReplaceExp = '${Username}@${DomainName}'
Output
2 Warning
For example:
PowerShell
$1 = 'Goodbye'
PowerShell
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
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:
Examples:
PowerShell
PowerShell
$DomainServers = "ContosoDC1","ContosoDC2","ContosoFileServer","ContosoDNS",
"ContosoDHCP","ContosoWSUS"
$thisComputer = "ContosoDC2"
# Output: True
$a = "abc", "def"
PowerShell
PowerShell
$DomainServers = "ContosoDC1","ContosoDC2","ContosoFileServer","ContosoDNS",
"ContosoDHCP","ContosoWSUS"
$thisComputer = "ContosoDC2"
# Output: True
$a = "abc", "def"
Type comparison
The type comparison operators ( -is and -isnot ) are used to determine if an
object is a
specific type.
Syntax:
PowerShell
Example:
PowerShell
$a = 1
$b = "1"
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.
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
$ctr += 1
if ($ctr -eq 5)
continue
Write-Host -Object $i
if ($i -eq 5)
continue
$i--
PowerShell
if ($condition) {
continue labelB
} else {
$condition = Update-Condition
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
switch (1,2,3) {
default { $_ }
Output
This means that functions and scripts that inadvertently use a continue
outside of an
enclosing construct that supports it, can inadvertently terminate
their callers.
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
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.
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.
can be used.
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.
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.
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.
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:
<Permitted content>
Comments
Pipelines
PowerShell
1,2,3
"PowerShell 2.0"
[XML] @'
'@
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.
PowerShell
PowerShell
$TextMsgs = DATA {
Text001 = Windows 7
'@
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 {
Text001 = Windows 7
'@
$TextMsgs
Output
Name Value
---- -----
Text001 Windows 7
Examples
Simple data strings.
PowerShell
DATA {
PowerShell
DATA {
if ($null) {
PowerShell
DATA {
Text001 = Windows 7
'@
PowerShell
DATA {
"@
PowerShell
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
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.
When you reach a breakpoint, execution stops, and control is turned over to the
debugger.
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.
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.
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.
<Enter> : Repeats the last command if it was Step (s), StepOver (v), or
List (l).
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.
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
PowerShell
$scriptname = $MyInvocation.PSCommandPath
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.
For example:
PowerShell
You can use the value of the $PSDebugContext variable in your debugging.
= {} {} C:\ps-test\vote.ps1 (1)
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
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.
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.
PowerShell
0 TestWFDemo1.ps1 8
PS C:> C:\TestWFDemo1.ps1
At C:\TestWFDemo1.ps1:8 char:5
# ~~~~~
# 3:
4: workflow SampleWorkflowTest
5: {
6: param ($MyOutput)
# 7:
# 10:
# 13:
15: }
# 16:
Hello
At C:\TestWFDemo1.ps1:9 char:5
# +!INCLUDE[]~
4: workflow SampleWorkflowTest
5: {
6: param ($MyOutput)
# 7:
# 10:
# 13:
15: }
# 16:
# 19:
Hello
At C:\TestWFDemo1.ps1:11 char:5
# +!INCLUDE[]~~~~~~~~~
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> test-cmdlet
Begin
test-cmdlet
[DBG]: C:\PS> c
Process
test-cmdlet
[DBG]: C:\PS> c
End
test-cmdlet
# [DBG]: C:\PS>
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
0 ttest19.ps1 6
1 ttest19.ps1 11
2 ttest19.ps1 22
3 ttest19.ps1 25
At C:\psscripts\ttest19.ps1:11 char:1
+ $winRMName = "WinRM"
# + ~
7: }
# 8:
9: $count = 10
# 13:
15: {
16: sleep 1
# 19:
20: hello2day
# 21:
At C:\psscripts\ttest19.ps1:12 char:1
+ $myVar = 102
# + ~
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 {
if ($PSVersionTable.PSVersion.Major -lt 6) {
else {
$scriptName = $MyInvocation.PSCommandPath
psversion
"Done $scriptName."
Start by creating a line breakpoint on the first line of the Test.ps1 script in
the current
directory.
PowerShell
PowerShell
Column : 0
Line : 1
Action :
Enabled : True
HitCount : 0
Id : 0
Script : C:\ps-test\test.ps1
ScriptName : C:\ps-test\test.ps1
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
# 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
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
PowerShell
DBG> o
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
PowerShell
PowerShell
PowerShell
PowerShell
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
(Write access)
# DBG>
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
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>
PowerShell
PowerShell
PowerShell
PowerShell
PS C:\ps-test> .\test.ps1
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
PowerShell
DBG> c
Done C:\ps-test\test.ps1
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
-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
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.
PowerShell
PS C:\ps-test> .\test.ps1
test.ps1:12 psversion
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
PowerShell
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.
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 {
Node $MachineName
WindowsFeature IIS
Ensure = "Present"
# You can use the File resource to create files and folders
File WebDirectory
Recurse = $true
SourcePath = $WebsiteFilePath
DestinationPath = "C:\inetpub\wwwroot"
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
# 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
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
Name Properties
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
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.
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
PowerShell
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> $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> $count
The following example writes all the values of an array, skipping any value
that is less
than zero.
PowerShell
do {
Write-Host $x[$a]
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.
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
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 {
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
<label 0> [= 1]
<label 1> [= 2]
<label 2> [= 4]
<label 3> [= 8]
...
PowerShell
Archive = 1
Compressed = 2
Device = 4
Directory = 8
Encrypted = 16
Hidden = 32
[FileAttributes]$file1 = [FileAttributes]::Archive
[FileAttributes]$file1 +=[FileAttributes]::Compressed
[FileAttributes]$file1 += [FileAttributes]::Device
Output
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
True
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
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.
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.
PowerShell
The Environment provider has no containers, so the above command has the
same
effect when used with Get-ChildItem .
PowerShell
PowerShell
PowerShell
$env:windir
PowerShell
PowerShell
PowerShell
PowerShell
PowerShell
PowerShell
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
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.
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.
$Env:<variable-name>
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>"
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
$Env:Foo += '!'
$Env:Foo
Output
An example!
PowerShell
$Env:Foo = ''
Output
At line:1 char:12
+ $env:foo | Get-Member
+ ~~~~~~~~~~
+ FullyQualifiedErrorId :
NoObjectInGetMember,Microsoft.PowerShell.Commands.GetMemberCommand
PowerShell
Output
TypeName: System.String
For example, to create the Foo environment variable with a value of Bar :
PowerShell
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
Output
Name Value
---- -----
Foo2 Bar
Name Value
---- -----
Foo2 BAR
Foo Bar
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
PowerShell
[Environment]::SetEnvironmentVariable('Foo','')
[Environment]::GetEnvironmentVariable('Foo')
Output
For more information about the methods of the System.Environment class, see
Environment Methods.
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.
For example, to save a new environment variable Foo with the value Bar to
the machine
scope:
PowerShell
You can delete an environment variable from the user or machine scope by
setting the
variable's value to an empty string.
PowerShell
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.
PSModulePath
scope is $env:ProgramFiles\PowerShell\Modules .
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.
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
$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
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 .
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
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 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 .
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
Or, type:
PowerShell
Sort-Object EventID |
Group-Object EventID
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 |
Format-List -Property *
PowerShell
Variable Description
$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.
PowerShell
Import-Module <ModuleName>
$m = Get-Module <ModuleName>
$m.LogPipelineExecutionDetails = $true
PowerShell
$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.
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.
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
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.
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.
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
Output
Scope ExecutionPolicy
----- ---------------
MachinePolicy Undefined
UserPolicy Undefined
Process Undefined
CurrentUser RemoteSigned
LocalMachine AllSigned
For example, the following command gets the execution policy for the
CurrentUser
scope:
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
PowerShell
For example:
PowerShell
For example:
PowerShell
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.
For example, to remove the execution policy for all the users of the local
computer:
PowerShell
PowerShell
For example:
PowerShell
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
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.
Policies set in the Computer Configuration node take precedence over policies
set in the
User Configuration node.
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.
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
Output
At line:1 char:1
+ C:\scriptpath\scriptname.ps1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ FullyQualifiedErrorId : UnauthorizedAccess
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.
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 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
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 .
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 .
PowerShell
Get-ChildItem
The following command copies all of the files and directories under the path
C:\temp\
to the folder C:\Windows\Temp .
PowerShell
This command copies the a.txt file from the C:\a directory to the C:\a\bb
directory.
PowerShell
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
PowerShell
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.
At line:1 char:1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ FullyQualifiedErrorId :
InvalidOperation,Microsoft.PowerShell.Commands.MoveItemCommand
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
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}
PowerShell
PowerShell
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.
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 .
PowerShell
$e[0]
PowerShell
For more information about this object, pipe the command to the
Get-Member cmdlet
or see the FileSecurity Class.
Create a directory
This command creates the logfiles directory on the C drive:
PowerShell
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
PowerShell
New-Item -Path c:\logfiles -Name log2.txt -Type file -Value "test log"
Rename a file
This command renames the a.txt file in the C:\a directory to b.txt :
PowerShell
Rename a directory
This command renames the C:\a\cc directory to C:\a\dd :
PowerShell
Delete a file
This command deletes the Test.txt file in the current directory:
PowerShell
PowerShell
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.
PowerShell
Get-Service | Export-Csv -Path services.csv
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
PowerShell
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.
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 .
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.
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
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.
! - 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).
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.
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.
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).
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).
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 .
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 .
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.
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
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.
<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.
PowerShell
"`$i:$i"
"`$j:$j"
"`$i:$i"
"`$j:$j"
The following syntaxes are supported for multiple assignment operations in the
Repeat
statement:
PowerShell
"`$i:$i"
"`$j:$j"
"`$i:$i"
"`$j:$j"
"`$i:$i"
"`$j:$j"
7 Note
Operations other than pre or post increment may not work with all syntaxes.
PowerShell
for (($i = 0), ($j = 0); $i -lt 10 -and $j -lt 10; $i++,$j++)
"`$i:$i"
"`$j:$j"
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
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
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
Write-Host $i
The For loop can also be written on one line as in the following example.
PowerShell
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.
Syntax
The following shows the foreach syntax:
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"
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
PowerShell
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
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)
Write-Host $file
Write-Host $file.length
Write-Host $file.lastaccesstime
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
$i = $i + 1
if ($i -ne 0) {
Write-Host
else {
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
PowerShell
function Get-FunctionPosition {
[CmdletBinding()]
[OutputType('FunctionPosition')]
param(
[Parameter(Position = 0, Mandatory,
ValueFromPipeline, ValueFromPipelineByPropertyName)]
[ValidateNotNullOrEmpty()]
[Alias('PSPath')]
[System.String[]]
$Path
process {
try {
$_
} else {
$parser = [System.Management.Automation.Language.Parser]
Write-Verbose "$item"
if ($item.PSIsContainer -or
continue
$parser::ParseFile($item.FullName, ([REF]$tokens),
([REF]$errors)) | Out-Null
if ($errors) {
$errors.Count
Write-Warning $msg
continue
$position = $token.Extent.StartLineNumber
do {
if (-not $foreach.MoveNext()) {
break tokenLoop
$token = $foreach.Current
$functionPosition = [pscustomobject]@{
Name = $token.Text
LineNumber = $position
Path = $item.FullName
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.
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
2. DotNetTypes.Format.ps1xml
3. FileSystem.Format.ps1xml
Help views, such as detailed and full views, parameters, and examples.
5. PowerShellCore.Format.ps1xml
6. PowerShellTrace.Format.ps1xml
7. Registry.Format.ps1xml
Table
List
Wide
Custom
When a formatting file includes more than one view of an object, PowerShell
applies the
first view that it finds.
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.
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>
PowerShell
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.
XML
<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
<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
To test the change, type Get-Culture and review the output that includes the
Calendar
property.
PowerShell
Get-Culture
Output
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
7 Note
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
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.
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
<DefaultDisplayProperty>
<DefaultDisplayPropertySet>
<DefaultKeyPropertySet>
parameter:
FormatFileLoading
FormatViewBinding
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
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
<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.
PowerShell
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.
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
Syntax
The following are the syntax for a function:
Syntax
Syntax
function [<scope:>]<name>
param([type]$parameter1 [,[type]$parameter2])
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
For example, the following function starts PowerShell with the Run as
Administrator
option.
PowerShell
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
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.
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> {
<statement list>
You can also define parameters outside the braces without the Param keyword,
as shown
in the following sample syntax:
Syntax
<statement list>
PowerShell
$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.
PowerShell
function Get-SmallFiles {
Param($Size)
In the function, you can use the $Size variable, which is the name defined for
the
parameter.
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
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
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] .
PowerShell
function Get-Extension {
$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)
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
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
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
The @Args feature uses the $Args automatic parameter, which represents
undeclared
cmdlet parameters and values from remaining arguments.
Syntax
function <name> {
) 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,
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
1,2,4 | Get-Pipeline
Output
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
PowerShell
1,2,4 | Get-PipelineBeginEnd
Output
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.
PowerShell
function Get-PipelineInput
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
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 following filter takes log entries from the pipeline and then displays
either the
whole entry or only the message portion of the entry:
PowerShell
else { $_ }
PowerShell
Function Scope
A function exists in the scope in which it's created.
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 {
When a function is in the global scope, you can use the function in scripts,
in functions,
and at the command line.
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
PowerShell
$function:help
For more information about the Function: drive, see the help topic for the
Function
provider. Type Get-Help Function .
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.
PowerShell
Get-Help Get-MyDisks
You can write help for a function using either of the two following methods:
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.
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#.
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
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.
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:
All the methods and properties of the PSCmdlet class are available to
advanced
functions. For more information, see
System.Management.Automation.PSCmdlet.
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.
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
end
Confirmation methods
ShouldProcess
This method is called to request confirmation from the user before the function
performs an action that would change the system. The function can continue
based on
the Boolean value returned by the method. This method can 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).
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
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
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
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.
PowerShell
Add-Type @'
using System;
using System.Management.Automation;
[Cmdlet("Get", "Date_Cmdlet")]
[Parameter(Position=0)]
WriteObject(Date);
[cultureinfo]::CurrentCulture = 'de-DE'
$dateStr = '19-06-2018'
Get-Date_Cmdlet $dateStr
Output
PowerShell
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.
$dateStr = '19-06-2018'
Get-Date_Func $dateStr
Output
DateTime."
At line:13 char:15
+ Get-Date_Func $dateStr
+ ~~~~~~~~
+ 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.
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, 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 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.
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 .
dynamicparam {<statement-list>}
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(
$paramDictionary =
[System.Management.Automation.RuntimeDefinedParameterDictionary]::new()
$paramDictionary.Add('KeyCount', $dynParam1)
return $paramDictionary
Attributes of parameters
This section describes the attributes that you can add to function parameters.
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.
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
PowerShell
Param(
[Parameter(Mandatory=$true)]
Param(
[Parameter(Mandatory)]
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.
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.
PositionalBinding in
about_Functions_CmdletBindingAttribute.
PowerShell
Param(
[Parameter(Position=0)]
[string[]]
$ComputerName
ParameterSetName argument
7 Note
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.
PowerShell
Param(
[Parameter(Mandatory,
ParameterSetName="Computer")]
[string[]]
$ComputerName,
[Parameter(Mandatory,
ParameterSetName="User")]
[string[]]
$UserName,
[Parameter(ParameterSetName="Computer")]
[Parameter(Mandatory, ParameterSetName="User")]
[switch]
$Summary
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.
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.
PowerShell
Param(
[Parameter(Mandatory,
ValueFromPipelineByPropertyName)]
[string[]]
$ComputerName
PowerShell
function Test-ValueFromPipelineByPropertyName{
param(
[Parameter(Mandatory, ValueFromPipelineByPropertyName)]
[string[]]
$ComputerName
Test-ValueFromPipelineByPropertyName
Output
7 Note
ValueFromRemainingArguments argument
PowerShell
function Test-Remainder
param(
[string]
[Parameter(Mandatory, Position=0)]
$Value,
[string[]]
[Parameter(Position=1, ValueFromRemainingArguments)]
$Remaining)
"${i}: $($Remaining[$i])"
Output
Found 1 elements
0: one two
7 Note
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 .
PowerShell
Param(
[Parameter(Mandatory,
[string[]]
$ComputerName
Example output:
Output
ComputerName[0]: !?
ComputerName[0]: localhost
ComputerName[1]:
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.
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]
Output
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
At line:1 char:1
+ [string][ValidateLength(1,5)]$TicketIDFromInt = 43
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Exception
+ FullyQualifiedErrorId : ValidateSetFailure
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.
PowerShell
Param(
[Parameter(Mandatory)]
[AllowEmptyString()]
[string]
$ComputerName
PowerShell
Param(
[Parameter(Mandatory)]
[AllowEmptyCollection()]
[string[]]
$ComputerName
Param(
[Parameter(Mandatory)]
[ValidateCount(1,5)]
[string[]]
$ComputerName
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
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
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
PowerShell
Param(
[Parameter(Mandatory)]
[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
7 Note
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)]
[string[]]
$Detail
In the following example, the value of the variable $flavor must be either
Chocolate,
Strawberry, or Vanilla.
PowerShell
[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"
Output
The attribute cannot be added because variable Message with value bye would
no
longer be valid.
At line:1 char:1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ FullyQualifiedErrorId : ValidateSetFailure
Using ValidateSet also enable tab expansion of values for that parameter. For
more
information, see about_Tab_Expansion.
PowerShell
Class SoundNames : System.Management.Automation.IValidateSetValuesGenerator
{
[string[]] GetValidValues() {
$SoundPaths = '/System/Library/Sounds/',
'/Library/Sounds','~/Library/Sounds'
If (Test-Path $SoundPath) {
(Get-ChildItem $SoundPath).BaseName
PowerShell
Param(
[ValidateSet([SoundNames])]
[string]$Sound
7 Note
PowerShell
Param(
[Parameter()]
[ValidateNotNull()]
$ID
$null
PowerShell
Param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string[]]
$UserName
If you use relative path, the current drive must be in the allowed drive list.
PowerShell
Param(
[string]$Path
PowerShell
function Test-UserDrivePath{
[OutputType([bool])]
Param(
[Parameter(Mandatory, Position=0)][ValidateUserDrive()][string]$Path
$True
Output
argument drive C does not belong to the set of approved drives: User.
PowerShell
Output
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
Output
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
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)]
[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
[string]$flavor = 'Strawberry'
The validation occurs whenever that variable is assigned even within the
script.
PowerShell
Param(
[ValidateSet('hello', 'world')]
[string]$Message
$Message = 'bye'
PowerShell
[string[]] GetValidValues() {
$SoundPaths = '/System/Library/Sounds/',
'/Library/Sounds',
'~/Library/Sounds'
If (Test-Path $SoundPath) {
(Get-ChildItem $SoundPath).BaseName
PowerShell
Param(
[ValidateSet([SoundNames])]
[string]$Sound
7 Note
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.
PowerShell
function MyArgumentCompleter {
Param(
[Parameter(Mandatory)]
[ArgumentCompleter( {
param ( $commandName,
$parameterName,
$wordToComplete,
$commandAst,
$fakeBoundParameters )
} )]
$ParamName
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
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.
PowerShell
function MyArgumentCompleter{
param ( $commandName,
$parameterName,
$wordToComplete,
$commandAst,
$fakeBoundParameters )
$possibleValues = @{
if ($fakeBoundParameters.ContainsKey('Type')) {
$possibleValues[$fakeBoundParameters.Type] | Where-Object {
$_ -like "$wordToComplete*"
} else {
function Test-ArgumentCompleter {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[ValidateSet('Fruits', 'Vegetables')]
$Type,
[Parameter(Mandatory=$true)]
$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.
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.
7 Note
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{}
PowerShell
[CmdletBinding(SupportsPaging=$true)]
Param ($Parameter1)
Begin{}
Process{}
End{}
[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.
The following sample function shows how to add support for the paging
parameters to
an advanced function.
PowerShell
function Get-Numbers {
[CmdletBinding(SupportsPaging)]
param()
$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
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.
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.
Syntax
The OutputType attribute of functions has the following syntax:
[OutputType([<TypeLiteral>], ParameterSetName="<Name>")]
[OutputType("<TypeNameString>", ParameterSetName="<Name>")]
[OutputType([<Type1>],[<Type2>],[<Type3>])]
[OutputType([<Type1>], ParameterSetName=("<Set1>","<Set2>"))]
[OutputType([<Type2>], ParameterSetName="<Set3>")]
PowerShell
function SimpleFunction2
[OutputType([<Type>])]
Param ($Parameter1)
<function body>
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
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
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>
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()
PowerShell
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
PowerShell
function Invoke-Notepad
[OutputType([System.Void])]
Param ()
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
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
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
PowerShell
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}
PowerShell
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
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 {
Rename a function
This command uses the Rename-Item cmdlet to change the name of the help
function
to gh .
PowerShell
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
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.
Cmdlets supported
New-Item
Set-Item
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
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.
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.
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>
To turn on module logging for all sessions on a particular computer, add the
previous
commands to the 'All Users' PowerShell profile
( $Profile.AllUsersAllHosts ).
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.
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.
If you enable this policy setting, you can specify a default value for the
SourcePath
parameter. Enter a file system location.
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.
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
PowerShell
Creating hashtables
To create a hashtable, follow these guidelines:
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
PowerShell
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 = @{}
+ ~~~~~~~~~~~~~~
+ FullyQualifiedErrorId : OrderedAttributeOnlyOnHashLiteralNode
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]@{
$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
PowerShell
$hash.count
For example:
PowerShell
$hash["Number"]
$hashtable.psbase.Keys
PowerShell
7 Note
Each example returns a message for every key and its value:
Output
PowerShell
PowerShell
$hash.Keys | ForEach-Object {
This example uses the GetEnumerator method to send each key-value pair
through the
pipeline to ForEach-Object .
PowerShell
$hash.GetEnumerator() | ForEach-Object {
This example uses the GetEnumerator and ForEach methods to iterate over
each key-
value pair.
PowerShell
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
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.
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.
The following statement creates a hashtable of process name strings and process
object
values and saves it in the $p variable.
PowerShell
You can display the hashtable in $p and use the key-name properties to
display the
values.
PowerShell
$p
Name Value
---- -----
$p.PowerShell
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
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
---- -----
System.ServiceProcess.Servi... Running
$p.keys
PowerShell
Notepad
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
You can display and access the new values using the same methods.
PowerShell
$p
Name Value
---- -----
System.ServiceProcess.Servi... Running
Hash2 {a, b, c}
$p.Hash2
Name Value
---- -----
a 1
b 2
c 3
$p.Hash2.b
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
Name Value
---- -----
System.ServiceProcess.Servi... Running
The following command uses the same procedure to sort the hash values in
descending
order.
PowerShell
Name Value
---- -----
System.ServiceProcess.Servi... Running
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.
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 = @"
"@
ConvertFrom-StringData $string
Name Value
---- -----
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.
Hidden members are not displayed in tab completion or IntelliSense unless the
completion occurs in the class that defines the hidden member.
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
$this.Distance += $miles
$this.rides++
return $this.Distance
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
TypeName: Car
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
TypeName: Car
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.
History Cmdlets
PowerShell has a set of cmdlets that manage the command 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.
PowerShell
$MaximumHistoryCount = 100
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.
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>)
[elseif (<test2>)
[else
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) {
PowerShell
if ($a -gt 2) {
else {
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) {
else {
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.
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 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
Output
TypeName: System.Collections.Hashtable
pstypenames CodeProperty
System.Collections.ObjectModel.Collection`1[[System.String,
System.Private.CoreLib, Version=7…
PowerShell
Output
Count Property 2
PowerShell
$user = [pscustomobject]$hash
Output
Age NoteProperty 33
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
Output
TypeName: System.Management.Automation.PSCustomObject
pstypenames CodeProperty
System.Collections.ObjectModel.Collection`1[[System.String,
System.Private.CoreLib, Version=7…
Type information
The pstypenames CodeProperty lists the object type hierarchy in order of
inheritance.
For example:
PowerShell
$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.
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.
PS> (2)[0]
PS> (2)[-1]
True
True
PowerShell
$expression = [regex]::new('pattern')
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.
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.
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.
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
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
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
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
The following example, the Receive-Job cmdlet gets the results of the job
using job
object in the $job variable.
PowerShell
Output
...
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
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.
PowerShell
C:\PS> Receive-Job -Job $job
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
PowerShell
Get-Job
The results appear in a table. The status of the job appears in the State
column.
Output
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
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
PowerShell
Wait-Job -ID 10
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
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
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
PowerShell
Get-Job $job
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.
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 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
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.
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
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
PowerShell
You can also use a Get-Job command on the child job, as shown in the
following
command:
PowerShell
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.
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 .
PowerShell
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
Name : Job3
When you display the parent job, it shows that the job failed.
PowerShell
PS> $j
But when you run a Get-Job command that gets the child jobs, the output
shows that
only one child job failed.
PowerShell
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
ComputerName DateTime
------------ --------
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.
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.
Invoke-Command cmdlet.
CDXML module.
WMI module.
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
PowerShell
PowerShell
Create a workflow.
PowerShell
PowerShell
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
PowerShell
PS> Get-ScheduledJob
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[]>
Parameters
String[] - Specifies one or more strings to be joined.
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.
For example:
PowerShell
-join "a", "b", "c"
abc
-join $z
abc
Examples
The following statement joins three strings:
PowerShell
WindowsPowerShell2.0
PowerShell
PowerShell
$a -join "OW"
WINDOWS POWERSHELL
PowerShell
$a = @'
'@
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
catch about_Try_Catch_Finally
class about_Classes
data about_Data_Sections
do about_Do, about_While
dynamicparam about_Functions_Advanced_Parameters
else about_If
elseif about_If
enum about_Enum
filter about_Functions
finally about_Try_Catch_Finally
Keyword Reference
for about_For
foreach about_ForEach
hidden about_Hidden
if about_If
in about_ForEach
param about_Functions
return about_Return
static about_Classes
switch about_Switch
try about_Try_Catch_Finally
until about_Do
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> {
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
class
Specifies a new class in PowerShell.
Syntax:
Syntax
class <class-name> {
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
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
Syntax
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> {
else
Used with the if keyword to specify the default statement list.
Syntax:
Syntax
elseif
Used with the if and else keywords to specify additional conditionals. The
else
keyword is optional.
Syntax:
Syntax
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
Syntax:
Syntax
function <name> {
enum
enum is used to declare an enumeration; a distinct type that consists of a
set of named
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.
In the following example, the user sets the error level variable value to 4
by adding exit
4 to the script file test.ps1 .
C:\scripts\test>type test.ps1
exit 4
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
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
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
for
Defines a loop with a condition.
Syntax:
Syntax
foreach
Defines a loop using each member of a collection.
Syntax:
Syntax
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> {
You also have the option of defining one or more parameters outside the
statement list
after the function name.
Syntax:
Syntax
if
Defines a conditional.
Syntax:
Syntax
hidden
Hides class members from the default results of the Get-Member cmdlet,
IntelliSense, and
tab completion results.
Syntax:
Syntax
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> {
<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> {
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.
switch
To check multiple conditions, use a switch statement. The switch statement
is
equivalent to a series of if statements, but it is simpler.
Syntax 1:
Syntax
...
Syntax 2:
Syntax
...
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
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
until
Used in a do statement as a looping construct where the statement list is
executed at
least one time.
Syntax:
Syntax
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
Module syntax:
Syntax
Assembly syntax:
Syntax
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>
do loop Syntax:
Syntax
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.
FullLanguage
RestrictedLanguage
ConstrainedLanguage (introduced in PowerShell 3.0)
NoLanguage
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.
PowerShell
$ExecutionContext.SessionState.LanguageMode
ConstrainedLanguage
PropertyReferenceNotSupportedInDataSection and
VariableReferenceNotSupportedInDataSection error messages.
PowerShell
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.
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 .
$PSCulture
$PSUICulture
$True
$False
$Null
Module manifests are loaded in RestrictedLanguage mode and may use these
additional
variables:
$PSScriptRoot
$PSEdition
$EnabledExperimentalFeatures
-gt (greater-than)
-lt (less-than)
ConstrainedLanguage mode
ConstrainedLanguage mode is designed to allow basic language elements such as
loops,
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]
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.
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.
To move the cursor one character to the right, press the RightArrow .
Delete characters
To delete the character behind the cursor's position, press
Backspace .
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.
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
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
PowerShell
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
When Script Block Logging is enabled, PowerShell logs the following events to
the
Microsoft-Windows-PowerShell/Operational log:
Field Value
Channel Operational
Level Verbose
Opcode Create
Field Value
Task CommandStart
Keyword Runspace
7 Note
Script Block Logging can be enabled via Group Policy or a registry setting.
PowerShell
function Enable-PSScriptBlockLogging
$basePath = 'HKLM:\Software\Policies\Microsoft\Windows' +
'\PowerShell\ScriptBlockLogging'
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.
several forms:
2 Warning
PowerShell
Get-WinEvent Microsoft-Windows-PowerShell/Operational |
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
PowerShell
PowerShell
PowerShell
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.
Syntax
{! | -NOT} <statement>
Statements that use the logical operators return Boolean (TRUE or FALSE)
values.
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
Output
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
$Hash = @{ a = 'b' }
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
The following examples detail the behavior of the member-access operator under
all
possible scenarios.
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'
$MyString.DoesNotExist()
Output
True
named 'DoesNotExist'.
At line:1 char:1
+ $MyString.DoesNotExist()
+ ~~~~~~~~~~~~~~~~~~~~~~
+ FullyQualifiedErrorId : MethodNotFound
PowerShell
$Collection.IsReadOnly
$Collection.Add('c')
$Collection
Output
False
PowerShell
$Collection.Count
$Collection.ToString()
Output
System.Collections.Generic.List`1[System.String]
7 Note
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
PowerShell
$Collection.Length
$Collection.ToUpper()
Output
PowerShell
$Collection.DoesNotExist()
Output
True
named 'DoesNotExist'.
At line:1 char:1
+ $Collection.DoesNotExist()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ 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.
PowerShell
@('a', 1, 'c').ToUpper()
Output
named 'ToUpper'.
At line:1 char:1
+ @('a', 1, 'c').ToUpper()
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ FullyQualifiedErrorId : MethodNotFound
PowerShell
$CapitalizedProperty = @{
MemberType = 'ScriptProperty'
Name = 'Capitalized'
Value = { $this.ToUpper() }
PassThru = $true
[System.Collections.Generic.List[object]]$MixedCollection = @(
'a'
'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.
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
Output
TypeName: System.Diagnostics.Process
...
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.Kill()
PowerShell
(Get-Process Notepad).Kill()
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
Output
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).
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)
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
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
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
$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
Output
Get-Process : Cannot find a process with the name "notepad". Verify the proc
At line:1 char:12
, ProcessCommandException
+ FullyQualifiedErrorId : NoProcessFoundForGivenName,Microsoft.PowerShel
l.Commands.GetProcessCommand
PowerShell
$p | ForEach-Object {$_.Kill()}
PowerShell
// Interface
string IFoo.Bar(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
.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.
PowerShell
Get-CimInstance Win32_OperatingSystem
PowerShell
Get-Command Get-CimInstance
PowerShell
Get-Help Get-CimInstance
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.
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.
This topic explains how to perform these tasks. It also includes other useful
information
about managing modules.
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
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
$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.
PowerShell
Get-Module -ListAvailable
To find the modules that have already been imported into your session, at the
PowerShell prompt, type:
PowerShell
Get-Module
PowerShell
PowerShell
PowerShell
Get-Help <command-name>
PowerShell
To download and install the help files for the commands in a module, type:
PowerShell
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
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.
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.
PowerShell
Import-Module C:\ps-test\TestCmdlets.dll
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
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.
7 Note
You can verify the location of your Documents folder using the
following
command: [Environment]::GetFolderPath('MyDocuments') .
7 Note
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.
PowerShell
$Env:PSModulePath
PowerShell
The semi-colon ( ; ) in the command separates the new path from the path that
precedes it in the list.
$Env:PSModulePath + ";C:\ps-test\Modules"
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.
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.
You can also use the Alias, Cmdlet, Function, and Variable
parameters of Import-Module
to select only the commands that you want to
import, and you can exclude commands
that cause name conflicts in your session.
Even if a command is hidden, you can run it by qualifying the command name with
the
name of the module or snap-in in which it originated.
The 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.
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
PowerShell
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.
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
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.
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'
# 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 = ''
# HelpInfoURI = ''
# DefaultCommandPrefix = ''
can be used.
Allowed commands
Import-LocalizedData
ConvertFrom-StringData
Write-Host
Out-Host
Join-Path
Allowed variables
$PSScriptRoot
$PSEdition
$EnabledExperimentalFeatures
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
Required No
Accepts wildcards No
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:
Tip
PowerShell
@{
RootModule = ''
7 Note
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
Required Yes
Accepts wildcards No
The value of this setting must be convertible to System.Version when you run
Import-
Module .
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.Version
$ExampleModule.Version.GetType().Name
Output
1 2 3 -1
Version
CompatiblePSEditions
This setting specifies the module's compatible PSEditions.
Value
Required No
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.
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
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
Required No
Accepts wildcards No
The value of this setting must be convertible to System.Guid when you run
Import-
Module .
U Caution
PowerShell
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
Accepts wildcards No
This manifest declares that the module's author is the Contoso Developer
Experience
Team.
PowerShell
@{
CompanyName
This setting identifies the company or vendor who created the module.
Value
Required No
Accepts wildcards No
This manifest declares that the module was created by Contoso, Ltd.
PowerShell
@{
Copyright
This setting specifies a copyright statement for the module.
Value
Required No
Accepts wildcards No
PowerShell
@{
Description
This setting describes the module at a high level.
Value
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
@{
PowerShellVersion
This setting specifies the minimum version of PowerShell this module requires.
Value
Required No
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
Required No
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
$Host.Name
Output
ConsoleHost
ServerRemoteHost
PowerShell
@{
# PowerShellHostName = ''
PowerShell
@{
PowerShellHostName = 'ServerRemoteHost'
PowerShellHostVersion
This setting specifies the minimum version of a PowerShell host program that
the
module requires.
Value
Required No
Accepts wildcards No
The value of this setting must be convertible to System.Version when you run
Import-
Module .
U Caution
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
Required No
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
Required No
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
Required No
Accepts wildcards No
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
Required No
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.
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.
7 Note
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
PowerShell
@{
RequiredModules = @(
'Vendored\PSReadLine\PSReadLine.psd1'
PowerShell
@{
RequiredModules = @(
@{
ModuleName = 'PSReadLine'
RequiredVersion = '2.0.0'
PowerShell
@{
RequiredModules = @(
@{
ModuleName = 'PSReadLine'
ModuleVersion = '2.0.0'
PowerShell
@{
RequiredModules = @(
@{
ModuleName = 'PSReadLine'
MaximumVersion = '2.0.0'
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
Required No
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.
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
Required No
Value
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'
PowerShell
if ([string]::IsNullOrEmpty($ExampleState)) {
$ExampleState = 'Initialized'
} else {
When you import the module, the script runs, writing those messages and setting
$ExampleState in your session.
PowerShell
$InformationPreference = 'Continue'
Import-Module .\example7x.psd1
Output
Initializing now...
TypesToProcess
This setting specifies the type files ( .ps1xml ) that run when the module is
imported.
Value
Required No
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 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
Required No
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 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
Required No
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.
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.
7 Note
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
Required No
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 = @()
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.
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
Required No
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 = @()
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.
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
Required No
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 = @()
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 = @()
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
Required No
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
Required No
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.
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.
7 Note
RequiredVersion was added in Windows PowerShell 5.0.
MaximumVersion was added
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
Required No
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.
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
Accepts wildcards No
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
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 {
} catch {
} else {
Once the module is imported, the function uses the value from PrivateData
to
determine when the module was published.
PowerShell
Output
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
Required No
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.
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
Required No
Accepts wildcards No
Module users can override this prefix by specifying the Prefix parameter of
the Import-
Module cmdlet.
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.
Suffix Meaning
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.
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.
Suffix Meaning
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.
7 Note
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.
Multiplier examples
PS> 1kb
1024
PS> 1.30Dmb
1363148.80
PS> 0x10Gb
17179869184
PS> 1.4e23tb
1.5393162788864E+35
PS> 0x12Lpb
20266198323167232
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:
PowerShell
PS> 2.GetType().Name
At line:1 char:11
+ 2.GetType().Name
+ ~
+ FullyQualifiedErrorId : ExpectedExpression
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.
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.
When working with objects, you can use their methods and properties
in commands to
take action and manage data.
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
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:
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
-------------------
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.
PowerShell
$PSDirInfo = Get-Item /
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('/')
Output
Count Name
----- ----
4 CodeProperty
13 Property
1 ScriptProperty
18 Method
[<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.
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
Output
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.
PowerShell
$hash = @{
Name = "Server30"
PSVersion = "4.0"
$Asset = [pscustomobject]$hash
$Asset
Output
PowerShell
[System.Management.Automation.Remoting.PSSessionOption]@{
IdleTimeout=43200000
SkipCnCheck=$True
PowerShell
[System.Diagnostics.ProcessStartInfo]@{
CreateNoWindow="$true"
Verb="run as"
Output
Arguments :
ArgumentList : {}
CreateNoWindow : True
CommonProgramFiles(x86), APPDATA...}
[PROCESSOR_ARCHITECTURE, AMD64],
[CommonProgramFiles(x86),
[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
IdleTimeout=43200000
SkipCnCheck=$True
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.
PowerShell
$dict.Add("One", 1)
$dict
Output
Key Value
--- -----
One 1
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.
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.
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 * .
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.
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.
Type Operators
Use the type operators ( -is , -isnot , -as ) to find or change the .NET
Framework type of
an object.
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++ .
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
example:
PowerShell
True
7 Note
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)
True
PowerShell
PS> $i = 0
PS> $i = 0
PS> $i
You can also use this technique In the context of a conditional statement, such
as the if
statement.
PowerShell
$textFiles.Count
7 Note
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
PowerShell
PS> $list.GetType()
PS> $list.Count
20
PS> $list.GetType()
PS> $list.Count
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
PS> & $c
& : The term 'Get-Service -Name Spooler' is not recognized as the name of a
the name, or if a path was included, verify that the path is correct and
try again.
At line:1 char:2
+ & $c
+ ~~
+ FullyQualifiedErrorId : CommandNotFoundException
The Invoke-Expression cmdlet can execute code that causes parsing errors
when using
the call operator.
& : 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
At line:1 char:2
+ & "1+1"
+ ~~~~~
+ FullyQualifiedErrorId : CommandNotFoundException
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
Hello World!
Cast operator [ ]
Converts or limits objects to the specified type. If the objects can't be
converted,
PowerShell generates an error.
PowerShell
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)
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.
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
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
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
Output
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.
PS> $a = 1, 2, 3
PS> $a[0]
PS> $a[-1]
PS> $a[2, 1, 0]
PowerShell
PowerShell
$h["name"]
Output
PowerShell
PowerShell
$x["doc"]
Output
intro
-----
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]
True
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
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
10..1
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
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()
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.
PowerShell
[datetime]::Now
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.
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
:: (static) about_Operators
++ -- about_Assignment_Operators
! -not about_Logical_Operators
- (unary/negative) about_Arithmetic_Operators
* / % about_Arithmetic_Operators
+ - about_Arithmetic_Operators
OPERATOR REFERENCE
-replace about_Comparison_Operators
OPERATOR REFERENCE
SYNTAX REFERENCE
. (dot-source) 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
PowerShell
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]
PowerShell
False
PowerShell
False
If the -and operator had higher precedence, the answer would be TRUE.
PowerShell
PS> 2 -gt (4 -and 1)
True
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.
7 Note
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
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.
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.
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:
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.
PowerShell
If the Chocolatey provider is not already installed, when you run the
preceding
command, you are prompted to install it.
PowerShell
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.
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 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
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.
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[]>
Required? false
Position? 0
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
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.
PowerShell
PowerShell
$s = "winrm", "netlogon"
Get-Service -Name $s
Value Description
----- -----------
parameter.
True (by Value) Indicates that you can pipe any value to the
Framework type.
True (by Property Name) Indicates that you can pipe a value to the
For example, you can pipe a value to a Name parameter only when the value
has a
property called Name.
7 Note
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.
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.
$PSDefaultParameterValues=@{"CmdletName:ParameterName"="DefaultValue"}
$PSDefaultParameterValues=@{ "CmdletName:ParameterName"={{ScriptBlock}} }
$PSDefaultParameterValues["Disabled"]=$True | $False
$PSDefaultParameterValues["CmdletName:ParameterName"]="DefaultValue"
PowerShell
$PSDefaultParameterValues=@{ "Invoke-Command:ScriptBlock"={{Get-Process}} }
about_Hash_Tables
about_Script_Blocks
about_Preference_Variables
Examples
see about_Profiles.
PowerShell
$PSDefaultParameterValues = @{
"Send-MailMessage:SmtpServer"="Server123"
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"
PowerShell
$PSDefaultParameterValues = @{"*:Verbose"=$True}
PowerShell
$PSDefaultParameterValues = @{
"Invoke-Command:ComputerName"="Server01","Server02"
PowerShell
$PSDefaultParameterValues=@{
PowerShell
$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
$PSDefaultParameterValues["CmdletName:ParameterName"]
PS> $PSDefaultParameterValues["Send-MailMessage:SmtpServer"]
Server123
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")
PowerShell
$PSDefaultParameterValues["Get-Process:Name"]="PowerShell"
PS> $PSDefaultParameterValues
Name Value
---- -----
Get-Process:Name PowerShell
Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational
Get-*:Verbose True
Send-MailMessage:SmtpServer Server123
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")
PS> $PSDefaultParameterValues
Name Value
---- -----
Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational
Get-*:Verbose True
Send-MailMessage:SmtpServer Server123
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"
PS> $PSDefaultParameterValues
Name Value
---- -----
Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational
Get-*:Verbose True
Send-MailMessage:SmtpServer ServerXYZ
PS> $PSDefaultParameterValues["Disabled"]=$True
PS> $PSDefaultParameterValues
Name Value
---- -----
Disabled True
Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational
Get-*:Verbose True
Send-MailMessage:SmtpServer ServerXYZ
PS> $PSDefaultParameterValues.Remove("Disabled")
PS> $PSDefaultParameterValues["Disabled"]=$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.
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
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',
Position = 0)]
[Parameter(Mandatory = $true,
ParameterSetName = 'PathAll',
Position = 0)]
[string[]]$Path,
[Parameter(Mandatory = $true,
ParameterSetName = 'LiteralPath',
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,
[switch]$All,
[Parameter(ParameterSetName = 'Path')]
[Parameter(ParameterSetName = 'PathAll')]
[switch]$Recurse
begin {
if ($All) {
$Lines = $true
if ($Path) {
else {
process {
$result = [ordered]@{ }
$result.Add('File', $file.fullname)
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)
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 |
@{n='Parameters';e={$_.ToString()}}
Output
ParameterSetName Parameters
---------------- ----------
Output
C:\temp\test\test.ps1 3 3 79
PowerShell
Output
At line:1 char:1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ FullyQualifiedErrorId :
AmbiguousParameterSet,Microsoft.PowerShell.Commands.GetChildItemCommand
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.
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
PowerShell
'hello'
32
PowerShell
$x
$script:path
PowerShell
-12
-not $Quiet
3 + 7
$input.Length -gt 1
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:
() , $() , and @() at the start of a token create a new parsing context
that can
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 .
2 Expression 2 (integer)
$a Expression 4 (integer)
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.
PowerShell
Output
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
PowerShell provides several ways break lines at natural points in the syntax.
PowerShell
$parameters = @{
ResourceGroupName = "myResourceGroupVM"
Name = "myVM"
Location = "EastUS"
VirtualNetworkName = "myVnet"
SubnetName = "mySubnet"
SecurityGroupName = "myNetworkSecurityGroup"
PublicIpAddressName = "myPublicIpAddress"
Credential = $cred
New-AzVm @parameters
PowerShell
To run this command in PowerShell 2.0, you must use escape characters to
prevent
PowerShell from misinterpreting the parentheses.
PowerShell
7 Note
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.
PowerShell
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.
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
"a|b"
7 Note
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.
PowerShell
Output
PowerShell
Write-Output -- -InputObject
Output
-InputObject
Unlike the stop-parsing ( --% ) token, any values following the -- token can
be
interpreted as expressions by PowerShell.
PowerShell
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
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>
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.
( . ) - 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 .
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
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
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
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
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
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.
| ( Sorted by length )
| ( 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.
PowerShell
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
PowerShell
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
You can also pipe the output of native commands to PowerShell cmdlets. For
example:
PowerShell
) 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.
PowerShell
or
PowerShell
The help for the Start-Service cmdlet shows that only the InputObject and
Name
parameters accept pipeline input.
Output
-InputObject <ServiceController[]>
Required? true
Position? 0
-Name <String[]>
The parameter name is optional. You can use Name or its alias, ServiceName,
Required? true
Position? 0
ByValue: The parameter accepts values that match the expected .NET type
or that
can be converted to that type.
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.
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.
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
$services = Get-Service
Format-Table -InputObject $services -Property Name, DependentServices
PowerShell
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-
PowerShell
Get-Process | Get-Member
Output
TypeName: System.Diagnostics.Process
...
7 Note
For example,
PowerShell
Output
TypeName: System.Object[]
...
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.
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.
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
PowerShell
Output
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
PowerShell
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
...
...
...
...
Finally, it shows that the attempt to bind the path to the Destination
parameter of Move-
ItemProperty failed.
Output
...
COERCION
COERCION
...
Use the Get-Help cmdlet to view the attributes of the Destination parameter.
Output
-Destination <String>
Required? true
Position? 1
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
Output
Get-Help Move-ItemProperty -Parameter Path
-Path <String[]>
Required? true
Position? 0
For example,
PowerShell
PowerShell
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]
[-NoLogo]
[-NoExit]
[-Sta]
[-Mta]
[-NoProfile]
[-NonInteractive]
[-WindowStyle <style>]
[-EncodedCommand <Base64EncodedCommand>]
[-ConfigurationName <string>]
[-File - | <filePath> <args>]
[-ExecutionPolicy <ExecutionPolicy>]
| { <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.
PowerShell
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.
PowerShell
@'
"in"
"hi" |
% { "$_ there" }
"out"
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.
-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
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.
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
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
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 .
-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.
-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.
-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 V2 session with text input, XML output, and no
logo
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)
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.
Syntax
PowerShell_Ise[.exe]
PowerShell_ISE[.exe]
ISE[.exe]
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:
-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
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.
$ConfirmPreference High
$DebugPreference SilentlyContinue
$ErrorActionPreference Continue
$ErrorView NormalView
$FormatEnumerationLimit 4
$InformationPreference SilentlyContinue
$MaximumAliasCount 4096
Variable Default Value
$MaximumDriveCount 4096
$MaximumErrorCount 256
$MaximumFunctionCount 4096
$MaximumHistoryCount 4096
$MaximumVariableCount 4096
$ProgressPreference Continue
$PSModuleAutoLoadingPreference All
$PSSessionApplicationName 'wsman'
$PSSessionConfigurationName 'http://schemas.microsoft.com/powershell/Microsoft.PowerShell'
$VerbosePreference SilentlyContinue
$WarningPreference Continue
$WhatIfPreference $False
env:PSExecutionPolicyPreference
$env:PSModulePath
7 Note
PowerShell
$ConfirmPreference
Output
High
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.
$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.
To change the confirming behavior for all cmdlets and functions in the session,
change
$ConfirmPreference variable's value.
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
Output
Confirm
[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
PowerShell
Output
Confirm
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend
PowerShell
$ConfirmPreference = "Medium"
Output
Confirm
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend
PowerShell
$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.
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.
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.
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.
PowerShell
$DebugPreference
Output
SilentlyContinue
PowerShell
PowerShell
Output
Confirm
[Y] Yes [A] Yes to All [H] Halt Command [S] Suspend
PowerShell
$DebugPreference = "Continue"
Output
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
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"
Output
At line:1 char:1
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
PowerShell
$DebugPreference = "Inquire"
Output
Confirm
[Y] Yes [A] Yes to All [H] Halt Command [S] Suspend
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
$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.
Examples
These examples show the effect of the different values of the
$ErrorActionPreference
variable. The ErrorAction parameter is used to
override the $ErrorActionPreference
value.
PowerShell
$ErrorActionPreference = 'Continue'
Output
+ FullyQualifiedErrorId :
Microsoft.PowerShell.Commands.WriteErrorException
Hello World
PowerShell
$ErrorActionPreference = 'Inquire'
Output
Confirm
Test Error
[Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is
"Y"):
PowerShell
$ErrorActionPreference = 'SilentlyContinue'
Output
Hello World
PowerShell
# Change the ErrorActionPreference to 'Stop'
$ErrorActionPreference = 'Stop'
$Error[0]
$Error[1]
Output
At line:1 char:1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ FullyQualifiedErrorId :
Microsoft.PowerShell.Commands.WriteErrorException
At line:1 char:1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ FullyQualifiedErrorId :
Microsoft.PowerShell.Commands.WriteErrorException
$ErrorView
Determines the display format of error messages in PowerShell.
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
Output
At line:1 char:1
This example shows how the same error appears when the value of $ErrorView is
changed to CategoryView.
PowerShell
$ErrorView = "CategoryView"
Output
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
Output
PSMessageDetails :
Exception : System.Management.Automation.ItemNotFoundException:
not exist.
at
System.Management.Automation.SessionStateInternal.
at System.Management.Automation.ChildItemCmdlet
at
Microsoft.PowerShell.Commands.GetChildItemCommand.
ProcessRecord()
TargetObject : C:\nofile.txt
ItemNotFoundException
FullyQualifiedErrorId : PathNotFound,
Microsoft.PowerShell.Commands.GetChildItemCommand
ErrorDetails :
InvocationInfo : System.Management.Automation.InvocationInfo
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
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.
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
Output
PowerShell
$FormatEnumerationLimit = 1000
Output
Use Format-Table with the Wrap parameter to display the list of services.
PowerShell
Output
$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.
$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.
(logged).
$LogEngineLifecycleEvent : Logs the opening and closing of sessions. The
default is
$true (logged).
$LogProviderHealthEvent : Logs provider errors, such as read and write
errors,
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.
Default: 4096
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.
Default: 4096
PowerShell
(Get-PSDrive).count
$MaximumErrorCount
Determines how many errors are saved in the error history for the session.
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]
PowerShell
$Error[($Error.Count -1]
PowerShell
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
PowerShell
$Error | Get-Member
$MaximumFunctionCount
Determines how many functions are permitted in a given session.
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.
PowerShell
Get-ChildItem Function:
PowerShell
(Get-ChildItem Function:).Count
$MaximumHistoryCount
Determines how many commands are saved in the command history for the current
session.
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.
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.
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.
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.
The valid values are as follows: Objects derived from an Encoding class, such
as
ASCIIEncoding,
UTF7Encoding,
UTF8Encoding,
UTF32Encoding, and
UnicodeEncoding.
The first command finds the value of $OutputEncoding . Because the value is an
encoding
object, display only its EncodingName property.
PowerShell
$OutputEncoding.EncodingName
PowerShell
findstr <Unicode-characters>
PowerShell
$OutputEncoding = [console]::OutputEncoding
$OutputEncoding.EncodingName
Output
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.
$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.
$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' .
$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.
$PSSessionConfigurationName
Specifies the default session configuration that's used to create new sessions
in the
current session.
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.
$PSSessionOption
Establishes the default values for advanced user options in a remote session.
These
option preferences override the system default values for session
options.
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
PowerShell
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.
$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 .
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
PowerShell
Output
PowerShell
$VerbosePreference = "Continue"
Output
This example uses the Verbose parameter with a value of $false that
overrides the
Continue value. The message isn't displayed.
PowerShell
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"
Output
At line:1 char:1
This example uses the Verbose parameter with a value of $false that
overrides the Stop
value. The message isn't displayed.
PowerShell
PowerShell
$VerbosePreference = "Inquire"
Output
Confirm
[Y] Yes [A] Yes to All [H] Halt Command [S] Suspend
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
$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 .
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.
PowerShell
$m = "This action can delete data."
Write-Warning -Message $m
Output
PowerShell
PowerShell
$WarningPreference = "SilentlyContinue"
Write-Warning -Message $m
PowerShell
Output
At line:1 char:1
PowerShell
$WarningPreference = "Inquire"
Write-Warning -Message $m
Output
Confirm
[Y] Yes [A] Yes to All [H] Halt Command [S] Suspend
PowerShell
PowerShell
$WarningPreference = "Stop"
Write-Warning -Message $m
Output
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
Output
Confirm
[Y] Yes [A] Yes to All [H] Halt Command [S] Suspend
$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.
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
Output
Directory: C:\Test
PowerShell
Output
At line:1 char:1
This example shows the effect of using the WhatIf parameter when the value
of
$WhatIfPreference is False.
PowerShell
Output
Directory: C:\Test
PowerShell
Output
Output
Directory: C:\Test
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.
PowerShell
$WhatIfPreference = "True"
Output
PowerShell
Output
Directory: C:\Test
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
Output
At line:1 char:1
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.
PowerShell
Output
PowerShell
Output
You can override the Stop-Process WhatIf behavior using the WhatIf
parameter with a
value of $false . The Winword process is stopped.
PowerShell
PowerShell
Output
At line:1 char:1
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.
For example, the PowerShell console supports the following basic profile files.
The
profiles are listed in order that they're executed.
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.
7 Note
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.
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.
PowerShell
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
PowerShell
For example, to create a profile for the current user in the current PowerShell
host
application, use the following command:
PowerShell
7 Note
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.
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.
Get-Alias |
function CustomizeConsole {
$hostversion="$($Host.Version.Major)`.$($Host.Version.Minor)"
Clear-Host
CustomizeConsole
function Prompt
Type:
powershell -NoProfile
powershell -?
For example, the following command runs the "Current user, Current Host"
profile from
the local computer in the session in $s .
PowerShell
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
. "$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.
PowerShell
For example, the following Prompt function returns a "Hello, World" string
followed by a
right angle bracket ( > ).
PowerShell
PS C:\> function prompt {"Hello, World > "}
For example:
PowerShell
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
PS>
For example, the following command sets the Prompt function to $null , which
is invalid.
As a result, the default prompt appears.
PowerShell
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 {
Output
[DBG]: PS C:\ps-test>
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>>>
Output
Other PowerShell host applications and alternate shells might have their own
custom
command prompts.
function prompt { }
Then, between the braces, enter the commands or the string that creates your
prompt.
PowerShell
Output
PS [Server01] >
The following Prompt function includes the current date and time:
PowerShell
Output
03/15/2012 17:49:47>
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()
$adminRole = [Security.Principal.WindowsBuiltInRole]::Administrator
else { '' }
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
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 {
-ForegroundColor $Color
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
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
Output
TypeName: System.IO.FileInfo
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
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
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
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
ProductVersion: 10.0.22000.1
Debug: False
Patched: False
PreRelease: False
PrivateBuild: False
SpecialBuild: False
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
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
Output
TypeName: System.DateTime
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 Identity
Application Information
...
All collections have a Count property that returns the number of objects in
the
collection.
PowerShell
(Get-Service).Count
Output
176
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"}
$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
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.
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.
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
You can view and move through the data in a provider drive just as you would on
a file
system drive.
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:
PowerShell
Get-ChildItem
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.
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
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
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
PowerShell
Cert:\> Set-Location ~
Output
Set-Location : Home location for this provider isn't set. To set the home
At line:1 char:1
+ Set-Location ~
+ ~~~~~~~~~~~~~~
PSInvalidOperationException
...
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
Get-Help <ProviderName>
For example:
PowerShell
Get-Help registry
PowerShell
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
# Notepad opens. Enter your command in it, save the file, and then exit.
$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.
PowerShell
TypeName: System.Management.Automation.PSCustomObject
PS> $object1
one two
--- ---
1 2
TypeName: System.Management.Automation.PSCustomObject
PS> $object2
one two
--- ---
1 2
PowerShell
TypeName: System.Management.Automation.PSCustomObject
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"
PSVersion = "4.0"
$Asset = [pscustomobject]$hash
$Asset
Output
PowerShell
False
PowerShell
PS> [pscustomobject]
PS> [psobject]
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
True
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
System.Collections.Hashtable
PS> ([pscustomobject]123).GetType().Name
Int32
System.Management.Automation.PSCustomObject
Wrapped objects will match their original type and the [psobject] type.
PowerShell
True
False
True
True
PowerShell
1 2
At line:1 char:1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ 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
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.
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 = @{
Process = {
$PSItem + 1
Output
Result is: 2 3 4
Where-Object FilterScript
The Where-Object cmdlet is designed to filter objects in the pipeline.
PowerShell
Output
PowerShell
Output
PowerShell
PowerShell
$numbers = 1, 2, 3
switch ($numbers) {
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.
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
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) {
$number = $entries.Length
end {
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]@{
[pscustomobject]@{
[pscustomobject]@{
Output
"TimeStamp": "\/Date(1670344068257)\/"
},
"TimeStamp": "\/Date(1670344068259)\/"
},
"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.
PowerShell
function Add-EvenNumber {
param(
[int[]]$Number
begin {
[int]$total = 0
}
process {
$total += $n
end {
$total
Add-EvenNumber -Number 2, 4, 6
Add-EvenNumber -Number 1, 2
Output
12
" 0 -eq ($PSItem % 2) " validation script for the argument with value "1"
did not return a result of True. Determine why the validation script
At line:1 char:24
+ Add-EvenNumber -Number 1, 2
+ ~~~~
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.
Output
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.
PowerShell
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.
PowerShell
$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
$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.
You can also create a PSSession on the local computer and run commands in it.
A local
PSSession uses the Windows PowerShell remoting infrastructure to
create and maintain
the PSSession.
This topic explains how to create, use, get, and delete PSSessions. For more
advanced
information, see
about_PSSession_Details.
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.
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.
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.
For example, the following command creates a new PSSession on the Server01
computer.
PowerShell
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
PowerShell
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
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
PowerShell
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.
PowerShell
PowerShell
or
PowerShell
Remove-PSSession -Id 1
PowerShell
If you do not delete the PSSession, the PSSession remains available for use
until it times
out.
PowerShell
Get-Help *-PSSession
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.
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.
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.
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.
PowerShell
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.
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.
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.
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.
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
PowerShell
PowerShell
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
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.
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
PowerShell
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.
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.
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 ( " ).
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
Output
The value of 5 is 5.
PowerShell
Output
The value of 5 is 5.
PowerShell
Output
PS version: 5.1.19041.1151
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 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
Output
PowerShell
Output
PowerShell
Output
PowerShell
Output
Or, double the quotation marks around a double-quoted phrase. For example:
PowerShell
Output
PowerShell
'don''t'
Output
don't
PowerShell
Output
Here-strings
The quotation rules for here-strings are slightly different.
A here-string:
You can use here-strings for any text, but they are particularly useful for
the following
kinds of text:
@"<Enter>
"@
Single-quotes:
@'<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
@"
"@
Output
PowerShell
@"
"@
Output
PowerShell
@'
'@
Output
PowerShell
@"
$profile.
"@
Output
C:\Users\User1\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1.
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:description>
<command:verb>format</command:verb>
<command:noun>table</command:noun>
<dev:version></dev:version>
</command:details>
...
</command:command>
"@
7 Note
PowerShell
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
Output
hashtable:
Name Value
---- -----
key value
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.
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.
) 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.
7 Note
Unlike some Unix shells, you can only redirect other streams to the
Success stream.
Examples
PowerShell
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
PowerShell
PowerShell
&{
Write-Warning "hello"
Write-Error "hello"
Write-Output "hi"
PowerShell
PowerShell
&{
Write-Host "Hello"
} 6> $null
PowerShell
$ErrorActionPreference = 'Continue'
$ErrorActionPreference = 'SilentlyContinue'
$ErrorActionPreference = 'Stop'
Try {
catch {
$ErrorActionPreference = 'Ignore'
$ErrorActionPreference = 'Inquire'
$ErrorActionPreference = 'Continue'
PowerShell
PS C:\temp> .\test.ps1
Confirm
[Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is
"Y"): H
Get-Item: C:\temp\test.ps1:23
Line |
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| The running command stopped because the user selected the Stop
option.
Get-Item: C:\temp\test.ps1:3
Line |
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
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.
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.
Output
Name Value
---- -----
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
Depending on the objects being compared, the output using > can appear to be
correct
(because 36 is not greater than 42).
PowerShell
false
However, a check of the local filesystem can see that a file called 42 was
written, with
the contents 36 .
PowerShell
PS> dir
PS> cat 42
36
Attempting to use the reverse comparison < (less than), yields a system error:
PowerShell
At line:1 char:8
+ ~
+ FullyQualifiedErrorId : RedirectionNotSupported
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
$var
Output
10
When passing a variable by reference, the function can change the data and
that change
persists after the function executes.
PowerShell
Function Test($data)
$var = @{}
$var
Output
Name Value
---- -----
The function adds a new key-value pair that persists outside of the function's
scope.
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
7 Note
PowerShell
$var = 10
$var
Output
PowerShell
Output
PS> $number = 0
True
PS> $number
15
PowerShell
$i = 0
$iRef = [ref]0
&{$i++;$iRef.Value++}
Output
$i = 0;$iRef = 1
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 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
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"
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.
PowerShell
Output
Hive: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services
Name Property
---- --------
Description : @%systemroot%\system32\spoolsv.exe,-2
DisplayName : @%systemroot%\system32\spoolsv.exe,-1
ErrorControl : 1
Group : SpoolerGroup
ImagePath : C:\WINDOWS\System32\spoolsv.exe
ObjectName : LocalSystem
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
Output
Hive: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Spooler
Name Property
---- --------
Collect : PerfCollect
Library : C:\Windows\System32\winspool.drv
Open : PerfOpen
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
---- --------
Description : @%systemroot%\system32\spoolsv.exe,-2
...
For more information on the cmdlets covered in this section, see the following
articles.
-Get-Item
-Get-ChildItem
PowerShell
$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
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
PowerShell
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
PowerShell
Output
17134.1
For more information on the cmdlets used in this section, see the following
articles.
Get-ItemProperty
Get-ItemPropertyValue
Output
Name StartType
---- ---------
spooler Automatic
PowerShell
$path = "HKLM:\SYSTEM\CurrentControlSet\Services\Spooler\"
Output
Name StartType
---- ---------
spooler Manual
PowerShell
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
For more information on the cmdlets used in this section, see the following
articles.
Set-Item
Set-ItemProperty
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"
7 Note
Review the dynamic parameters section in this article for other allowed type
values.
PowerShell
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"
For more information on the cmdlets used in this section, see the following
articles.
Copy-Item
Copy-ItemProperty
PowerShell
PowerShell
$source = "HKLM:\SOFTWARE\Contoso"
$dest = "HKLM:\SOFTWARE\Fabrikam"
For more information on the cmdlets used in this section, see the following
articles.
Move-Item
Move-ItemProperty
PowerShell
$path = "HKLM:\SOFTWARE\Contoso"
PowerShell
$acl.SetAccessRule($rule)
For more examples and cmdlet usage details see the following articles.
Get-Acl
Set-Acl
PowerShell
dir HKLM:\SOFTWARE\Contoso\
Output
Hive: HKEY_LOCAL_MACHINE\SOFTWARE\Contoso
Name Property
---- --------
ChildKey
PowerShell
Output
Confirm
parameter was not specified. If you continue, all children will be removed
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help
(default is "Y"):
PowerShell
PowerShell
PowerShell
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
---- --------
(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).
Value Description
Value Description
Binary Specifies binary data in any form. Used for REG_BINARY values.
REG_RESOURCE_LIST values.
Cmdlets supported
Set-Item
Set-ItemProperty
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
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.
Select-String
-match and -replace operators
-split operator
switch statement with -regex 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"
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
PowerShell
# This expression returns true if the pattern matches big, bog, or bug.
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).
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
Wildcards
The period ( . ) is a wildcard character in regular expressions. It will match
any character
except a newline ( \n ).
PowerShell
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
# The pattern uses the whitespace character class to match the leading
Quantifiers
Quantifiers control how many instances of each element should be present in the
input
string.
Quantifier Description
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.
The plus sign ( + ) matches the previous element one or more times.
PowerShell
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.
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
PowerShell
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.
7 Note
When using anchors in PowerShell, you should understand the difference between
Singleline and Multiline regular expression options.
Escaping characters
The backslash ( \ ) is used to escape characters so they aren't parsed by the
regular
expression engine.
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.
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
\t Matches a tab
\n Matches a newline
PowerShell
Output
True
PowerShell
$Matches.0
Output
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
) Important
The 0 key is an Integer. You can use any Hashtable method to access
the value
stored.
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.
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 -match $r
Output
True
PowerShell
$Matches
Output
Name Value
---- -----
D CONTOSO
N jsmith
7 Note
PowerShell
Output
PowerShell
Output
FABRIKAM\Administrator
PowerShell
Output
Gobble Gobble
2 Warning
PowerShell
Output
Hello Universe
Hello Universe
PowerShell
Output
$5.72
$5.72
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.
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.
PowerShell
Enter-PSSession Server01
The command prompt changes to indicate that you are connected to the Server01
computer.
Server01\PS>
PowerShell
Exit-PSSession
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
PowerShell
Get-Command | Where-Object {
For example, the following command runs a Get-Culture command on the Server01
computer.
PowerShell
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.
PowerShell
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
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
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
PowerShell
For example, the following command runs the Sample.ps1 script on the S1 and S2
computers:
PowerShell
The results of the script are returned to the local computer. You do not need
to copy
any files.
For information about how remoting works, how to manage remote data, special
configurations, security issues, and other frequently asked questions, see
PowerShell Remoting FAQ.
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.
sessions.
Invoke-Command : InDisconnectedSession parameter creates a PSSession and
disconnects immediately.
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.
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.
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 first command creates a session to the Server01 computer. The session
resides on
the Server01 computer.
PowerShell
Output
PowerShell
Output
PowerShell
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
PowerShell
Output
PowerShell
Output
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.
The following command gets the sessions on the Server02 computer. The output
includes two disconnected sessions, both of which are available.
PowerShell
Output
The following command connects to Session2. The PSSession is now open and
available.
PowerShell
Output
disconnected.
PowerShell
Output
PowerShell
Output
ProviderName: PowerShell
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
Output
PowerShell
# Session 2
Output
PowerShell
# Session 1
Output
PowerShell
# Session 2
Output
PowerShell
# Session 2
Output
PowerShell
# Session 1
Output
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.
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.
PowerShell
Get-PSSessionConfiguration |
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.
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 ).
PowerShell
$PSSessionOption = New-PSSessionOption -IdleTimeoutMSec 172800000
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
New-PSSession -SessionOption $o
For example:
PowerShell
TransportOption parameter of
Register-PSSessionConfiguration .
For example:
PowerShell
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
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.
PowerShell
(Get-PSSessionConfiguration <ConfigurationName>).OutputBufferingMode
PowerShell
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.
property is Drop.
For example:
PowerShell
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
New-PSSession -SessionOption $o
For example:
PowerShell
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
For example:
PowerShell
For example:
PowerShell
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.
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.
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.
the same process on the local machine. For more information, see
about_Thread_Jobs.
) 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.
Remote Jobs
You can run jobs on remote computers by using three different
methods.
PowerShell
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.
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
PowerShell
The Get-Job output shows that job is running on the "localhost" computer
because the job was started on and is running on the same computer (in this
case,
Server01).
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
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.
PowerShell
Get-Content c:\logs\pslog.txt}
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.
PowerShell
Output
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.
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
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
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.
PowerShell
PowerShell
Output
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.
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
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
PowerShell
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
PowerShell
PS> $job
PS> $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.
PowerShell
PowerShell
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
DateTime PSComputerName
-------- --------------
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
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
Id ProcessName MachineName
-- ----------- -----------
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.
PowerShell
@{Label="NPM(K)";Expression={int}}, `
@{Label="PM(K)";Expression={int}}, `
@{Label="WS(K)";Expression={int}}, `
@{Label="VM(M)";Expression={int}}, `
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.
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.
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
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:
To run remote sessions on Windows PowerShell 2.0, the local and remote
computers
must have the following:
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.
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.
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.
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
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
Run as administrator
Administrator privileges are required for the following remoting operations:
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.
1. Click Start, click All Programs, and then click the Windows PowerShell
folder.
2. Right-click Windows PowerShell, 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.
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.
PowerShell
New-PSSession
Output
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.
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.
ERROR: Access is denied. You need to run this cmdlet from an elevated
process.
Right-click a Windows PowerShell (or Windows PowerShell ISE) icon and then
click
Run as administrator.
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.
or
ERROR: The connection to the remote host was refused. Verify that the
Enable-PSRemoting
Enable-PSRemoting -Force
or
ERROR: The connection to the remote host was refused. Verify that the
To enable remoting for multiple computers in an enterprise, you can use the
following
scaled options.
To enable a firewall exception, use the Windows Firewall: Allow Local Port
Exceptions group policy.
or
ERROR: The connection to the remote host was refused. Verify that the
To configure the listeners for all computers in a domain, enable the Allow
automatic
configuration of listeners policy in the following Group Policy
path:
Enable the policy and specify the IPv4 and IPv6 filters. Wildcards ( * ) are
permitted.
The Enable-PSRemoting cmdlet returns this error when the local network is
public and
the SkipNetworkProfileCheck parameter is not used in the command.
To remove the local subnet restriction on public networks and allow remote
access from
any location, run the following command:
PowerShell
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
7 Note
or
ERROR: The connection to the remote host was refused. Verify that the
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
PowerShell
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 : {}
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
To see the results use the Get-WMIObject cmdlet with the Win32_Service
object. For
more information, see
Set-Service.
To connect to the local computer and run commands remotely, the local computer
must
include session configurations for remote commands.
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
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").
PowerShell
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
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
-Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System `
ERROR: The WinRM client cannot process the request. If the authentication
domain, then HTTPS transport must be used or the destination machine must be
1. Configure the computer for HTTPS transport or add the IP addresses of the
remote
computers to the TrustedHosts list on the local computer.
This is required even when you are submitting the credentials of the current
user.
domain, then HTTPS transport must be used or the destination machine must be
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.
To set password for your user account, use User Accounts in Control Panel.
This is required even when you are submitting the credentials of the current
user.
To view or change the trusted host list, use the WSMan: drive. The TrustedHost
item is in
the WSMan:\localhost\Client node.
Caution: The value that you set for the TrustedHosts item affects all users of
the
computer.
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
PowerShell
To add the names of particular computers to the list of trusted hosts, use
the following
command format:
PowerShell
<Computer>.<Domain>.<Company>.<top-level-domain>
For example:
PowerShell
$server = 'Server01.Domain01.Fabrikam.com'
To add a computer name to an existing list of trusted hosts, first save the
current value
in a variable, and then set the value to a comma-separated list
that includes the current
and new values.
For example, to add the Server01 computer to an existing list of trusted hosts,
use the
following command
PowerShell
"$curValue, Server01.Domain01.Fabrikam.com"
PowerShell
For example:
PowerShell
ERROR: The connection to the specified remote host was refused. Verify that
the
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
requests.
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:
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
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.
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
Output
x86
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
PowerShell
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 WSMan provider (WSMan:) provides several quota settings, such as the
MaxEnvelopeSizeKB and MaxProviderRequests settings in the
WSMan:
<ComputerName> node and the MaxConcurrentOperations,
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.
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
-MaximumReceivedObjectSizeMB 11 -Force
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.
You can also protect the remote computer by setting timeout values
programmatically in the session configuration for the session.
PowerShell
For more information about the WS-Management timeouts, see the Help topic for
the
WSMan provider (type Get-Help WSMan ).
When you use these programs, you might see unexpected behavior, such as no
output,
partial output, or a remote command that does not complete.
or an application request.
To resolve this issue, verify that the WinRM service is running and try the
command
again.
Start-Service WinRM
Authentication
Only basic authentication works on macOS and attempting to use other
authentication
schemes may result in the process crashing.
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.
PowerShell
PowerShell
$s = New-PSSession -ComputerName S1
Beginning in PowerShell 3.0, you can use the Using scope modifier to identify
a local
variable in a remote command.
$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*"
PowerShell
$s = New-PSSession -ComputerName S1
$ps = "*PowerShell*"
PowerShell
$s = New-PSSession -ComputerName S1
$ps = "*PowerShell*"
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
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.
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*"
param($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 -RunAsAdministrator
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
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
) Important
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:
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
For example:
PowerShell
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.
7 Note
RequiredVersion was added in Windows PowerShell 5.0.
MaximumVersion was added
For example:
PowerShell
PowerShell
PowerShell
PowerShell
When using the RequiredVersion key, ensure your version string exactly matches
the
version string you wish to require.
PowerShell
Get-Module Hyper-V
Output
-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
-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
7 Note
This parameter is intended for use in mini-shells, which have been deprecated.
-RunAsAdministrator
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 -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.
continue if try
data in type
do interface using
end param
enum private
Get-Help about_ForEach
For information about the Filter statement or the Return statement syntax,
type:
PowerShell
Get-Help about_Functions
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
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.
7 Note
Syntax
The syntax for the return keyword is as follows:
return [<expression>]
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)
$number * 2
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
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)
$value += 73
return $value
$a = calculation 14
PS> $a
87
Both the informational string and the result of the calculation are returned
by the
function and assigned to the $a variable.
PowerShell
function calculation {
param ($value)
$value += 73
return $value
$a = calculation 14
Output
C:\PS> $a
87
PowerShell
function Test-Return
$array = 1,2,3
return $array
Test-Return | Measure-Object
Output
Count : 3
Average :
Sum :
Maximum :
Minimum :
Property :
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 :
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
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.
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.
"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.
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.
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.
For example, to get all the variables in the local scope, type:
PowerShell
PowerShell
Scope modifiers
A variable, alias, or function name can include any one of the following
optional scope
modifiers:
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
Namespace Description
Namespace Description
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.
$[<scope-modifier>:]<name> = <value>
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 *
Name : a
Description :
Value : one
Visibility : Public
Module :
ModuleName :
Options : None
Attributes : {}
PowerShell
Using the private scope modifier sets the Options property to Private .
Output
Name : pVar
Description :
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 {
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
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:
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.
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
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
PowerShell
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
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.
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
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.
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.
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.
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.
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
PS> $ConfirmPreference
High
PowerShell
$ConfirmPreference = "Low"
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
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.
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"
When you run Sample.ps1 , the output should resemble the following output:
Output
When the script is complete, only the global value of $test is defined in the
session.
PS> $test
Global
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"
PS> $test
Local
PowerShell
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 $ptest variable isn't visible in the script scope, the output is empty.
PowerShell
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
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.
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.
Set-ExecutionPolicy AllSigned
or
PowerShell
Set-ExecutionPolicy RemoteSigned
To run a script, type the full name and the full path to the script file.
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
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.
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.
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.
PowerShell
C:\Scripts\Get-ServiceLog.ps1
PowerShell
get-help C:\admin\scripts\ServicesLog.ps1
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
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.
PowerShell
function CanPing {
$error.clear()
if (!$?)
else
function CanRemote {
else
To run this script, type the parameter name after the script name. For example:
PowerShell
For more information about the Param statement and the function parameters, see
about_Functions and
about_Functions_Advanced_Parameters.
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.
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.
PowerShell
#In UtilityFunctions.ps1
function New-Profile
if (test-path $profile)
else
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
At line:1 char:12
+ new-profile <<<<
+ 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
C:\PS> $profileName
Microsoft.PowerShellISE_profile.ps1
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.
$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
PSCommandPath contains the full path and name of the script that called or
invoked 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.
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.
{<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.
PowerShell
Output
...
Invoke-Command can also execute script blocks that have parameter blocks.
Parameters
PowerShell
"p1: $p1"
"p2: $p2"
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 ).
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
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"
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
Within the delay-bind script block, you can reference the piped in object
using the
pipeline variable $_ .
PowerShell
# Without delay-binding
# With delay-binding
In more complex cmdlets, delay-bind script blocks allow the reuse of one piped
in
object to populate other 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
Output
At line:1 char:23
+ ~~~~~~~~~~~~~~~~~~
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.
A Data section that separates text strings from code instructions. For more
information about the Data section, see
about_Data_Sections.
A new file type, .psd1 , that stores translated text strings. The .psd1
files are stored
in language-specific subdirectories of the script directory.
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 @'
'@
<language>-<region>
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
'@
PowerShell
helloWorld =
مرحًبا أيها العاَل م
errorMsg1 =
ال يمكنك ترك حقل اسم المستخدم فارًغا
promptMsg =
يرجى إدخال اسم المستخدم الخاص بك
'@
PowerShell
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 }
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 script begins with a Data section named Day ($Day) that contains a
ConvertFrom-
StringData command. The expression submitted to
ConvertFrom-StringData is a here-
The remaining commands load the strings into an array and display them.
PowerShell
$Day = Data {
#culture="en-US"
messageDate = Today is
d0 = Sunday
d1 = Monday
d2 = Tuesday
d3 = Wednesday
d4 = Thursday
d5 = Friday
d6 = Saturday
'@
The .psd1 files that support the script are saved in subdirectories of the
script directory
with names that match the $PSUICulture values.
PowerShell
# culture="de-DE"
ConvertFrom-StringData @'
d0 = Sonntag
d1 = Montag
d2 = Dienstag
d3 = Mittwoch
d4 = Donnerstag
d5 = Freitag
d6 = Samstag
'@
Output
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.
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.
Name : microsoft.powershell
Permission : BUILTIN\Administrators AccessAllowed
Name : microsoft.powershell.workflow
Name : microsoft.powershell32
PowerShell
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.)
PowerShell
WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Plugin
For example, the following command adds a node for the Server01 remote
computer to
the WSMAN: drive on the local computer.
PowerShell
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
WSManConfig: Microsoft.WSMan.Management\WSMan::server01.corp.fabrikam.com\Pl
ugin
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.
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
-ShowSecurityDescriptorUI
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
For example:
PowerShell
-ShowSecurityDescriptorUI
PowerShell
-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.
PowerShell
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
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.
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.
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.
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
To view the new configuration file in your default text editor, use the
following
command:
PowerShell
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
-Path .\NoLanguage.pssc
To create a session configuration for sessions in which users can use only Get
cmdlets,
type:
PowerShell
-Path .\GetSessions.pssc
PowerShell
New-PSSessionConfigurationFile -RunAsVirtualAccount
-Path .\VirtualAccount.pssc
PowerShell
New-PSSessionConfigurationFile -RoleDefinitions
-Path .\Maintenance.pssc
For example, the following command uses the NoLanguage.pssc file when it
creates a
NoLanguage session configuration.
PowerShell
-Path .\NoLanguage.pssc
When a new NoLanguage session starts, users will only have access to Windows
PowerShell commands.
For example, the following command adds the NoLanguage.pssc file to the
LockedDown
session configuration.
PowerShell
-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
-ConfigurationName LockedDown
en-US
ParseException
+ FullyQualifiedErrorId : ScriptsNotAllowed
The following command gets the location of the session configuration file for
the
NoLanguage session configuration.
PowerShell
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.
For example, the following command tests the active session configuration file
of the
NoLanguage session configuration.
PowerShell
WindowsPowerShell\v1.0\SessionConfig\
NoLanguage_0c115179-ff2a-4f66-a5eb-e56e5692ba22.pssc
-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.
PowerShell
Output
TypeName: Microsoft.PowerShell.Commands.PSSessionConfigurationCommands
#PSSessionConfiguration
PowerShell
Get-PSSessionConfiguration |
PowerShell
Get-PSSessionConfiguration |
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.
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
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.
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
[V] Never run [D] Do not run [R] Run once [A] Always run
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.
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 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.
PowerShell
$params = @{
Type = 'CodeSigning'
CertStoreLocation = 'Cert:\CurrentUser\My'
HashAlgorithm = 'sha256'
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).
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
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.
PowerShell
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
---------- -------
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.
) 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
To sign the Add-Signature.ps1 script file, type the following commands at the
PowerShell command prompt:
PowerShell
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
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.
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.
Standard Syntax
PowerShell
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
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
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
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.
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.
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
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
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
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
PowerShell
"Column1`t`tColumn2`t`tColumn3"
Output
PowerShell
The following examples show the rendered output of the vertical tab in some
common
environments.
Output
Output
Output
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.
PowerShell
Write-Output -- -InputObject
Output
-InputObject
Place the stop-parsing token after the program name and before program
arguments
that might cause errors.
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 {
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
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
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
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
The first example uses the traditional format in which parameter names are
omitted. The
parameter values appear in position order in the command.
PowerShell
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
The following example has a script block that takes a single parameter that is
an array of
strings.
PowerShell
Invoke-Command -ScriptBlock {
} -ArgumentList $array
In this example, only the first item in $array is passed to the script block.
Output
Hello
PowerShell
Invoke-Command -ScriptBlock {
} -ArgumentList (,$array)
Output
Hello World!
Examples
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
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
PowerShell
function Test1
"a = $a"
"b = $b"
"c = $c"
function Test2
Test1 @PSBoundParameters
#Call the Test1 function with $b and $c, but not with $a
Test2 -a 1 -b 2 -c 3
Output
a = 1
b = 2
c = 3
a =
b = 2
c = 3
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
When you use the Get-MyProcess function, all unassigned parameters and
parameter
values are passed to @Args , as shown in the following commands.
PowerShell
Output
PowerShell
Output
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
Output
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 :
\v1.0\powershell.exe
InternalName: POWERSHELL
OriginalFilename: PowerShell.EXE.MUI
ProductVersion: 10.0.14393.0
Debug: False
Patched: False
PreRelease: False
PrivateBuild: False
SpecialBuild: False
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:
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[]>)
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:
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
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
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.
PowerShell
Output
Chocolate
Vanilla
Strawberry-Blueberry
<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"
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.
"SimpleMatch [,IgnoreCase]"
[,IgnorePatternWhitespace] [,ExplicitCapture]
[,Singleline | ,Multiline]"
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
Use one of the following patterns to split more than one string:
a b
PS> -split $a
Examples
The following statement splits the string at whitespace.
PowerShell
Output
Windows
PowerShell
2.0
Windows
PowerShell
with
remoting
PowerShell
Output
Mercury
Venus
Earth
Mars
Jupiter
Saturn
Uranus
Neptune
Output
cury,Venus,Earth,Mars,Jupit
,Saturn,Uranus,Neptune
PowerShell
Output
Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,
eptune
PowerShell
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
PowerShell
Output
c,d,e,f,g,h
PowerShell
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 = @'
'@
Output
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
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
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
Output
LastName, FirstName
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.
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>}
Syntax
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.
Syntax
or
Syntax
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 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.
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."}
4 {"It is four."}
3 {"Three again."}
Output
It is three.
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)
3 {"Three again."}
Output
It is four.
$test = @{
Test = 'test'
Test2 = 'test2'
$test.ToString()
'System.Collections.Hashtable'
'test'
'Hashtable value'
Output
System.Collections.Hashtable
PowerShell
switch ("fourteen")
By adding the default clause, you can perform an action when no other
conditions
succeed.
PowerShell
switch ("fourteen")
Default {
"No matches"
Output
No matches
For the word "fourteen" to match a case you must use the -Wildcard or
-Regex
parameter.
PowerShell
Output
PowerShell
$target = 'https://bing.com'
Output
PowerShell
switch ("Test")
"Found a string"
"Test" {
Output
Found a string
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
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)
{$_ % 2} {
"$_ is Odd"
"$_ 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.
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:
When you press the Tab key, the command expands to:
PSReadLine also has a menu completion feature. The default key binding on
Windows is
Ctrl + Space .
PS> fore<Ctrl-Space>
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 <<<<
+ FullyQualifiedErrorId : ScriptHalted
Throwing a string
The optional expression in a throw statement can be a string, as shown in the
following
example:
PowerShell
Output
This is an error.
At line:1 char:6
untimeException
PowerShell
Output
At line:1 char:6
erShell):Process) [],
RuntimeException
You can use the TargetObject property of the ErrorRecord object in the
$Error
automatic variable to examine the error.
PowerShell
$Error[0].TargetObject
Output
PowerShell
throw $formatError
Output
At line:1 char:6
format.
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.
TRANSACTION CMDLETS
PowerShell includes several cmdlets designed for managing transactions.
PowerShell
get-command *transaction
PowerShell
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.
PowerShell
For more information about a provider, see the Help for the provider. To get
provider
Help, type:
get-help <provider-name>
get-help registry
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.
PowerShell
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.
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.
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.
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.
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".
PowerShell
start-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
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
0 0 MyCompany {}
PowerShell
complete-transaction
PowerShell
dir m*
Output
Hive: HKEY_CURRENT_USER\software
83 1 Microsoft {(default)}
0 0 MyCompany {}
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
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
0 0 MyOtherCompany {}
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
83 1 Microsoft {(default)}
0 0 MyCompany {}
The following example shows how to use the Get-ChildItem command (the alias is
"dir")
to preview the changes in 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
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
83 1 Microsoft {(default)}
0 0 MyCompany {}
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
83 1 Microsoft {(default)}
0 1 MyCompany {MyKey}
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 MyCompany2
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
83 1 Microsoft {(default)}
0 0 MyCompany2 {}
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
83 1 Microsoft {(default)}
0 0 MyCompany1 {}
0 0 MyCompany2 {}
0 0 MyCompany3 {}
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.
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
Because the MyCompany key already exists in the registry, the command fails,
and the
transaction is rolled back.
Output
At line:1 char:9
A Get-Transaction command confirms that the transaction has been rolled back
and that
the SubscriberCount is 0.
Output
Error 0 RolledBack
PowerShell
In this case, when the command fails, the transaction is not automatically
rolled back.
PowerShell
Output
At line:1 char:9
Because the transaction is still active, you can resubmit the command as part
of the
transaction.
PowerShell
PowerShell
start-transaction
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
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
Output
PowerShell
PowerShell
complete-transaction
$t.tostring()
PowerShell
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
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
PowerShell
start-transaction
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
The MyCompany key does not exist in the registry, but this command succeeds
because
the two commands are part of the same transaction.
PowerShell
complete-transaction
Output
Error 1 Active
PowerShell
complete-transaction
Another Get-Transaction command shows that the transaction has been committed.
Output
RollbackPreference SubscriberCount Status
Error 0 Committed
When you do, Start-Transaction creates a new transaction object and makes the
new
transaction the active transaction.
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
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
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
PowerShell
get-transaction
Output
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
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
PowerShell
get-transaction
Output
Error 1 Active
PowerShell
complete-transaction
PowerShell
dir m*
Output
Hive: HKEY_CURRENT_USER\Software
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.
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
Display the error and abort execution of the script or function containing
the trap
using break 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
A script or command can have multiple trap statements. trap statements can
appear
anywhere in the script or command.
PowerShell
In the following example, the function includes a nonsense string that causes
a runtime
error.
PowerShell
function TrapTest {
nonsenseString
TrapTest
Output
Error found.
At line:3 char:5
+ nonsenseString
+ ~~~~~~~~~~~~~~
+ FullyQualifiedErrorId : CommandNotFoundException
The following example includes a trap statement that displays the error by
using the $_
automatic variable:
PowerShell
function TrapTest {
nonsenseString
TrapTest
Output
At line:3 char:5
+ nonsenseString
+ ~~~~~~~~~~~~~~
+ FullyQualifiedErrorId : CommandNotFoundException
) Important
trap statements may be defined anywhere within a given script block, but
always
The following example is a trap statement that traps the specific error
CommandNotFoundException:
PowerShell
trap [System.Management.Automation.CommandNotFoundException]
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
PowerShell uses .NET exception types. The following example specifies the
System.Exception error type:
PowerShell
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 [System.Management.Automation.CommandNotFoundException] {
nonsenseString
Output
At C:\Temp\traptest.ps1:5 char:1
+ nonsenseString
+ ~~~~~~~~~~~~~~
+ FullyQualifiedErrorId : CommandNotFoundException
The following script example contains the same trap statements with a
different error:
PowerShell
trap [System.Management.Automation.CommandNotFoundException]
1/$null
Output
At C:\temp\traptest.ps1:4 char:1
+ 1/$null
+ ~~~~~~~
+ FullyQualifiedErrorId : RuntimeException
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
1/$x
'after division'
'after loop'
Output
0.333333333333333
after division
0.5
after division
after division
An error occurred!
At line:3 char:4
+ 1/$x
+ ~~~~
+ 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.
PowerShell
function function1 {
NonsenseString
function1
Output
An error:
At line:3 char:5
+ NonsenseString
+ ~~~~~~~~~~~~~~
+ FullyQualifiedErrorId : CommandNotFoundException
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
Output
An error:
At C:\temp\traptest.ps1:2 char:5
+ NonsenseString
+ ~~~~~~~~~~~~~~
+ 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
) Important
PowerShell
function break_example {
trap {
"Error trapped"
break
1/$null
"Function completed."
break_example
Output
Error trapped
At line:6 char:5
+ 1/$null
+ ~~~~~~~
+ 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.
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.
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,
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.
PowerShell
PowerShell
Error types appear in brackets. The outermost brackets indicate the element is
optional.
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.
PowerShell
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.
Catching errors
The following sample script shows a try block with a catch block:
PowerShell
try { NonsenseString }
The catch keyword must immediately follow the try block or another catch
block.
PowerShell
An error occurred.
PowerShell
try {
$wc.DownloadFile("http://www.contoso.com/MyDoc.doc","c:\temp\MyDoc.doc")
catch [System.Net.WebException],[System.IO.IOException] {
catch {
PowerShell
catch [System.Management.Automation.CommandNotFoundException]
{"Inherited Exception" }
PowerShell
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
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.
PowerShell
try { NonsenseString }
catch {
Write-Host $_
Output
An Error occurred:
was included, verify that the path is correct and try again.
PowerShell
try { NonsenseString }
catch {
Write-Host $_.ScriptStackTrace
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.
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.
PowerShell
(Get-Date).DateTime
Output
The Types.ps1xml files that modules export are loaded when the module
is
imported into the current session.
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.
For more information about these cmdlets, see the help topic for each cmdlet.
XML
<Type>
<Name>System.Array</Name>
<Members>
<AliasProperty>
<Name>Count</Name>
<ReferencedMemberName>
Length
</ReferencedMemberName>
</AliasProperty>
</Members>
</Type>
PowerShell
Output
# ...
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
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.
XML
<Types>
<Type>
<Name>System.IO.FileInfo</Name>
<Members>
<ScriptProperty>
<Name>Age</Name>
<GetScriptBlock>
((Get-Date) - ($this.CreationTime)).Days
</GetScriptBlock>
</ScriptProperty>
</Members>
</Type>
</Types>
PowerShell
PowerShell
Output
142
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.
<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.
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.
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.
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>
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.
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.
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.
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.
XML
<Type>
<Name>System.IO.FileInfo</Name>
<Members>
<ScriptProperty>
<Name>VersionInfo</Name>
<GetScriptBlock>
[System.Diagnostics.FileVersionInfo]::GetVersionInfo($this.FullName)
</GetScriptBlock>
</ScriptProperty>
</Members>
</Type>
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.
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
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.
-is |Returns TRUE when the input is an instance of the specified .NET type.
PowerShell
-isnot |Returns TRUE when the input not an instance of the specified.NET type.
PowerShell
PowerShell
PowerShell
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 .
PowerShell
True
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.GetType().FullName
System.IO.DirectoryInfo
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> [datetime]'05/13/20'
PS> [datetime]'13/05/20'
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
False
True
True
False
True
True
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.
PowerShell
True
False
True
$_ -is [System.Globalization.CultureInfo])
True
True
True
PowerShell
False
The following example shows that when the -as operator cannot convert the
input
object to the .NET type, it returns $null .
PowerShell
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.
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
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
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
type: Update-Help.
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
PowerShell
(Get-Command Set-ExecutionPolicy).ModuleName
PowerShell
For example, to update help for the module that contains the
Set-ExecutionPolicy
cmdlet, type:
PowerShell
Update-Help -Module Microsoft.PowerShell.Security
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.
The Update-Help cmdlet does all of the hard work for you, including the
following tasks.
To install or update help for all modules on the computer that supports
Updatable Help,
type:
PowerShell
Update-Help
PowerShell
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.
Save-Help compares the help files in the specified directory to the newest
help files that
For example, to save help for all installed modules to the \\Server\Share
directory, type:
PowerShell
PowerShell
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.
PowerShell
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
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
In the following example, the administrator installs help for the DHCP Server
module on
a computer that does not have network access.
PowerShell
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
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
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.
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
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
7 Note
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.
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.
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.
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).
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 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:
Module syntax
To load classes from a PowerShell module:
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.
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:
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
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
[string]$algorithm = "SHA256"
[byte[]]$stringbytes = [UnicodeEncoding]::Unicode.GetBytes($string)
[Stream]$memorystream = [MemoryStream]::new($stringbytes)
-Algorithm $algorithm
$hashfromstream.Hash.ToString()
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
[Deck]$deck = [Deck]::new()
$deck.Shuffle()
[Card[]]$hand1 = $deck.Deal(5)
[Card[]]$hand2 = $deck.Deal(5)
[Card[]]$hand3 = $deck.Deal(5)
PowerShell
$yamlSerializer = [Serialization.Serializer]::new()
$info = [ordered]@{
Inventory = @(
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.
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.
session history.
For example:
PowerShell
$MyVariable = 1, 2, 3
$Path = "C:\Windows\System32"
For example:
PowerShell
$Processes = Get-Process
$Today = (Get-Date).DateTime
For example:
PowerShell
$MyVariable
Output
1
PowerShell
$Today
Output
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
Output
PowerShell
PowerShell
$MyVariable = $null
PowerShell
PowerShell
PowerShell
$a = $b = $c = 0
PowerShell
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
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 = "Hello"
Output
At line:1 char:1
+ $number = "Hello"
+ ~~~~~~~~~~~~~~~~~
ArgumentTransformationMetadataException
+ FullyQualifiedErrorId : RuntimeException
PowerShell
[string]$words = "Hello"
$words
Output
210
PowerShell
$dates
Output
PowerShell
$dates
Output
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.
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
Output
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:
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
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}
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}
Output
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.
To create the variable in every PowerShell session that you start, add the
variable 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.
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
about_Environment_Provider
about_Variable_Provider
about_Function_Provider
about_Alias_Provider
PowerShell
PowerShell
Get-Help <cmdlet-name>
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 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.
MyInvocation
PSCommandPath
PSScriptRoot
PSBoundParameters
args
input
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.
PowerShell
PowerShell
$variable:home
PowerShell
PowerShell
Get-ChildItem -Literalpath ?
PowerShell
Creating variables
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
PowerShell
Changing variables
Rename a variable
This command uses the Rename-Item cmdlet to change the name of the a
variable to
processes .
PowerShell
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
Delete a variable
This command deletes the serv variable from the current session. You can use
this
command in any PowerShell drive.
PowerShell
PowerShell
PowerShell
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
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.
PowerShell
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.
PowerShell
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
?n matches an , in , and on
?n doesn't match ran
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
PowerShell
$p = Get-ComputerRestorePoint
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 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.
PowerShell Editions
Starting with version 5.1, PowerShell is available in different editions which denote
varying feature sets and platform compatibility.
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.
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.
Test-FileCatalog
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.
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
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.
In WMF 5.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.
Windows PowerShell ISE introduces two new features in Windows PowerShell 4.0.
IntelliSense support has been added for Windows PowerShell Desired State
Configuration providers and configurations.
In Windows Server 2012 R2 and Windows Server 2012, in Server Manager, on the
Tools menu, click Windows PowerShell ISE.
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
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.
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.
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.
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.
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.
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.
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.
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
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
PowerShell
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
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
PowerShell
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:
Cmdlet Description
Cmdlet Description
SAMPLE COMMANDS
The following command displays the BIOS information for the local computer.
PowerShell
The following command displays information about the WinRM service for three
remote
computers.
PowerShell
PowerShell
C:\PS> notepad.exe
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.
[WMICLASS] - A shortcut for accessing the static properties and methods of a class.
For example:
PowerShell
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
CIM_ManagedSystemElement}
__SERVER : SERVER01
__NAMESPACE : ROOT\cimv2
__PATH : \\SERVER01\ROOT\cimv2:Win32_Process
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.
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:
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:
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.
For example, the following Select statement selects all properties (*) from
the instances
of the Win32_Bios WMI class.
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.
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.
PowerShell
Output
Manufacturer : LENOVO
SerialNumber : R9FPY3P
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
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
Output
__GENUS : 2
__CLASS : Win32_BIOS
__SUPERCLASS :
__DYNASTY :
__RELPATH :
__PROPERTY_COUNT : 1
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH :
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
Output
__GENUS : 2
__CLASS : Win32_BIOS
__SUPERCLASS :
__DYNASTY :
__RELPATH :
__PROPERTY_COUNT : 1
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH :
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
Manufacturer : LENOVO
SerialNumber : R9FPY3P
Microsoft.Management.Infrastructure.CimInstance
System.Management.ManagementObject
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.Get()
Output
Manufacturer : LENOVO
SerialNumber : R9FPY3P
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
$bios.Get()
Output
Manufacturer : LENOVO
SerialNumber : R9FPY3P
When you use the [wmisearcher] type accelerator, it changes the query string
into a
ManagementObjectSearcher object, as shown in the following commands.
$a.GetType().FullName
System.String
$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 :
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
Output
__GENUS : 2
__CLASS : Win32_BIOS
__SUPERCLASS :
__DYNASTY :
__RELPATH :
__PROPERTY_COUNT : 1
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH :
For example:
The Where statement is used with the Select statement, as shown in the
following
example.
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
However, the following command fails, because the process name includes the
".exe" file
name extension.
PowerShell
-----------------------
= Equal
!= Not equal
IS Evaluates null
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
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
Output
Name ProcessID
---- ---------
SROSVC.exe 4220
WINWORD.EXE 4664
TscHelp.exe 4744
SnagIt32.exe 4748
WmiPrvSE.exe 5056
--------------------------------------------------
_ One character.
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.
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
Output
Name ProcessID
---- ---------
notepad.exe 1740
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
The following command gets processes whose names do not begin with any of the
following letters: A, S, W, P, R, C, U, N
PowerShell
PowerShell
Output
Name ProcessID
---- ---------
calc.exe 4424
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
Output
Name ProcessID
---- ---------
calc.exe 4424
PowerShell
$query = "Select * from win32_Process where name LIKE 'WLIDSVC.exe'"
```powershell
```output
Name ProcessID
---- ---------
WLIDSVC.exe 84
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
" 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
For example, the following commands get processes that have a name of
"Winword.exe"
and the process ID of 6512.
PowerShell
Get-CimInstance -Query $q
Output
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.
PowerShell
Get-CimInstance -Query $q
Output
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
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
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
The following WQL query returns only local user accounts from a domain joined
computer.
PowerShell
Get-CimInstance -Query $q
PowerShell
Get-CimInstance -Query $q
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
Output
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
Get-CimInstance -Query $q
Output
At line:1 char:1
+ Get-CimInstance -Query $q
+ ~~~~~~~~~~~
PowerShell
Get-CimInstance -Query $q
See also
about_Special_Characters
about_Quoting_Rules
about_WMI
about_WMI_Cmdlets
Add-History
Reference
Module: Microsoft.PowerShell.Core
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
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
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.
PowerShell
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
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 .
PowerShell
$a = Import-Csv c:\testing\history.csv
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
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
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
-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
Inputs
HistoryInfo
Outputs
None
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
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
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
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.
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
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
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
Inputs
None
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.
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
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.
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
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.
PowerShell
Get-History
Id CommandLine
-- -----------
1 Set-Location C:\Test\
2 Get-Command Clear-History
5 Get-Help Get-Alias
7 Get-Help Clear-History
8 Set-Location C:\Test\Logs
9 Get-Help Get-Variable
10 Get-Help Get-ChildItem
Get-History
Id CommandLine
-- -----------
1 Set-Location C:\Test\
2 Get-Command Clear-History
5 Get-Help Get-Alias
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.
PowerShell
Get-History
Id CommandLine
-- -----------
1 Set-Location C:\Test\
2 Get-Command Clear-History
5 Get-Help Get-Alias
7 Get-Help Clear-History
Get-History
Id CommandLine
-- -----------
1 Set-Location C:\Test\
2 Get-Command Clear-History
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.
PowerShell
Get-History
Id CommandLine
-- -----------
1 Set-Location C:\Test\
2 Get-History
3 Get-Help Get-Alias
4 Get-Command Clear-History
Clear-History -Id 3, 5
Get-History
Id CommandLine
-- -----------
1 Set-Location C:\Test\
2 Get-History
4 Get-Command Clear-History
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
5 Get-Help Get-Alias
7 Get-Help Clear-History
8 Set-Location C:\Test\Logs
9 Get-Help Get-Variable
10 Get-Help Get-ChildItem
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
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
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-Id
Type: Int32[]
Position: 0
-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
-WhatIf
Shows what would happen if the Clear-History cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
None
Outputs
None
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
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
0 0 0 24 0 0 Idle
...
PS C:\> cls
#After
PS C:>
This command uses the cls alias of Clear-Host to clear the current display.
Inputs
None
Outputs
None
Notes
Windows PowerShell includes the following aliases for Clear-Host :
clear
cls
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
Examples
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.
Get-PSSession
Get-PSSession | Disconnect-PSSession
Get-PSSession | Connect-PSSession
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.
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
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
-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
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
-Authentication
Default
Basic
Credssp
Digest
Kerberos
Negotiate
NegotiateWithImplicitCredential
U Caution
Type: AuthenticationMechanism
Position: Named
-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.
Type: String
Position: Named
-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
-ConfigurationName
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.
Type: String
Position: Named
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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>
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.
Type: Uri[]
Aliases: URI, CU
Position: 0
-Credential
Specifies a user account that has permission to connect to the disconnected session.
The default is
the current user.
7 Note
Type: PSCredential
Position: Named
-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
-InstanceId
Type: Guid[]
Position: Named
-Name
Type: String[]
Position: Named
-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:
<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
-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
-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,
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
-ThrottleLimit
The throttle limit applies only to the current command, not to the session or to the
computer.
Type: Int32
Position: Named
-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
-WhatIf
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
PSSession
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
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.
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
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
PowerShell
Debug-Job -ID 3
At C:\TestWFDemo1.ps1:8 char:5
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3:
4: workflow SampleWorkflowTest
5: {
6: param ($MyOutput)
7:
10:
13:
15: }
16:
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-InstanceId
Type: Guid
Position: 0
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
-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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
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
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.
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
PowerShell
Disable-PSRemoting
WARNING: Disabling the session configurations does not undo all the changes
made by the Enable-PSRemoting
steps:
PowerShell
Disable-PSRemoting -Force
WARNING: Disabling the session configurations does not undo all the changes
made by the Enable-PSRemoting
steps:
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
WARNING: Disabling the session configurations does not undo all the changes
made by the Enable-PSRemoting
At line:1 char:1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError:
(System.Management.A\u2026tion.RemoteRunspace:RemoteRunspace)
[New-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionOpenFailed
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
Enable-PSRemoting -Force
Name Permission
---- ----------
Name Permission
---- ----------
PowerShell
Disable-PSRemoting -Force
WARNING: Disabling the session configurations does not undo all the changes
made by the Enable-PSRemoting
At line:1 char:1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError:
(System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession],
PSRemotin
gTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionOpenFailed
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:
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.
PowerShell
Disable-PSRemoting -Force
Name Permission
---- ----------
DOMAIN01\User01 AccessAllowed
WARNING: Disabling the session configurations does not undo all the changes
made by the Enable-PSRemoting
Name Permission
---- ----------
+ CategoryInfo : OpenError:
(System.Manageme....RemoteRunspace:RemoteRunspace) [],
PSRemotingTransportException
+ FullyQualifiedErrorId : PSSessionOpenFailed
PowerShell
Disable-PSRemoting -Force
WARNING: Disabling the session configurations does not undo all the changes
made by the Enable-PSRemoting
Name Permission
---- ----------
Name Permission
---- ----------
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
Default value: False
-Force
Type: SwitchParameter
Position: Named
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
None
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.
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
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.
PowerShell
Disable-PSSessionConfiguration
PowerShell
Disable-PSSessionConfiguration -Name *
PowerShell
PowerShell
PowerShell
Name Permission
---- ----------
MaintenanceShell BUILTIN\Administrators AccessAllowed
Name Permission
---- ----------
MaintenanceShell Everyone AccessDenied, BUILTIN\Administrators
AccessAllowed
+ 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
-Force
Type: SwitchParameter
Position: Named
-Name
Type: String[]
Position: 0
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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
Microsoft.PowerShell.Commands.PSSessionConfigurationCommands
String
You can pipe a string that contains the name of a session configuration to this cmdlet.
Outputs
None
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
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.
Examples
PowerShell
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.
PowerShell
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
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
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.
PowerShell
idle timeout value 172800(seconds) is either greater than the server maximum
allowed
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
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> $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 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
-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
-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
-InstanceId
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
-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
-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.
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
-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
-ThrottleLimit
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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Default value: False
Inputs
PSSession
Outputs
PSSession
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.
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
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.
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
PowerShell
Enable-PSRemoting
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
Name
----
WINRM-HTTP-In-TCP-NoScope
WINRM-HTTP-In-TCP
WINRM-HTTP-Compat-In-TCP-NoScope
WINRM-HTTP-Compat-In-TCP
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 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
Type: SwitchParameter
Aliases: cf
Position: Named
-Force
Type: SwitchParameter
Position: Named
-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
-WhatIf
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
None
Outputs
String
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 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.
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
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-
PowerShell
Enable-PSSessionConfiguration
PowerShell
PowerShell
Enable-PSSessionConfiguration -Name *
Get-PSSessionConfiguration | Enable-PSSessionConfiguration
PowerShell
$sddl = "O:NSG:BAD:P(A;;GXGWGR;;;BA)(A;;GAGR;;;S-1-5-21-123456789-188441444-
3100496)S:P"
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-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 .
Type: String[]
Position: 0
-NoServiceRestart
Type: SwitchParameter
Position: Named
-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
-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 .
Type: SwitchParameter
Position: Named
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
String
You can pipe a string that contains the name of a session configuration to this cmdlet.
Outputs
None
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
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 .
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.
Examples
PowerShell
PS C:\> Enter-PSHostProcess -Name powershell_ise
PowerShell
MyModuleWorkflowF1 {}
TestNoFile3.psm1: line 6
WFTest1 {}
TestNoFile2.ps1: line 14
TestNoFile2.ps1 {}
TestNoFile2.ps1: line 22
At C:\TestWFVar1.ps1:83 char:1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
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:1520]: PS C:\>
PS C:\>
Parameters
-AppDomainName
Type: String
Position: 1
-HostProcessInfo
Type: PSHostProcessInfo
Position: 0
-Id
Specifies a process by the process ID. To get a process ID, run the Get-Process
cmdlet.
Type: Int32
Position: 0
-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
-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
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
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-
To end the interactive session and disconnect from the remote computer, use the Exit-
PSSession
cmdlet, or type exit .
Examples
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.
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
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
[Server01]: PS C:\>
PS C:\>
At line:1 char:4
This command shows how to work in an interactive session with a remote computer.
[Server01]: PS>
These commands use the Session parameter of Enter-PSSession to run the interactive
session in
an existing PowerShell session (PSSession).
[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.
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
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
-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 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
-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
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
Position: Named
-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.
Type: String
Position: Named
-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 .
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
-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.
Position: Named
-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>
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.
Type: Uri
Aliases: URI, CU
Position: 1
-ContainerId
Position: 0
-Credential
Specifies a user account that has permission to perform this action. The default is the
current
user.
7 Note
Type: PSCredential
Position: 1
-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.
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.
Type: SwitchParameter
Position: Named
-Id
Specifies the ID of an existing session. Enter-PSSession uses the specified session for
the
interactive session.
Type: Int32
Position: 0
-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
-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
-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:
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
-RunAsAdministrator
Type: SwitchParameter
Position: Named
-Session
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
-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,
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
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.
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
-VMId
Type: Guid
Aliases: VMGuid
Position: 0
-VMName
Type: String
Position: 0
Inputs
String
PSSession
Outputs
None
Notes
Windows PowerShell includes the following aliases for Enter-PSSession :
etsn
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.
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
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
Examples
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
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
Server01\PS> Exit-PSSession
PS C:\>
These commands start and then stop an interactive session with the Server01 remote
computer.
Server01\PS> Exit-PSSession
PS C:\> $s
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 final command displays the PSSession in the $s variable. The State property shows
the
PSSession is still open and available for use.
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
Notes
Windows PowerShell includes the following aliases for Exit-PSSession :
exsn
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
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.
Examples
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.
Add-PSSnapin NewPSSnapin
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
<PSConsoleFile ConsoleSchemaVersion="1.0">
<PSVersion>2.0</PSVersion>
<PSSnapIns>
</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.
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 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 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
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-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
-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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
String
Outputs
FileInfo
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,
To use a Windows PowerShell console file in a new session, use the following
syntax to start
Windows PowerShell:
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
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.
Examples
This command exports all the functions and aliases defined in the script module.
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.
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.
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.
# From TestModule.psm1
function New-Test
function Validate-Test
function Start-Test
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.
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
-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
-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
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
Inputs
String
Outputs
None
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
Related Links
Get-Module
Import-Module
Remove-Module
about_Modules
ForEach-Object
Reference
Module: Microsoft.PowerShell.Core
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.
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.
Examples
PowerShell
29.296875
55.466796875
12.140625
Get-ChildItem $PSHOME |
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.
PowerShell
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.
PowerShell
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).
PowerShell
Hello
Hello
Hello
Hello
PowerShell
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.
PowerShell
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.
begin
process
process
PowerShell
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.
PowerShell
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.
Type: Object[]
Aliases: Args
Position: Named
-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
-Confirm
Prompts you for confirmation before running the cmdlet.
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-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
-MemberName
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.
Type: String
Position: 0
-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
-RemainingScripts
Specifies all script blocks that are not taken by the Process parameter.
Type: ScriptBlock[]
Position: Named
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
PSObject
Outputs
PSObject
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
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
PowerShell
Get-Command
PowerShell
Get-Command -ListImported
PowerShell
PowerShell
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
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.
PowerShell
function Get-DynamicParameters
ForEach-Object {$_.Parameters} |
Where-Object { $_.IsDynamic } |
Name
----
CodeSigningCert
PowerShell
Get-Command *
PowerShell
You can use a command like this one to find cmdlets that let you specify the method
that is used to
authenticate the user.
PowerShell
CommandType Name
ModuleName
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.
PowerShell
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.
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
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.
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.
Type: SwitchParameter
Position: Named
-ArgumentList
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
-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.
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 * .
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
Position: Named
-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.
Type: ModuleSpecification[]
Position: Named
-ListImported
Indicates that this cmdlet gets only commands in the current session.
Type: SwitchParameter
Position: Named
-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
-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
-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
-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.
Type: String[]
Position: Named
-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.
Type: PSTypeName[]
Position: Named
Type: SwitchParameter
Position: Named
-Syntax
Indicates that this cmdlet gets only the following specified data about the command:
Type: SwitchParameter
Position: Named
-TotalCount
Specifies the number of commands to get. You can use this parameter to limit the
output of a
command.
Type: Int32
Position: Named
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
Inputs
String
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
CmdletInfo
Represents cmdlets.
FunctionInfo
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.
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
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 .
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
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.
Examples
PowerShell
Get-Help Format-Table
Format-Table -?
Get-Help <cmdlet-name> is the simplest and default syntax of Get-Help cmdlet. You can
omit the
Name parameter.
PowerShell
help Format-Table
man Format-Table
help is a function that runs Get-Help cmdlet internally and displays the result one page
at a
time.
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.
PowerShell
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.
PowerShell
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.
PowerShell
PowerShell
Get-Help
PowerShell
Get-Help *
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_*
PowerShell
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.
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
Install-PowerShellRemoting.ps1 External
Install-PowerShellRemoting.ps1
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
NAME
Get-Item
SYNOPSIS
Gets a collection of Server objects for the local computer and any
computers
...
Set-Location SQLSERVER:\DataCollection
NAME
Get-Item
SYNOPSIS
Gets a collection of Server objects for the local computer and any
computers
...
PowerShell
Parameters
-Category
Displays help only for items in the specified category and their aliases. Conceptual
articles are in
the HelpFile category.
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
-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
-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
-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
-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
-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
-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.
Type: String
Position: 0
-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
-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
-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.
Type: String
Position: Named
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
-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.
Type: SwitchParameter
Position: Named
Inputs
None
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
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
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:
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
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.
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
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.
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
PowerShell
Get-History
PowerShell
PowerShell
PowerShell
Get-History -Count 1
PowerShell
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
-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
Inputs
Int64
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.
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.
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
PowerShell
PS C:\> Get-Job
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:\> $ID
Guid
----
03c3232e-1d23-453b-a6f4-ed73c9e29d55
PowerShell
PowerShell
PowerShell
PowerShell
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:\> $j
...
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:\> Get-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
Reason :
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 :
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
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
Access is denied.
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.
Type: DateTime
Position: Named
-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.
Type: DateTime
Position: Named
-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.
Type: JobState
Position: Named
-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
-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.
Type: Hashtable
Position: 0
-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 .
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 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
-Id
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
-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.
Type: SwitchParameter
Position: Named
-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
-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
-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.
Type: Int32
Position: Named
-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
Type: JobState
Position: 0
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.
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
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
Get-Module
This command gets modules that have been imported into the current session.
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
$FullyQualifiedName =
@{ModuleName="Microsoft.PowerShell.Management";ModuleVersion="3.1.0.0"}
Name Version
---- -------
Microsoft.PowerShell.Management 3.1.0.0
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.
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.
Name: AppLocker
AppLocker Manifest
C:\Windows\system32\WindowsPowerShell\v1.0\Modules\AppLocker\AppLocker.psd1
Name: Appx
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
BestPractices Manifest
C:\Windows\system32\WindowsPowerShell\v1.0\Modules\BestPractices\BestPractic
es.psd1
Name: BitsTransfer
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.
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
# Second command
Get-Content $m.Path
@ {
GUID = "{8FA5064B-8479-4c5c-86EA-0D311FE48875}"
ModuleVersion = "1.0.0.0"
CLRVersion = "2.0"
NestedModules =
"Microsoft.BackgroundIntelligentTransfer.Management"
FormatsToProcess = "FileTransfer.Format.ps1xml"
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.
Directory: C:\Windows\system32\WindowsPowerShell\v1.0\Modules\FileTransfer
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.
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.
PowerShell
Get-Command Get-Disk
Get-Disk
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
-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.
Position: Named
-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.
Type: Uri
Position: Named
-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
-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.
Type: ModuleSpecification[]
Position: Named
-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
Type: SwitchParameter
Position: Named
-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.
Type: String[]
Position: 0
-PSEdition
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
Type: String
Position: Named
-PSSession
When the session is connected to a remote computer, you must specify the
ListAvailable
parameter.
Type: PSSession
Position: Named
-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.
Type: SwitchParameter
Position: Named
Inputs
String
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.
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
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
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.
Examples
Parameters
-Id
Specifies a process by the process ID. To get a process ID, run the Get-Process
cmdlet.
Type: Int32[]
Position: 0
-Name
Specifies a process by the process name. To get a process name, run the Get-Process
cmdlet.
Type: String[]
Position: 0
-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
Inputs
Process
Outputs
PSHostProcessInfo
Related Links
Get-Process
Get-PSSession
Reference
Module: Microsoft.PowerShell.Core
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 remaining parameters to configure the temporary connection in which the Get-
PSSession
command runs when you use the ComputerName or ConnectionUri
parameters.
7 Note
Examples
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.
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.
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
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.
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
$s
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
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.
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
This parameter configures the temporary connection that is created to run a Get-
PSSession command
with the ConnectionUri parameter.
Type: SwitchParameter
Position: Named
-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
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
-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.
Default
Basic
CredSSP
Digest
Kerberos
Negotiate
NegotiateWithImplicitCredential .
U Caution
Type: AuthenticationMechanism
Position: Named
-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.
Type: String
Position: Named
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.
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
-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
-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.
<Transport>://<ComputerName>:<Port\>/<ApplicationName>
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.
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
-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
-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.
7 Note
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
-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.
Type: Int32[]
Position: 0
-InstanceId
Specifies an array of instance IDs of sessions. This cmdlet gets only the sessions with
the
specified instance IDs.
Type: Guid[]
Position: Named
-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
-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:
<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.
Type: Int32
Position: Named
-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,
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
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.
Type: SessionFilterState
Position: Named
-ThrottleLimit
Type: Int32
Position: Named
Default value: 32
-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.
Type: SwitchParameter
Position: Named
-VMId
Type: Guid[]
Aliases: VMGuid
Position: Named
-VMName
Type: String[]
Position: Named
Inputs
None
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.
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
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
Examples
This example returns the commands available to the user CONTOSO\User when
connecting to the
Endpoint1 constrained endpoint on the local computer.
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
-Full
Indicates that this cmdlet returns the entire initial session state for the specified user
at the
specified constrained endpoint.
Type: SwitchParameter
Position: Named
-Username
Type: String
Position: 1
Outputs
AliasInfo
FunctionInfo
InitialSessionState
Related Links
New-PSRoleCapabilityFile
Get-PSSessionConfiguration
Reference
Module: Microsoft.PowerShell.Core
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.
Examples
Example 1 - Get session configurations on the local
computer
PowerShell
Get-PSSessionConfiguration
PowerShell
microsoft.powershell 5.1
BUILTIN\Administrators AccessAll...
microsoft.powershell32 5.1
BUILTIN\Administrators AccessAll...
PowerShell
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.
PowerShell
dir wsman:\localhost\plugin
Container {Name=microsoft.powershell.workf...
microsoft.powershell.workflow
PowerShell
dir WSMan:\Server01\Plugin
WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Plugin
Container {Name=microsoft.powershell.workf...
microsoft.powershell.workflow
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.
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
Connect-WSMan Server02
microsoft.powershell 5.1
BUILTIN\Administrators AccessAll... server02.corp.fabrikam.com
microsoft.powershell32 5.1
BUILTIN\Administrators AccessAll... server02.corp.fabrikam.com
PowerShell
http://schemas.microsoft.com/powershell/microsoft.CustomShell
Parameters
-Force
Suppresses the prompt to restart the WinRM service, if the service is not already
running.
Type: SwitchParameter
Position: Named
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
Inputs
None
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.
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
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.
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
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.
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.
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
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
Inputs
None
Outputs
PSSnapInInfo
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
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
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
Verb Group
---- -----
Block Security
Grant Security
Protect Security
Revoke Security
Unblock Security
Unprotect Security
Gets only the specified verbs. Enter the name of a verb or a name pattern. Wildcards
are allowed.
Type: String[]
Position: 1
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.
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
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
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
PowerShell
PowerShell
PowerShell
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.
PowerShell
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.
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
(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
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.
PowerShell
Get-Command gets the members that have been imported from the module. The output
shows that the
module members were correctly prefixed.
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
Name ModuleType
---- ----------
Show-Calendar Script
BitsTransfer Manifest
PSDiagnostics Manifest
TestCmdlets Script
...
$a | Get-Member
TypeName: System.Management.Automation.PSCustomObject
$a."Show-Calendar"()
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.
PowerShell
Import-Module PSDiagnostics
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.
PowerShell
Get-Date
Import-Module TestModule
Get-Date
19227
Microsoft.PowerShell.Utility\Get-Date
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.
PowerShell
PowerShell
Name Version
---- -------
PowerShellGet 2.2.1
PowerShellGet 2.1.3
PowerShellGet 2.1.2
PowerShellGet 1.0.0.1
PowerShell
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
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
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
DisplayName Name
----------- ----
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.
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
# Importing a CIM module, converts the CDXML files for each command into
PowerShell scripts.
Get-Command Get-Disk
# Use implicit remoting to query disks on the remote computer from which the
module was imported.
Get-Disk
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
-ArgumentList
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
-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
-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
-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.
Type: String
Position: Named
-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.
Type: Uri
Position: Named
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.
Type: CimSession
Position: Named
-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
-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:
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
-Force
This parameter causes a module to be loaded, or reloaded, over top of the current
one.
Type: SwitchParameter
Position: Named
-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.
Type: ModuleSpecification[]
Position: 0
-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
-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.
Type: SwitchParameter
Position: Named
-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
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.
Type: Version
Aliases: Version
Position: Named
-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
-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
-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.
Type: SwitchParameter
Aliases: NoOverwrite
Position: Named
-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
-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.
Type: String
Position: Named
Default value: None
-PSSession
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.
Import-Module cannot import core PowerShell modules from another session. The
core PowerShell
modules have names that begin with Microsoft.PowerShell.
Type: PSSession
Position: Named
-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
-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.
Type: String
-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
Inputs
String
PSModuleInfo
Assembly
Outputs
None
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.
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.
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 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,
Related Links
about_Modules
Export-ModuleMember
Get-Module
New-Module
Remove-Module
Invoke-Command
Reference
Module: Microsoft.PowerShell.Core
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.
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.
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
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.
PowerShell
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.
PowerShell
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.
PowerShell
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 = {
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.
PowerShell
$parameters = @{
ConfigurationName = 'MySession.PowerShell'
Invoke-Command @parameters
PowerShell
(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.
PowerShell
$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
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.
PowerShell
}
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.
PowerShell
Get-Process 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.
PowerShell
$parameters = @{
ComputerName = 'Server01'
ScriptBlock = {
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.
PowerShell
$parameters = @{
ComputerName = 'Server01'
Invoke-Command @parameters
Directory: C:\Test
and
$args[1] array values. The ArgumentList passes the $args array values to the Get-
ChildItem
parameter positions for Path and Filter.
PowerShell
$parameters = @{
FilePath = 'C:\Scripts\Sample.ps1'
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.
PowerShell
$LiveCred = Get-Credential
$parameters = @{
ConfigurationName = 'Microsoft.Exchange'
ConnectionUri = 'https://ps.exchangelabs.com/PowerShell'
Credential = $LiveCred
Authentication = 'Basic'
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.
PowerShell
$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.
PowerShell
$parameters = @{
ConnectionUri = 'https://ps.exchangelabs.com/PowerShell'
AllowRedirection = $true
SessionOption = $max
Invoke-Command @parameters
PowerShell
$s = New-PSSession Server02
$parameters = @{
Session = $s
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.
PowerShell
$parameters = @{
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.
To get the results of commands and scripts that run in disconnected sessions, use the
Receive-PSSession cmdlet.
Parameters
-AllowRedirection
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
-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 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
-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
-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
-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.
Default
Basic
Credssp
Digest
Kerberos
Negotiate
NegotiateWithImplicitCredential
U Caution
Type: AuthenticationMechanism
Position: Named
-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.
Type: String
Position: Named
-ComputerName
Specifies the computers on which the command runs. 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, 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
-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.
Type: String
Position: Named
-ConnectionUri
Specifies a Uniform Resource Identifier (URI) that defines the connection endpoint of
the session.
The URI must be fully qualified.
<Transport>://<ComputerName>:<Port>/<ApplicationName>
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.
Type: Uri[]
Aliases: URI, CU
Position: 0
-ContainerId
Type: String[]
Position: Named
-Credential
Specifies a user account that has permission to perform this action. The default is the
current
user.
7 Note
Type: PSCredential
Position: Named
-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.
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 .
Type: SwitchParameter
Position: Named
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
-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
-InDisconnectedSession
You can't use InDisconnectedSession with the Session parameter or the AsJob
parameter.
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.
Type: SwitchParameter
Aliases: Disconnected
Position: Named
-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
-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.
Type: String
Position: Named
-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.
Position: Named
-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:
<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
-RunAsAdministrator
Type: SwitchParameter
Position: Named
Default value: False
-ScriptBlock
7 Note
Type: ScriptBlock
Aliases: Command
Position: 0
-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.
Type: PSSession[]
Position: 0
Default value: None
-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.
Type: String[]
Position: Named
-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
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
-ThrottleLimit
The throttle limit applies only to the current command, not to the session or to the
computer.
Type: Int32
Position: Named
Default value: 32
-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
-VMId
Type: Guid[]
Aliases: VMGuid
Position: 0
-VMName
Type: String[]
Position: Named
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.
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:
Name\>
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
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
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
PowerShell
7 Note
Pattern matching is case-insensitive, but the pattern matches the beginning of the
line.
PowerShell
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
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
String
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
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.
Examples
PowerShell
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 : {}
ExportedVariables : {}
NestedModules : {}
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 : {}
ExportedVariables : {}
NestedModules : {}
Get-Module
Get-Command Hello
PowerShell
$SayHelloHelp
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.
PowerShell
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 : {}
ExportedVariables : {}
NestedModules : {}
Get-Command hello
CommandType Name
Definition
----------- ----
----------
Function Hello
"Hello!"
The Get-Command cmdlet shows the Hello function that the dynamic module exports.
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 {
} -AsCustomObject
$m
$m | Get-Member
TypeName: System.Management.Automation.PSCustomObject
$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.
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
-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
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
-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
-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
-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
-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
Inputs
String
Outputs
PSModuleInfo
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
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
The output shows the default values of all keys in the manifest.
PowerShell
@{
# RootModule = ''
ModuleVersion = '1.0'
# Supported PSEditions
# CompatiblePSEditions = @()
GUID = '47179120-0bcb-4f14-8d80-f4560107f85c'
Author = 'ContosoAdmin'
CompanyName = 'Unknown'
# Description = ''
# PowerShellVersion = ''
# PowerShellHostName = ''
# PowerShellHostVersion = ''
# DotNetFrameworkVersion = ''
# CLRVersion = ''
# ProcessorArchitecture = ''
# RequiredModules = @()
# RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to
importing this module.
# ScriptsToProcess = @()
# TypesToProcess = @()
# FormatsToProcess = @()
# 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 = @()
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 = @()
# DscResourcesToExport = @()
# ModuleList = @()
# FileList = @()
PrivateData = @{
PSData = @{
# Tags = @()
# LicenseUri = ''
# ProjectUri = ''
# IconUri = ''
# ReleaseNotes = ''
# HelpInfoURI = ''
# Default prefix for commands exported from this module. Override the
default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''
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.
PowerShell
$moduleSettings = @{
HelpInfoUri = 'http://https://go.microsoft.com/fwlink/?LinkID=603'
Path = 'C:\ps-test\ManifestTest.psd1'
New-ModuleManifest @moduleSettings
PowerShell
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
AccessMode : ReadWrite
ClrVersion : 4.0
DotNetFrameworkVersion :
ExportedFunctions : {}
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.
Type: String[]
Position: Named
-Author
If you omit this parameter, New-ModuleManifest creates an Author key with the name
of the
current user.
Type: String
Position: Named
-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
-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.
Type: String[]
Position: Named
Default value: * (all)
-CompanyName
Type: String
Position: Named
-CompatiblePSEditions
Specifies the module's compatible PSEditions. For information about PSEdition, see
Modules with compatible PowerShell Editions.
Type: String[]
Position: Named
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
Default value: False
-Copyright
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
-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.
Type: String
Position: Named
-Description
Describes the contents of the module.
Type: String
Position: Named
-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
-DscResourcesToExport
Specifies the Desired State Configuration (DSC) resources that the module exports.
Wildcards are
permitted.
Type: String[]
Position: Named
-FileList
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
-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
-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
-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.
Type: Guid
Position: Named
-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.
Type: String
Position: Named
-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
-LicenseUri
Type: Uri
Position: Named
-ModuleList
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
-ModuleVersion
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
-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
-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
-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
-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.
Type: String
Position: Named
-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
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
-PrivateData
Type: Object
Position: Named
-ProcessorArchitecture
Specifies the processor architecture that the module requires. Valid values are x86,
AMD64, IA64,
MSIL, and None (unknown or unspecified).
Type: ProcessorArchitecture
Position: Named
-ProjectUri
Specifies the URL of a web page about this project.
Type: Uri
Position: Named
-ReleaseNotes
Type: String
Position: Named
-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
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.
Type: Object[]
Position: Named
-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
-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
-Tags
Type: String[]
Position: Named
-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
-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.
Type: String[]
Position: Named
-WhatIf
Shows what would happen if New-ModuleManifest runs. The cmdlet isn't run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
None
Outputs
None
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.
To add or change files in the $pshome\Modules directory, start PowerShell with the Run as
administrator option.
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
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.
Examples
PowerShell
PowerShell
$roleParameters = @{
Path = ".\Maintenance.psrc"
Author = "User01"
ModulesToImport = "Microsoft.PowerShell.Core"
VisibleCmdlets = "Restart-Service", @{
Name = "Restart-Computer"
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:
Type: IDictionary[]
Position: Named
-AssembliesToLoad
Specifies the assemblies to load into the sessions that use the role capability file.
Type: String[]
Position: Named
Type: String
Position: Named
-CompanyName
Type: String
Position: Named
-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
-Description
Position: Named
-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.
Type: IDictionary
Position: Named
-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
-FunctionDefinitions
Adds the specified functions to sessions that expose the role capability. Enter a hash
table with
the following keys:
For example:
@{Name="Get-PowerShellProcess";ScriptBlock={Get-Process
PowerShell};Options="AllScope"}
Type: IDictionary[]
Position: Named
-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
-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
-Path
Specifies the path and filename of the role capability file. The file must have a .psrc
filename
extension.
Type: String
Position: 0
-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
-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
-VariableDefinitions
Specifies variables to add to sessions that use the role capability file. Enter a hash
table with
the following keys:
Type: Object
Position: Named
-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
-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
-VisibleExternalCommands
Limits the external binaries, scripts and commands that can be executed in the
session to those
specified in the value of this parameter.
Type: String[]
Position: Named
-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
-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
Related Links
New-PSSessionConfigurationFile
Get-PSSessionCapability
New-PSSession
Reference
Module: Microsoft.PowerShell.Core
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
$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.
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.
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 ).
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.
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.
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.
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.
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.
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 .
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
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
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
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 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
-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
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
Position: Named
-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.
Type: String
Position: Named
-ComputerName
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,
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
-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.
Type: String
Position: Named
-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>
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.
Type: Uri[]
Aliases: URI, CU
Position: 0
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
-Credential
Specifies a user account that has permission to do this action. The default is the
current user.
7 Note
Type: PSCredential
Position: Named
-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.
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 .
Type: SwitchParameter
Position: Named
-Name
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
-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:
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
-RunAsAdministrator
Type: SwitchParameter
Position: Named
Default value: 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
-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
-ThrottleLimit
The throttle limit applies only to the current command, not to the session or to the
computer.
Type: Int32
Position: Named
-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
-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
-VMName
Use Get-VM to see the virtual machines that are available on your Hyper-V host.
Type: String[]
Position: Named
System.URI
PSSession
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
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.
For more information about session configurations and session configuration files, see
about_Session_Configurations and
about_Session_Configuration_Files.
Examples
PowerShell
+ FullyQualifiedErrorId : ScriptsNotAllowed
+ PSComputerName : localhost
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
Before
PowerShell
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:
PowerShell
notepad.exe $ITConfig.ConfigFilePath
True
PowerShell
$configSettings = @{
Path = '.\SampleFile.pssc'
SchemaVersion = '1.0.0.0'
Author = 'User01'
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
New-PSSessionConfigurationFile @configSettings
Get-Content SampleFile.pssc
@{
SchemaVersion = '1.0.0.0'
GUID = '1caeff7f-27ca-4360-97cf-37846f594235'
Author = 'User01'
SessionType = 'Default'
# TranscriptDirectory = 'C:\Transcripts\'
RunAsVirtualAccount = $true
ScriptsToProcess = 'Get-Inputs.ps1'
# User roles (security groups), and the role capabilities that should be
applied to them when applied to a session
LanguageMode = 'FullLanguage'
ExecutionPolicy = 'AllSigned'
PowerShellVersion = '3.0'
ModulesToImport = @{
'GUID' = '50cdb55f-5ab7-489f-9e94-4ec21ff51e59'
'ModuleName' = 'PSScheduledJob'
VisibleCmdlets = 'Get*'
VisibleFunctions = 'Get*'
AliasDefinitions = @{
'Name' = 'hlp'
'Options' = 'AllScope'
'Value' = 'Get-Help' }, @{
'Name' = 'Update'
'Options' = 'ReadOnly'
'Value' = 'Update-Help' }
FunctionDefinitions = @{
'Name' = 'Get-Function'
'Options' = 'ReadOnly'
VariableDefinitions = @{
'Name' = 'WarningPreference'
'Value' = 'SilentlyContinue' }
EnvironmentVariables = @{
'TESTSHARE' = '\\Test2\Test' }
FormatsToProcess = 'CustomFormats.ps1xml'
Parameters
-AliasDefinitions
Adds the specified aliases to sessions that use the session configuration. Enter a hash
table with
the following keys:
Type: IDictionary[]
Position: Named
-AssembliesToLoad
Specifies the assemblies to load into the sessions that use the session configuration.
Type: String[]
Position: Named
-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
-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
-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
-Description
Type: String
Position: Named
-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.
Type: IDictionary
Position: Named
-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
Position: Named
-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
-Full
Indicates that this operation includes all possible configuration properties in the
session
configuration file.
Type: SwitchParameter
Position: Named
Adds the specified functions to sessions that use the session configuration. Enter a
hash table with
the following keys:
For example:
@{Name='Get-PowerShellProcess';ScriptBlock={Get-Process
PowerShell};Options='AllScope'}
Type: IDictionary[]
Position: Named
-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
-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
-LanguageMode
The default value of the LanguageMode parameter depends on the value of the
SessionType
parameter.
Empty - NoLanguage
RestrictedRemoteServer - NoLanguage
Default - FullLanguage
Type: PSLanguageMode
Position: Named
Default value: None
-ModulesToImport
Specifies the modules and snap-ins that are automatically imported into sessions
that use the
session configuration.
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'}
Type: Object[]
Position: Named
-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
-Path
Specifies the path and filename of the session configuration file. The file must have a
.pssc file
name extension.
Type: String
Position: 0
-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.
Position: Named
-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 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
-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
-RunAsVirtualAccount
Type: SwitchParameter
Position: Named
-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
-SchemaVersion
Specifies the version of the session configuration file schema. The default value is
"1.0.0.0".
Type: Version
Position: Named
-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
-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:
Type: SessionType
Accepted values: Empty, RestrictedRemoteServer, Default
Position: Named
-TranscriptDirectory
Specifies the directory to place session transcripts for sessions using this session
configuration.
Type: String
Position: Named
-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
-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.
Position: Named
-VariableDefinitions
Adds the specified variables to sessions that use the session configuration. Enter a
hash table with
the following keys:
For example:
@{Name='WarningPreference';Value='SilentlyContinue';Options='AllScope'}
Type: Object
Position: Named
-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.
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
-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
-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.
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
-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
-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
Inputs
None
Outputs
None
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.
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
Examples
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
PowerShell
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.
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.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.
PowerShell
$PSSessionOption = New-PSSessionOption -OpenTimeOut 120000
PowerShell
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.
Name Value
---- -----
Team IT
Use Testing
Invoke-Command -Session $s {
.\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.
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.
Parameters
-ApplicationArguments
Type: PSPrimitiveDictionary
Position: Named
-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
-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
Type: CultureInfo
Position: Named
-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 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
-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.
Type: SwitchParameter
Position: Named
Type: Int32
Position: Named
-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.
Type: Int32
Position: Named
-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
-MaximumRedirection
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
-NoCompression
Turns off packet compression in the session. Compression uses more processor
cycles, but it makes
transmission faster.
Type: SwitchParameter
Position: Named
-NoEncryption
Type: SwitchParameter
Position: Named
-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
-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
-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.
Type: Int32
Aliases: OperationTimeoutMSec
Position: Named
-OutputBufferingMode
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.
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 .
Position: Named
-ProxyAccessType
IEConfig
WinHttpConfig
AutoDetect
NoProxyServer
None
Type: ProxyAccessType
Position: Named
-ProxyAuthentication
Specifies the authentication method that is used for proxy resolution. The acceptable
values for
this parameter are:
Basic
Digest
Negotiate
Type: AuthenticationMechanism
Position: Named
-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
-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
-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.
Type: SwitchParameter
Position: Named
-SkipRevocationCheck
Type: SwitchParameter
Position: Named
-UICulture
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
-UseUTF16
Indicates that this cmdlet encodes the request in UTF16 format instead of UTF8
format.
Type: SwitchParameter
Position: Named
Inputs
None
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
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.
Examples
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.
PowerShell
$t = New-PSTransportOption -MaxSessions 40
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 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.
$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 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.
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
-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.
Type: Nullable<T>[Int32]
Position: Named
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
-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.
Type: Nullable<T>[Int32]
Position: Named
-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).
Type: Nullable<T>[Int32]
Position: Named
Default value: None
-MaxProcessesPerSession
Limits the number of processes running in each session to the specified value. The
default value is
15.
Type: Nullable<T>[Int32]
Position: Named
-MaxSessions
Limits the number of sessions that use the session configuration. The default value is
25.
Type: Nullable<T>[Int32]
Position: Named
-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.
Type: Nullable<T>[Int32]
Position: Named
-OutputBufferingMode
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.
Type: Nullable<T>[OutputBufferingMode]
Position: Named
-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
Inputs
None
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.
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
No error is thrown when using Out-Default but the output isn't changed if it's not
explicitly
called.
Parameters
-InputObject
Type: PSObject
Position: Named
-Transcript
Type: SwitchParameter
Position: Named
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
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.
Examples
PowerShell
Get-Process gets the system processes and sends the objects down the pipeline. Out-
PowerShell
$io = Get-History
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
-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.
7 Note
Type: SwitchParameter
Position: Named
Inputs
PSObject
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.
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
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
Inputs
PSObject
Outputs
None
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
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.
+ PSComputerName : localhost
+ PSComputerName : localhost
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.
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
# 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
# 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.
# 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
# The Receive-Job command must be run in each session because the jobs were
run locally on each server.
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.
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.
Directory: C:\
Cannot find drive. A drive with the name 'Z' does not exist.
+ FullyQualifiedErrorId :
DriveNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
+ PSComputerName : localhost
# Using the object model, you can still retrieve child job data and streams.
$job.ChildJobs[0].Error
Cannot find drive. A drive with the name 'Z' does not exist.
+ 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.
Type: SwitchParameter
Position: Named
-ComputerName
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
-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
-Id
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
-InstanceId
Type: Guid[]
Position: 0
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
-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
-Location
Type: String[]
Position: 1
-Name
Type: String[]
Position: 0
-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
-Session
Type: PSSession[]
Position: 1
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.
Type: SwitchParameter
Position: Named
-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.
Type: SwitchParameter
Position: Named
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.
Type: SwitchParameter
Position: Named
Inputs
Job
Outputs
PSObject
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
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
Some examples use splatting to reduce the line length and improve readability. For
more information,
see about_Splatting.
Examples
PowerShell
Because the command doesn't use the OutTarget parameter, the results appear on the
command line.
PowerShell
PowerShell
$parms = @{
ComputerName = "Server01"
Name = "ITTask"
OutTarget = "Job"
JobName = "ITTaskJob01"
Credential = "Domain01\Admin01"
}
Receive-PSSession @parms
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
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
PowerShell
PS> $s
Running "New-ADResolve.ps1"
# Network outage
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.
PowerShell
PS> $parms = @{
InDisconnectedSession = $True
FilePath = "\\Server12\Scripts\SharedScripts\Get-BugStatus.ps1"
Name = "BugStatus"
ConfigurationName = "ITTasks"
PS> Exit
PS> $s
PS> $s
PS> $Results
----------------------
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.
PowerShell
PS> $s = New-PSSession -ComputerName Server01 -Name Test
PS> $j
PS> $s | Disconnect-PSSession
PS> $j
Return 1
Return 2
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
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
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 parameter's value is used to select and filter sessions. It doesn't change the
application that
the session uses.
Type: String
Position: Named
-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
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
Position: Named
-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.
Type: String
Position: Named
-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
-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 parameter's value is used to select and filter sessions. It doesn't change the
session
configuration that the session uses.
Type: String
Position: Named
Type: SwitchParameter
Aliases: cf
Position: Named
-ConnectionUri
Specifies a URI that defines the connection endpoint that is used to reconnect to the
disconnected
session.
<Transport>://<ComputerName>:<Port>/<ApplicationName>
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.
Type: Uri
Aliases: URI, CU
Position: 0
-Credential
Specifies a user account that has permission to connect to the disconnected session.
The default is
the current user.
7 Note
Type: PSCredential
Position: Named
-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
-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
-JobName
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
Type: String
Position: Named
-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
Position: Named
-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:
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
-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
-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
The session option values take precedence over default values for sessions set in the
$PSSessionOption preference variable and in the session configuration. However,
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
-UseSSL
Indicates that this cmdlet uses the Secure Sockets Layer (SSL) protocol to connect to
the
disconnected session. By default, SSL isn't used.
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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet isn't run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
PSSession
You can pipe session objects to this cmdlet, such as objects returned by the Get-
PSSession cmdlet.
Int32
Guid
String
Outputs
Job
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
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
PowerShell
$scriptBlock = {
$_ -like "$wordToComplete*"
} | ForEach-Object {
"'$_'"
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 .
PowerShell
$s = {
$services | ForEach-Object {
$_.Name,
"ParameterValue",
$_.Name
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
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.
7 Note
The dotnet complete command is only available in version 2.0 and greater of the
dotnet cli.
PowerShell
$scriptblock = {
[System.Management.Automation.CompletionResult]::new($_, $_,
'ParameterValue', $_)
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
Type: String[]
Position: Named
-Native
Indicates that the argument completer is for a native command where PowerShell
cannot complete
parameter names.
Type: SwitchParameter
Position: Named
-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.
Type: String
Position: Named
-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.
containing the
$PSBoundParameters for the cmdlet, before the user pressed Tab
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.
(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 .
Type: ScriptBlock
Position: Named
Inputs
None
Outputs
None
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.
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.
Examples
PowerShell
$sessionConfiguration = @{
Name='NewShell'
ApplicationBase='c:\MyShells\'
AssemblyName='MyShell.dll'
ConfigurationTypeName='MyClass'
Register-PSSessionConfiguration @sessionConfiguration
PowerShell
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
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
PowerShell
$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
PowerShell
The script contains a single command that uses dot sourcing to run the user's
CurrentUserAllHosts profile in the current scope of the session.
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:
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
Type: PSSessionConfigurationAccessMode
Position: Named
-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
-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.
Type: String
Position: 1
-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.
Type: String
Position: 2
Default value: None
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-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
-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
-ModulesToImport
Specifies the modules that are automatically imported into sessions that use the
session
configuration.
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.
Position: Named
-Name
Type: String
Position: 0
-NoServiceRestart
Does not restart the WinRM service, and suppresses the prompt to restart the
service.
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
-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.
Type: String
Position: Named
-ProcessorArchitecture
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
Position: Named
-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.
Aliases: PowerShellVersion
Position: Named
-RunAsCredential
Specifies credentials for commands in the session. By default, commands run with
the permissions of
the current user.
Type: PSCredential
Position: Named
-SecurityDescriptorSddl
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 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
-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
The value of this parameter takes precedence over the value of the SessionType key
in the
session configuration file.
Type: PSSessionType
Position: Named
-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.
Type: PSSessionTypeOption
Position: Named
-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
-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
-ThreadApartmentState
Type: ApartmentState
Position: Named
-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
Position: Named
-TransportOption
Type: PSTransportOption
Position: Named
-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.
Type: SwitchParameter
Position: Named
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
None
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
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
PowerShell
$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 .
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 .
PowerShell
PowerShell
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.
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 | 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 .
Invoke-Command uses the $S session and runs Remove-Job . The Name parameter
specifies that
the job named MyJob is deleted.
PowerShell
State : Completed
HasMoreData : True
StatusMessage :
Location : localhost
JobStateInfo : Completed
Finished : System.Threading.ManualResetEvent
InstanceId : ad02b942-8007-4407-87f3-d23e71955872
Id : 3
Name : Job3
ChildJobs : {Job4}
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.
Parameters
-Command
Deletes jobs that include the specified words in the command. You can enter a
comma-separated array.
Type: String[]
Position: Named
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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 .
Type: Hashtable
Position: 0
-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
-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.
Type: Int32[]
Position: 0
Deletes jobs with the specified InstanceId. You can enter a comma-separated array.
An
InstanceId is a unique GUID that identifies a job.
Type: Guid[]
Position: 0
-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.
Type: Job[]
Position: 0
-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
-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
Position: 0
-WhatIf
Shows what would happen if Remove-Job runs. The cmdlet isn't run.
Type: SwitchParameter
Aliases: wi
Position: Named
Default value: False
Inputs
Job
Outputs
None
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
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
This command removes the BitsTransfer module from the current session.
Get-Module | Remove-Module
r.Management.dll')".
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.
$a = Get-Module BitsTransfer
Remove-Module -ModuleInfo $a
This command uses the ModuleInfo parameter to remove the BitsTransfer module.
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-Force
Type: SwitchParameter
Position: Named
-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.
It's also Required to specify at least one of the three below keys.
ModuleVersion - Specifies a minimum acceptable version of the module.
Type: ModuleSpecification[]
Position: 0
Default value: None
-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
-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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
String
PSModuleInfo
Outputs
None
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
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.
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
Get-PSSession | Remove-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.
$r | Remove-PSSession
These commands close the PSSessions that are connected to computers that have
names that begin
with Serv .
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.
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
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.
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
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-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.
Type: Int32[]
Position: 0
-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
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
-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
-VMId
Type: Guid[]
Aliases: VMGuid
Position: Named
-VMName
Type: String[]
Position: Named
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
PSSession
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 .
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
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
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
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.
This command removes all Windows PowerShell snap-ins that have names that include
event.
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-Name
Specifies the names of Windows PowerShell snap-ins to remove from the current
session.
Wildcard characters ( * ) are permitted.
Type: String[]
Position: 0
-PassThru
Returns an object that represents the snap-in. By default, this cmdlet does not
generate any output.
Type: SwitchParameter
Position: Named
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Outputs
None, System.Management.Automation.PSSnapInInfo
Notes
Windows PowerShell includes the following aliases for Remove-PSSnapin :
rsnp
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
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.
Examples
PowerShell
PowerShell
PowerShell
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.
PowerShell
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
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.
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-Id
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
-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
-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
-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
-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
Type: JobState
Position: 0
-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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
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.
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.
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.
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.
# module--to get the PSModuleInfo object for the remote module, and then run
Save-Help.
# module--to get the PSModuleInfo object for the remote module, and then run
Save-Help.
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.
# PSModuleInfo object with Import-CliXml. Run Save-Help to save the Help for
the imported DhcpServer
# Finally, transport the removable media back to the computer that does not
have network access, and
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.
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.
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
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.
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.
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.
7 Note
Type: PSCredential
Position: Named
-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
-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
-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.
Type: ModuleSpecification[]
Position: Named
-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
-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
-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
-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
Outputs
None
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
PowerShell
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help
(default is "Y"): A
PowerShell
The variable '$NewVar' cannot be retrieved because it has not been set.
At line:1 char:22
PowerShell
Parameters
-Off
Type: SwitchParameter
Position: Named
-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.
Type: SwitchParameter
Position: Named
-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
-Trace
Specifies the trace level for each line in a script. Each line is traced as it's run.
Type: Int32
Position: Named
Inputs
None
Related Links
about_Debuggers
Debug-Process
Set-PSBreakpoint
Set-StrictMode
Write-Debug
Set-PSSessionConfiguration
Reference
Module: Microsoft.PowerShell.Core
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.
Examples
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"
PowerShell
WSManConfig:
Microsoft.WSMan.Management\WSMan::localhost\Plugin\IncObj\InitializationPara
meters
ParamName ParamValue
--------- ----------
psmaximumreceivedobjectsizemb 20
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
WSManConfig:
Microsoft.WSMan.Management\WSMan::localhost\Plugin\MaintenanceShell\Initiali
zationParameters
ParamName ParamValue
--------- ----------
startupscript c:\ps-test\Mainte...
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:
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.
Other cmdlets can override the value of this parameter later. For example, the
Enable-PSRemoting
cmdlet enables all session configurations on the computer and
Type: PSSessionConfigurationAccessMode
Position: Named
-ApplicationBase
Specifies the path of the assembly file ( *.dll ) that is specified in the value of the
AssemblyName parameter.
Type: String
Position: Named
-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
-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.
Type: String
Position: 2
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-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
-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
-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.
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.
Type: Object[]
Position: Named
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
-NoServiceRestart
Does not restart the WinRM service, and suppresses the prompt to restart the
service.
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
-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
-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.
Type: Version
Aliases: PowerShellVersion
Position: Named
-RunAsCredential
Specifies credentials for commands in the session. By default, commands run with
the permissions of
the current user.
Type: PSCredential
Position: Named
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.
Type: String
Position: Named
-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.
Type: PSSessionTypeOption
Position: Named
-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
-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
-ThreadApartmentState
Specifies the apartment state of the threading module to be used. Acceptable values
are:
Unknown
MTA
STA
Type: ApartmentState
Position: Named
-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
Type: PSThreadOptions
Position: Named
-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.
Type: PSTransportOption
Position: Named
-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.
Type: SwitchParameter
Position: Named
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
None
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.
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.
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.
$a -gt 5
False
$a -gt 5
The variable $a cannot be retrieved because it has not been set yet.
At line:1 char:3
+ $a <<<< -gt 5
+ FullyQualifiedErrorId : VariableIsUndefined
With strict mode set to version 1.0 , attempts to reference variables that aren't initialized
fail.
'$b = ' + $b
add 3 4
$a = 3
$b = 4
$a+$b = 7
add(3,4)
$a = 3 4
$b =
$a+$b = 3 4
add(3,4)
At line:1 char:4
+ FullyQualifiedErrorId : StrictModeFunctionCallWithParens
Set-StrictMode -Off
True
At line:1 char:9
+ 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.
PowerShell
$a = @(1)
True
True
$a = @(1)
At line:1 char:1
+ ~~~~~~~~~~~~~~~
+ 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
+ ~~~~~~~~~~~~~~~~~~~
+ 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
-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
1.0
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
Outputs
None
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
Related Links
Set-PSDebug
Start-Job
Reference
Module: Microsoft.PowerShell.Core
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
Examples
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 .
PowerShell
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
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.
PowerShell
$j = Start-Job -ScriptBlock { Get-WinEvent -Log System } -Credential
Domain01\User01
$j | Select-Object -Property *
State : Completed
HasMoreData : True
StatusMessage :
Location : localhost
JobStateInfo : Completed
Finished : System.Threading.ManualResetEvent
InstanceId : 27ce3fd9-40ed-488a-99e5-679cd91b9dd3
Id : 18
Name : Job18
ChildJobs : {Job19}
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
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.
PowerShell
Start-Job uses the FilePath parameter to specify a script file that's stored on the local
computer.
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.
PowerShell
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.
PowerShell
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
PowerShell
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.
Type: Object[]
Aliases: Args
Position: Named
-Authentication
Default
Basic
Credssp
Digest
Kerberos
Negotiate
NegotiateWithImplicitCredential
U Caution
Type: AuthenticationMechanism
-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.
7 Note
Type: PSCredential
Position: Named
-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.
Type: String
Position: 0
-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.
Type: String
Position: 1
-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
-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
-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
-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
-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
-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 .
Type: Version
Position: Named
-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
-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
-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.
Type: String
Position: 2
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
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
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.
Stop-Job -Id 1, 3, 4
Get-Job | Stop-Job
This command stops all of the background jobs in the current session.
InstanceID -Auto
The second command uses a Stop-Job command that has the InstanceID parameter to
stop a
selected job.
$j | Stop-Job -PassThru
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.
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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.
Type: Hashtable
Position: 0
-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
-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
-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
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
-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
-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
Type: JobState
Position: 0
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
System.Management.Automation.RemotingJob
Outputs
None
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
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.
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.
Examples
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
CheckPoint-Workflow
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
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).
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.
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-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
-Id
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
-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
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
-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
-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.
Type: JobState
Position: 0
-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.
Type: SwitchParameter
Position: Named
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
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
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.
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
"$pshome\Modules\TestModule.psd1" | test-modulemanifest
At line:1 char:34
+ 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 : {}
The command output shows that the test failed, because the TestTypes.ps1xml file,
which was listed
in the manifest, was not found.
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 .
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
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
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.
Examples
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
PowerShell
PowerShell
function Test-AllConfigFiles
Get-PSSessionConfiguration | ForEach-Object {
if ($_.ConfigFilePath) {
$_.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
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
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
Inputs
String
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
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.
Examples
PowerShell
PowerShell
PowerShell
Unregister-PSSessionConfiguration -Name *
PowerShell
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException
+ CategoryInfo : OpenError:
(System.Manageme....RemoteRunspace:RemoteRunspace) [],
PSRemotingTransportException
+ FullyQualifiedErrorId : PSSessionOpenFailed
Finally, the New-PSSession cmdlet tries to create a session that uses the
MaintenanceShell
configuration. This time, the session fails because the
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-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.
Type: String
Position: 0
-NoServiceRestart
Indicates that this cmdlet does not restart the WinRM service, and suppresses the
prompt to
restart the service.
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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
Microsoft.PowerShell.Commands.PSSessionConfigurationCommands
Outputs
None
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
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.
) Important
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
PowerShell
Update-Help
PowerShell
In this example, Update-Help is being run on a system that's set to the en-GB locale.
PowerShell
At line:1 char:1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ 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.
PowerShell
$jobParams = @{
Name = 'UpdateHelpJob'
Credential = 'Domain01\User01'
ScriptBlock = '{Update-Help}'
Register-ScheduledJob @jobParams
1 UpdateHelpJob 1 Update-Help
True
PowerShell
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
PowerShell
PowerShell
Directory: C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules
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'}
$mDir = $mModule.ModuleBase
if (Test-Path $mdir\*helpinfo.xml)
$mName=$mModule.Name
$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
Type: SwitchParameter
Aliases: cf
Position: Named
-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: PSCredential
Position: Named
-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:
Type: SwitchParameter
Position: Named
-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.
Type: ModuleSpecification[]
Position: Named
-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
-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
Type: String[]
Aliases: Name
Position: 0
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
-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.
Type: String[]
Position: 1
-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
-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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet isn't run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
DirectoryInfo
PSModuleInfo
Outputs
None
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
Any module can support Updatable Help. For instructions for supporting Updatable
Help in the modules
that you author, see
Supporting Updatable Help.
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
Get-Job | Wait-Job
This command waits for all of the jobs running in the session to finish.
$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.
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.
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.
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.
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.
This command uses the job name to identify the job for which to wait.
$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.
$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.
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.
Get-Job
Wait-Job -Id 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
-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.
Type: Hashtable
Position: 0
-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
Type: SwitchParameter
Position: Named
-Id
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
-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
-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
-Name
Type: String[]
Position: 0
-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
Type: JobState
Position: 0
-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
Inputs
System.Management.Automation.RemotingJob
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
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 .
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.
Examples
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
PowerShell
The commands filter the processes the same way and return the same output. Only the
syntax is
different.
PowerShell
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
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
# 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.
# Finally, use the -not operator (!) to get objects that are not containers.
# This gets objects that do have the **PSIsContainer** property and those
# You cannot use the -not operator (!) in the comparison statement format
# of the command.
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.
Type: SwitchParameter
Position: Named
-CEQ
Indicates that this cmdlet gets objects if the property value is the same as the
specified value.
This operation is case-sensitive.
Type: SwitchParameter
Position: Named
Indicates that this cmdlet gets objects if the property value is greater than or equal
to the
specified value. This operation is case-sensitive.
Type: SwitchParameter
Position: Named
-CGT
Indicates that this cmdlet gets objects if the property value is greater than the
specified value.
This operation is case-sensitive.
Type: SwitchParameter
Position: Named
-CIn
Indicates that this cmdlet gets objects if the property value includes the specified
value. This
operation is case-sensitive.
CIn resembles CContains, except that the property and value positions are reversed.
For
example, the following statements are both true.
Type: SwitchParameter
Position: Named
-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.
Type: SwitchParameter
Position: Named
-CLike
Indicates that this cmdlet gets objects if the property value matches a value that
includes wildcard
characters ( * ). This operation is case-sensitive.
Type: SwitchParameter
Position: Named
Indicates that this cmdlet gets objects if the property value is less-than the specified
value. This
operation is case-sensitive.
Type: SwitchParameter
Position: Named
-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.
Type: SwitchParameter
Position: Named
-CNE
Indicates that this cmdlet gets objects if the property value is different than the
specified value.
This operation is case-sensitive.
Type: SwitchParameter
Position: Named
Default value: None
-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.
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.
Type: SwitchParameter
Position: Named
-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.
NotIn and CNotIn operators resemble NotContains and CNotContains, except that
the
property and value positions are reversed. For example, the following statements
are true.
Type: SwitchParameter
Position: Named
Default value: None
-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.
Type: SwitchParameter
Position: Named
-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.
Type: SwitchParameter
Position: Named
-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.
Type: SwitchParameter
Aliases: IContains
Position: Named
-EQ
Indicates that this cmdlet gets objects if the property value is the same as the
specified value.
Type: SwitchParameter
Aliases: IEQ
Position: Named
-FilterScript
Specifies the script block that's used to filter the objects. Enclose the script block in
braces
( {} ).
Type: ScriptBlock
Position: 0
-GE
Indicates that this cmdlet gets objects if the property value is greater than or equal
to the
specified value.
Type: SwitchParameter
Aliases: IGE
Position: Named
-GT
Indicates that this cmdlet gets objects if the property value is greater than the
specified value.
Type: SwitchParameter
Aliases: IGT
Position: Named
-In
Indicates that this cmdlet gets objects if the property value matches any of the
specified values.
For example:
"WsmProvHost"
Type: SwitchParameter
Aliases: IIn
Position: Named
-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) .
Type: PSObject
Position: Named
-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.
Type: SwitchParameter
Position: Named
-IsNot
Indicates that this cmdlet gets objects if the property value isn't an instance of the
specified
.NET type.
Type: SwitchParameter
Position: Named
-LE
Indicates that this cmdlet gets objects if the property value is less than or equal to
the specified
value.
Aliases: ILE
Position: Named
-Like
Indicates that this cmdlet gets objects if the property value matches a value that
includes wildcard
characters ( * ).
Type: SwitchParameter
Aliases: ILike
Position: Named
-LT
Indicates that this cmdlet gets objects if the property value is less than the specified
value.
Type: SwitchParameter
Aliases: ILT
Position: Named
-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.
Type: SwitchParameter
Aliases: IMatch
Position: Named
-NE
Indicates that this cmdlet gets objects if the property value is different than the
specified value.
Type: SwitchParameter
Aliases: INE
Position: Named
-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"
Type: SwitchParameter
Aliases: INotContains
Position: Named
-NotIn
Indicates that this cmdlet gets objects if the property value isn't an exact match for
any of the
specified values.
Type: SwitchParameter
Aliases: INotIn
Position: Named
Indicates that this cmdlet gets objects if the property value doesn't match a value
that includes
wildcard characters ( * ).
Type: SwitchParameter
Aliases: INotLike
Position: Named
-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.
Type: SwitchParameter
Aliases: INotMatch
Position: Named
-Property
Specifies the name of an object property. The parameter name, Property, is optional.
Position: 0
-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
Type: PSObject
Position: 1
Inputs
PSObject
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.
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-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
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
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.
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
PowerShell
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
20
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
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
-FileFormat
CSV
TSV
BLG
Type: String
Position: Named
-Force
Overwrites and replaces an existing file if one exists in the location specified by the
Path
parameter.
Type: SwitchParameter
Position: Named
-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
-MaxSize
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
-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
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
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
PowerShell
Get-Counter -ListSet *
CounterSetName : Processor
MachineName : .
CounterSetType : MultiInstance
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.
PowerShell
Timestamp CounterSamples
--------- --------------
20.7144271584086
10.4391790575511
37.5968799396998
interval
to check the counter. MaxSamples determines that three is the maximum
number of times to check
the counter.
PowerShell
Timestamp CounterSamples
--------- --------------
43.8522842937022
29.7896844697383
29.4962645638135
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 .
PowerShell
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.
PowerShell
uses
the Counter parameter to specify the counter path \LogicalDisk(_Total)\% Free
Space . The
MaxSamples parameter specifies to get 1000 samples of the counter.
PowerShell
Timestamp CounterSamples
--------- --------------
\\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.
An alternative for the server names in the ComputerName parameter is to use a text file.
For
example:
PowerShell
Timestamp CounterSamples
--------- --------------
6.52610319637854
3.41030663625782
9.64189975649925
1.85240835619747
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.
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.
\Memory\Cache Faults/sec
\Memory\Cache Bytes
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.
PowerShell
Get-Counter uses the ListSet parameter to specify the PhysicalDisk counter set. The
PowerShell
Timestamp CounterSamples
--------- --------------
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.
PowerShell
InstanceName : idle
CookedValue : 198.467899571389
RawValue : 14329160321003
SecondValue : 128606459528326201
MultipleCount : 1
CounterType : Timer100Ns
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.
PowerShell
$Counter.CounterSamples[0]
$Counter.CounterSamples[0] displays the array value for the first counter value.
PowerShell
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
PowerShell
Path InstanceName
CookedValue
---- ------------
-----------
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
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
-Continuous
Type: SwitchParameter
Position: Named
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 .
\\ComputerName\CounterSet(Instance)\CounterName
\CounterSet(Instance)\CounterName
For example:
Type: String[]
Position: 1
-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.
Type: String[]
Position: 1
-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
-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
Inputs
String[]
Get-Counter accepts pipeline input for counter paths and counter set names.
Outputs
CounterSet
PerformanceCounterSampleSet
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.
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
PowerShell
Get-WinEvent -ListLog *
The Get-WinEvent cmdlet gets log information from the computer. The ListLog
parameter uses the
asterisk ( * ) wildcard to display information about each log.
PowerShell
FileSize : 69632
IsLogFull : False
OldestRecordNumber : 1
RecordCount : 23
LogName : Setup
LogType : Operational
LogIsolation : Application
IsEnabled : True
IsClassicLog : False
LogFilePath :
%SystemRoot%\System32\Winevt\Logs\Setup.evtx
MaximumSizeInBytes : 1052672
LogMode : Circular
OwningProviderName : Microsoft-Windows-Eventlog
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.
PowerShell
$log.MaximumSizeInBytes = 1gb
try{
$log.SaveChanges()
}catch [System.UnauthorizedAccessException]{
$ErrMsg += ' Try running this script with administrator privileges. '
$ErrMsg += $_.Exception.Message
Write-Error $ErrMsg
FileSize : 69632
IsLogFull : False
OldestRecordNumber : 1
RecordCount : 23
LogName : Security
LogType : Administrative
LogIsolation : Custom
IsEnabled : True
IsClassicLog : True
LogFilePath :
%SystemRoot%\System32\Winevt\Logs\Security.evtx
MaximumSizeInBytes : 1073741824
LogMode : Circular
OwningProviderName :
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.
PowerShell
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
PowerShell
@{name='ComputerName'; expression={$Server}} |
Format-Table -AutoSize
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.
PowerShell
Get-WinEvent -ListProvider *
LogLinks : {Application}
Opcodes : {}
Tasks : {}
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.
PowerShell
.NET Runtime
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
LogLinks : {Application}
Opcodes : {}
Tasks : {}
LogLinks : {Application}
Opcodes : {}
Tasks : {}
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.
PowerShell
Id Description
-- -----------
1500 The Group Policy settings for the computer were processed
successfully...
1501 The Group Policy settings for the user were processed successfully...
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.
PowerShell
$Event.Count
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.
PowerShell
Format-Table -AutoSize
Count Name
----- ----
1 Error, PowerShellCore/Operational
26 Information, Microsoft-Windows-Kernel-WHEA/Operational
77 Information, PowerShellCore/Operational
19 Verbose, 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
archived
PowerShell log that is stored on the local computer.
PowerShell
ProviderName: PowerShell
The Get-WinEvent cmdlet gets log information from the computer. The Path parameter
specifies
the directory and file name.
PowerShell
ProviderName: PowerShellCore
...
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.
PowerShell
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.
PowerShell
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.
PowerShell
$xmlQuery = @'
<QueryList>
</Query>
</QueryList>
'@
PowerShell
$Date = (Get-Date).AddDays(-2)
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.
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
-Credential
Specifies a user account that has permission to perform this action. The default value
is the
current user.
Type: PSCredential
Position: Named
-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.
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.
LogName= <String[]>
ProviderName= <String[]>
Path= <String[]>
Keywords= <Long[]>
ID= <Int32[]>
Level= <Int32[]>
StartTime= <DateTime>
EndTime= <DateTime>
UserID= <SID>
Data= <String[]>
Type: Hashtable[]
Position: 1
-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
-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
-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
-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
-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
-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
Type: String[]
Position: 1
-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
-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
-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
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
Inputs
String
XmlDocument
Hashtable
Outputs
EventLogConfiguration
EventLogRecord
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
This command imports all counter data from the ProcessorData.csv file into the $data
variable.
PowerShell
$data = Import-Counter .\ProcessorData.blg
Path
----
\\SERVER01\Processor(_Total)\DPC Rate
\\SERVER01\Processor(1)\DPC Rate
\\SERVER01\Processor(0)\DPC Rate
\\SERVER01\Processor(_Total)\% C3 Time
\\SERVER01\Processor(1)\% C3 Time
$intCtrs
\\SERVER01\Processor(_Total)\Interrupts/sec
\\SERVER01\Processor(1)\Interrupts/sec
\\SERVER01\Processor(0)\Interrupts/sec
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
CounterSetName : Processor
MachineName : \\SERVER01
CounterSetType : MultiInstance
Description :
\\SERVER01\Processor(*)\DPC Rate
\\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(*)\C2 Transitions/sec
\\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
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.
PowerShell
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.
This command uses the Summary parameter of the Import-Counter cmdlet to get a
summary of the
counter data in the Memory.blg file.
PowerShell
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.
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
Each counter path has the following format. The ComputerName value is required in
the path. For
instance:
\\<ComputerName>\<CounterSet>(<Instance>)\<CounterName>
For example:
Type: String[]
Position: Named
-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
-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
-MaxSamples
Type: Int64
Position: Named
-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
-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
-Summary
Indicates that this cmdlet gets a summary of the imported data, instead of getting
individual
counter data samples.
Type: SwitchParameter
Position: Named
Inputs
String
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
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
This command uses the New-WinEvent cmdlet to create event 45090 for the
Microsoft-
Windows-PowerShell provider.
PowerShell
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">
</template>
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">
</template>
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.
PowerShell
ProviderName: Microsoft-Windows-GroupPolicy
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
Type: Int32
Position: 2
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
-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
-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
Inputs
None
Outputs
None
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.
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.
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
Start-Transcript
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
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-IncludeInvocationHeader
Indicates that this cmdlet logs the time stamp when commands are run.
Type: SwitchParameter
Position: Named
-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
-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
Type: String
Position: 0
-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
-WhatIf
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
None
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
Stop-Transcript
Inputs
None
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
Microsoft.PowerShell.LocalAccounts
Add-LocalGroupMember 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
PowerShell
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
Type: Microsoft.PowerShell.Commands.LocalGroup
Position: 0
-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
-Name
Specifies the name of the security group to which this cmdlet adds members.
Type: String
Position: 0
-SID
Specifies the security ID of the security group to which this cmdlet adds members.
Type: SecurityIdentifier
Position: 0
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
System.Management.Automation.SecurityAccountsManager.LocalGroup
String
SecurityIdentifier
Outputs
None
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
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
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
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-Name
Specifies an array of names of the user accounts that this cmdlet disables.
Type: String[]
Position: 0
-SID
Type: SecurityIdentifier[]
Position: 0
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
System.Management.Automation.SecurityAccountsManager.LocalUser
String
SecurityIdentifier
Outputs
None
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
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
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
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
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-Name
Specifies an array of names of the user accounts that this cmdlet enables.
Type: String[]
Position: 0
-SID
Type: SecurityIdentifier[]
Position: 0
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
System.Management.Automation.SecurityAccountsManager.LocalUser
String
SecurityIdentifier
Outputs
None
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
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
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
Examples
Parameters
-Name
Specifies an array of names of security groups that this cmdlet gets. You can use the
wildcard
character.
Type: String[]
Position: 0
-SID
Specifies an array of security IDs (SIDs) of security groups that this cmdlet gets.
Type: SecurityIdentifier[]
Position: 0
Inputs
String
SecurityIdentifier
Outputs
System.Management.Automation.SecurityAccountsManager.LocalGroup
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
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
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
Examples
Example 1: Get all members of the Administrators group
PowerShell
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
-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
-Name
Specifies the name of the security group from which this cmdlet gets members.
Type: String
Position: 0
-SID
Specifies the security ID of the security group from which this cmdlet gets members.
Type: SecurityIdentifier
Position: 0
Inputs
System.Management.Automation.SecurityAccountsManager.LocalGroup
String
SecurityIdentifier
Outputs
Microsoft.SecurityAccountsManager.LocalPrincipal
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
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
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
Examples
PowerShell
Get-LocalUser -Name "AdminContoso02"
PowerShell
PowerShell
Parameters
-Name
Specifies an array of names of user accounts that this cmdlet gets. You can use the
wildcard
character.
Type: String[]
Position: 0
-SID
Specifies an array of security IDs (SIDs) of user accounts that this cmdlet gets.
Type: SecurityIdentifier[]
Position: 0
Inputs
String
SecurityIdentifier
Outputs
System.Management.Automation.SecurityAccountsManager.LocalUser[]
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
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
Examples
Type: SwitchParameter
Aliases: cf
Position: Named
-Description
Type: String
Position: Named
-Name
Specifies a name for the group. The maximum length is 256 characters.
Type: String
Position: 0
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
String
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
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
Examples
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.
$params = @{
Name = 'User03'
Password = $Password
New-LocalUser @params
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
-AccountNeverExpires
Type: SwitchParameter
Position: Named
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
Specifies a comment for the user account. The maximum length is 48 characters.
Type: String
Position: Named
-Disabled
Type: SwitchParameter
Position: Named
-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
-Name
Type: String
Position: 0
-NoPassword
Type: SwitchParameter
Position: Named
-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
-PasswordNeverExpires
Type: SwitchParameter
Position: Named
-UserMayNotChangePassword
Indicates that the user can't change the password on the user account.
Type: SwitchParameter
Position: Named
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet isn't run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
String
DateTime
Boolean
SecureString
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:
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
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
Examples
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-Name
Specifies an array of names of the security groups that this cmdlet deletes.
Type: String[]
Position: 0
-SID
Specifies an array of security IDs (SIDs) of security groups that this cmdlet deletes.
Type: SecurityIdentifier[]
Position: 0
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
String
SecurityIdentifier
Outputs
None
Notes
This cmdlet cannot delete the following default groups:
Administrators
Backup Operators
Cryptographic Operators
Guests
Hyper-V Administrators
IIS_IUSRS
Replicator
Users
WinRMRemoteWMIUsers__
Local
Active Directory
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
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
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
Type: SwitchParameter
Aliases: cf
Position: Named
-Group
Specifies the security group from which this cmdlet removes members.
Type: Microsoft.PowerShell.Commands.LocalGroup
Position: 0
-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
-Name
Specifies the name of the security group from which this cmdlet removes members.
Type: String
Position: 0
-SID
Specifies the security ID of the security group from which this cmdlet removes
members.
Type: SecurityIdentifier
Position: 0
-WhatIf
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
System.Management.Automation.SecurityAccountsManager.LocalPrincipal
String
SecurityIdentifier
Outputs
None
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
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
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
7 Note
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-Name
Specifies an array of names of the user accounts that this cmdlet deletes.
Type: String[]
Position: 0
-SID
Specifies an array of security IDs (SIDs) of user accounts that this cmdlet deletes.
Type: SecurityIdentifier[]
Position: 0
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
System.Management.Automation.SecurityAccountsManager.LocalUser
SecurityIdentifier
Outputs
None
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
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
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
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-InputObject
Type: Microsoft.PowerShell.Commands.LocalGroup
Position: 0
-Name
Specifies the name of the security group that this cmdlet renames.
Type: String
Position: 0
-NewName
Type: String
Position: 1
-SID
Specifies the security ID (SID) of a security group that this cmdlet renames.
Type: SecurityIdentifier
Position: 0
-WhatIf
Aliases: wi
Position: Named
Inputs
System.Management.Automation.SecurityAccountsManager.LocalGroup
String
SecurityIdentifier
Outputs
None
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
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
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
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-Name
Specifies the name of the user account that this cmdlet renames.
Type: String
Position: 0
-NewName
Type: String
Position: 1
-SID
Specifies the security ID (SID) of a user accounts that this cmdlet renames.
Type: SecurityIdentifier
Position: 0
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
System.Management.Automation.SecurityAccountsManager.LocalUser
String
SecurityIdentifier
Outputs
None
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
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
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
7 Note
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-Description
Type: String
Position: Named
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
-Name
Specifies the name of the security group that this cmdlet changes.
Type: String
Position: 0
-SID
Specifies the security ID (SID) of the security group that this cmdlet changes.
Type: SecurityIdentifier
Position: 0
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
System.Management.Automation.SecurityAccountsManager.LocalGroup
String
SecurityIdentifier
Outputs
None
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
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
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
Examples
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.
Type: DateTime
Position: Named
-AccountNeverExpires
Type: SwitchParameter
Position: Named
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-Description
Specifies a comment for the user account. The maximum length is 48 characters.
Type: String
Position: Named
-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
-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
Specifies the name of the user account that this cmdlet changes.
Type: String
Position: 0
-Password
Specifies a password for the user account. If the user account is connected to a
Microsoft account,
do not set a password.
If you omit the Password and NoPassword parameters, Set-LocalUser prompts you
for the
user's password.
Type: SecureString
Position: Named
-PasswordNeverExpires
Type: Boolean
Position: Named
Specifies the security ID (SID) of the user account that this cmdlet changes.
Type: SecurityIdentifier
Position: 0
-UserMayChangePassword
Indicates that the user can change the password on the user account.
Type: Boolean
Position: Named
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
System.Management.Automation.SecurityAccountsManager.LocalUser
You can pipe a local user to this cmdlet.
String
SecurityIdentifier
Outputs
None
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
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.
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.
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-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-ItemPropertyValue Gets the value for one or more properties of a specified item.
Get-Process Gets the processes that are running on the local computer or a
remote computer.
Get-TimeZone Gets the current time zone or a list of available time zones.
Limit-EventLog Sets the event log properties that limit the size of the event log
and the age of its entries.
New-EventLog Creates a new event log and a new event source on a local or
remote computer.
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-WebServiceProxy Creates a Web service proxy object that lets you use and manage
the Web service in PowerShell.
Resolve-Path Resolves the wildcard characters in a path, and displays the path
contents.
Set-Service Starts, stops, and suspends a service, and changes its properties.
Test-ComputerSecureChannel Tests and repairs the secure channel between the local computer
and its domain.
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
This command adds the local computer to the Domain01 domain and then restarts the
computer to make
the change effective.
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
This command adds the local computer to the Domain02 domain. It uses the OUPath
parameter to specify
the organizational unit for the new accounts.
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.
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.
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.
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.
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:
UserName = $null
})
Parameters
-ComputerName
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.
Type: String[]
Position: Named
Type: SwitchParameter
Aliases: cf
Position: Named
-Credential
Specifies a user account that has permission to join the computers to a new domain.
The default is the current user.
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
-DomainName
Specifies the domain to which the computers are added. This parameter is required
when adding the
computers to a domain.
Type: String
Position: 0
-Force
Type: SwitchParameter
Position: Named
-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.
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.
Type: PSCredential
Position: Named
-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.
Type: String
Position: Named
-Options
Specifies advanced options for the Add-Computer join operation. Enter one or more
values in a
comma-separated string.
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.
Type: JoinOptions
Position: Named
-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
-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
-Restart
Restarts the computers that were added to the domain or workgroup. A restart is
often required to
make the change effective.
Type: SwitchParameter
Position: Named
-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
-UnjoinDomainCredential
Specifies a user account that has permission to remove the computers from their
current domains. The
default is the current user.
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.
Type: PSCredential
Position: Named
-Unsecure
Type: SwitchParameter
Position: Named
-WhatIf
Type: SwitchParameter
Aliases: wi
Position: Named
-WorkgroupName
Specifies the name of a workgroup to which the computers are added. The default
value is
"WORKGROUP".
Type: String
Aliases: WGN
Position: 0
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
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
PowerShell
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.
PowerShell
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 .
PowerShell
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.
PowerShell
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 .
PowerShell
Add-Content -Path .\NewFile.txt -Value (Get-Content -Path
.\CopyFromFile.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 .
PowerShell
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
Type: SwitchParameter
Aliases: cf
Position: Named
-Credential
7 Note
Type: PSCredential
Position: Named
-Encoding
Specifies the type of encoding for the target file. The default value is Default .
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.
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
Position: Named
-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
-Filter
Type: String
Position: Named
-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
-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
-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.
Type: String[]
Aliases: PSPath
Position: Named
-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
Returns an object representing the added content. By default, this cmdlet does not
generate any
output.
Type: SwitchParameter
Position: Named
-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
-Stream
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 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.
Position: Named
-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
-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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
Object
PSCredential
Outputs
None
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
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.
Examples
Parameters
-Description
Type: String
Position: 0
-RestorePointType
APPLICATION_INSTALL
APPLICATION_UNINSTALL
DEVICE_DRIVER_INSTALL
MODIFY_SETTINGS
CANCELLED_OPERATION
Type: String
Aliases: RPT
Position: 1
Default value: None
Inputs
None
Outputs
None
Notes
This cmdlet uses the CreateRestorePoint method of the SystemRestore class with
a BEGIN_SYSTEM_CHANGE event.
"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
Examples
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.
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
[ZoneTransfer]
ZoneId=3
Parameters
-Confirm
Aliases: cf
Position: Named
-Credential
7 Note
Type: PSCredential
Position: Named
-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
-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
-Force
Type: SwitchParameter
Position: Named
-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
-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
-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
-Stream
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.
Type: String
Position: Named
-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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
None
Outputs
None
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
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
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.
This command prompts you for confirmation before deleting the entries in the specified
event logs.
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
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
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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
Type: String[]
Aliases: LN
Position: 0
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Outputs
None
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
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:
PowerShell
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-Credential
7 Note
Type: PSCredential
Position: Named
-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
Type: String
Position: Named
-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
-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
-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.
Type: String[]
Aliases: PSPath
Position: Named
-Path
Type: String[]
Position: 0
-UseTransaction
Aliases: usetx
Position: Named
-WhatIf
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
String
Outputs
None
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
PowerShell
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-Credential
7 Note
Type: PSCredential
Position: Named
-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
-Filter
Type: String
Position: Named
-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
-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
-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.
Type: String[]
Aliases: PSPath
Position: Named
-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
-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
-Path
Type: String[]
Position: 0
-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
-WhatIf
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
String
Outputs
None
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
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
PowerShell
Clear-RecycleBin
Confirm
[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
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.
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
-DriveLetter
Specifies the recycle bin to clear for a single drive letter or an array of drive letters.
Type: String[]
Position: 0
-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
-WhatIf
Shows what would happen if Clear-RecycleBin runs. The cmdlet isn't run.
Type: SwitchParameter
Aliases: wi
Position: Named
Outputs
None
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.
Examples
Set-Location hkcu:\software
Start-Transaction
Get-ChildItem m*
Hive: HKEY_CURRENT_USER\software
82 1 Microsoft {(default)}
Complete-Transaction
Get-ChildItem m*
Hive: HKEY_CURRENT_USER\Software
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.
Set-Location hkcu:\software
Start-Transaction
Hive: HKEY_CURRENT_USER\Software
0 0 MyCompany {}
Start-Transaction
Get-Transaction
Error 2 Active
MyKey
-----
123
Complete-Transaction
Get-Transaction
Error 1 Active
Get-ChildItem m*
Hive: HKEY_CURRENT_USER\Software
82 1 Microsoft {(default)}
Complete-Transaction
Get-ChildItem m*
Hive: HKEY_CURRENT_USER\Software
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.
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.
Set-Location hkcu:\software
Start-Transaction
Get-ChildItem m*
Hive: HKEY_CURRENT_USER\Software
82 1 Microsoft {(default)}
Get-ChildItem m* -UseTransaction
Hive: HKEY_CURRENT_USER\Software
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
Type: SwitchParameter
Aliases: cf
Position: Named
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Outputs
None
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.
Related Links
Get-Transaction
Start-Transaction
Undo-Transaction
Use-Transaction
Get-ChildItem
New-Item
New-ItemProperty
Convert-Path
Reference
Module: Microsoft.PowerShell.Management
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
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
HKEY_LOCAL_MACHINE\Software\Microsoft
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
-Path
Specifies the PowerShell path to be converted.
Type: String[]
Position: 0
-UseTransaction
Type: SwitchParameter
Aliases: usetx
Position: Named
Inputs
String
You can pipe a path, but not a literal path, to this cmdlet.
Outputs
String
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
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
PowerShell
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
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 .
PowerShell
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:
PowerShell
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
PowerShell
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
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
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
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
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
PowerShell
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
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
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.
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
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.
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\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.
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\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
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-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
-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
-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
-Filter
Type: String
Position: Named
-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
-FromSession
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.
Type: PSSession
Position: Named
-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
-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.
Type: String[]
Aliases: PSPath
Position: Named
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
-Path
Specifies, as a string array, the path to the items to copy. Wildcard characters are
permitted.
Type: String[]
Position: 0
-Recurse
Type: SwitchParameter
Position: Named
-ToSession
Type: PSSession
Position: Named
-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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet isn't run.
Type: SwitchParameter
Aliases: wi
Position: Named
Outputs
None
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
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
PowerShell
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-Credential
2 Warning
Type: PSCredential
Position: Named
-Destination
Type: String
Position: 1
-Exclude
Type: String[]
Position: Named
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
-Force
Type: SwitchParameter
Position: Named
-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
-LiteralPath
Type: String[]
Aliases: PSPath
Position: Named
-Name
Type: String
Aliases: PSProperty
Position: 2
-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
-Path
Type: String[]
Position: 0
-UseTransaction
Type: SwitchParameter
Aliases: usetx
Position: Named
-WhatIf
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
String
Outputs
None
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
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
This command attaches a debugger to all processes that have names that begin with
SQL.
This command attaches a debugger to the Winlogon, Explorer, and Outlook processes.
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
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.
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.
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
Type: SwitchParameter
Aliases: cf
Position: Named
-Id
Specifies the process IDs of the processes to be debugged. The Id parameter name is
optional.
Position: 0
-InputObject
Type: Process[]
Position: Named
-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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
Int32
Process
String
Outputs
None
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
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
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
None
Outputs
None
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
This command enables System Restore on the C: drive of the local computer.
Example 2: Enable System Restore on multiple drives
PowerShell
This command enables System Restore on the C: and D: drives of the local computer.
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
None
Outputs
None
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 .
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.
Examples
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
Directory: C:\Test
d (directory)
a (archive)
r (read-only)
h (hidden)
s (system).
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
Logs
anotherfile.txt
Command.txt
CreateTestFile.ps1
ReadOnlyFile.txt
PowerShell
Directory: C:\Test\Logs\Adirectory
Directory: C:\Test\Logs\Backup
Directory: C:\Test\Logs
Directory: C:\Test
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.
PowerShell
# When using the -Include parameter, if you don't include an asterisk in the
path
Directory: C:\Test
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\ .
PowerShell
Directory: C:\Test\Logs
Directory: C:\Test\Logs
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 ( * ).
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.
PowerShell
Hive: HKEY_LOCAL_MACHINE\HARDWARE
Name Property
---- --------
ACPI
DESCRIPTION
DEVICEMAP
RESOURCEMAP
UEFI
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.
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
For more information about the Certificate provider and the Cert: drive,
see
about_Certificate_Provider.
PowerShell
Directory: C:\Parent
Directory: C:\Parent\SubDir_Level1
Directory: C:\Parent\SubDir_Level1\SubDir_Level2
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.
PowerShell
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:
Archive
Compressed
Device
Directory
Encrypted
Hidden
IntegrityStream
Normal
NoScrubData
NotContentIndexed
Offline
ReadOnly
ReparsePoint
SparseFile
System
Temporary
! (NOT)
+ (AND)
, (OR)
Don't use spaces between an operator and its attribute. Spaces are accepted after
commas.
D (Directory)
H (Hidden)
R (Read-only)
S (System)
Type: FlagsExpression<T>[FileAttributes]
Position: Named
-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
Type: UInt32
Position: Named
-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
-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.
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
-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
-Filter
Type: String
Position: 1
-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
-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
-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
-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.
Type: String[]
Aliases: PSPath
Position: Named
-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
-Path
Specifies a path to one or more locations. Wildcards are accepted. The default
location is the
current directory ( . ).
Type: String[]
Position: 0
-ReadOnly
To get only read-only items, use the ReadOnly parameter or the Attributes
parameter
ReadOnly property.
Type: SwitchParameter
Aliases: ar
Position: Named
-Recurse
Gets the items in the specified locations and in all child items of the locations.
Type: SwitchParameter
Aliases: s
Position: Named
-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
-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
Inputs
String
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
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
PowerShell
Get-Clipboard
https://en.wikipedia.org/wiki/PowerShell
PowerShell
Directory: C:\Git\PS-Docs\PowerShell-Docs\wmf
Parameters
-Format
Specifies the type, or format, of the clipboard. The acceptable values for this
parameter are:
Text
FileDropList
Image
Audio
Type: ClipboardFormat
Position: Named
-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
-TextFormatType
Specifies the text data format type of the clipboard. The acceptable values for this
parameter are:
Text
UnicodeText
Rtf
Html
CommaSeparatedValue
Type: TextDataFormat
Position: Named
Inputs
None
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
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
PowerShell
Get-ComputerInfo
PowerShell
WindowsCurrentVersion : 6.3
WindowsVersion : 2009
BiosEmbeddedControllerMajorVersion : 1
BiosEmbeddedControllerMinorVersion : 17
BiosSMBIOSMajorVersion : 2
BiosSMBIOSMinorVersion : 8
BiosSystemBiosMajorVersion : 1
BiosSystemBiosMinorVersion : 38
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
Inputs
String[]
You can pipe a string containing the name of a property to this cmdlet.
Outputs
Microsoft.PowerShell.Management.ComputerInfo
Notes
Windows PowerShell includes the following aliases for Get-ComputerInfo :
gin
Get-ComputerRestorePoint
Reference
Module: Microsoft.PowerShell.Management
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
Get-ComputerRestorePoint
PowerShell
Get-ComputerRestorePoint -RestorePoint 4, 5
PowerShell
Get-ComputerRestorePoint -LastStatus
most
recent system restore.
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
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.
PowerShell
((Get-ComputerRestorePoint).SequenceNumber)[-1]
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
-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.
Type: Int32[]
Position: 0
Inputs
None
You can't send objects down the pipeline to Get-ComputerRestorePoint .
Outputs
ManagementObject
Notes
To run a Get-ComputerRestorePoint command on Windows Vista and later versions of
Windows, open
PowerShell with the Run as administrator option.
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
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
PowerShell
This is Line 1
This is Line 2
...
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
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
PowerShell
This is Line 25
PowerShell
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.
PowerShell
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::$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
used to store hidden data such as attributes, security settings, or other data.
PowerShell
The following command gets the content of all *.log files in the C:\Temp directory.
PowerShell
PowerShell
TypeName: System.Byte[]
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
Type: PSCredential
Position: Named
-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
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
Type: String
Position: Named
-Encoding
Specifies the type of encoding for the target file. The default value is Default .
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.
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
Position: Named
-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.
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
-Filter
Type: String
Position: Named
-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
-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
-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.
Type: String[]
Aliases: PSPath
Position: Named
-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
-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
-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
-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
-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
-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
Position: Named
Default value: -1
-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
-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
Inputs
Int64
You can pipe the read count or total count to this cmdlet.
String[]
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
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
Get-ControlPanelItem
...
PowerShell
PowerShell
The Get-ControlPanelItem cmdlet gets the control panel item. The Show-
ControlPanelItem cmdlet
opens it.
PowerShell
PowerShell
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
-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
-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
Inputs
String
Outputs
ControlPanelItem
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
PowerShell
Get-EventLog -List
The Get-EventLog cmdlet uses the List parameter to display the available logs.
PowerShell
The Get-EventLog cmdlet uses the LogName parameter to specify the System event log.
The
Newest parameter returns the five most recent events.
PowerShell
Count Name
----- ----
110 DCOM
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.
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.
PowerShell
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.
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.
PowerShell
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.
PowerShell
$A | Select-Object -Property *
EventID : 10016
MachineName : localhost
Data : {}
Index : 13821
Category : (0)
CategoryNumber : 0
EntryType : Error
Source : DCOM
ReplacementStrings : {Local,...}
InstanceId : 10016
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.
PowerShell
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.
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.
PowerShell
...
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
-AsBaseObject
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
-AsString
Indicates that this cmdlet returns the output as strings, instead of objects.
Type: SwitchParameter
Position: Named
-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
-ComputerName
This parameter specifies a remote computer's NetBIOS name, Internet Protocol (IP)
address, or a
fully qualified domain name (FQDN).
Type: String[]
Aliases: Cn
Position: Named
-EntryType
Specifies, as a string array, the entry type of the events that this cmdlet gets.
Error
Information
FailureAudit
SuccessAudit
Warning
Type: String[]
Aliases: ET
Position: Named
-Index
Specifies the index values to get from the event log. The parameter accepts a
comma-separated string
of values.
Type: Int32[]
Position: Named
-InstanceId
Specifies the Instance IDs to get from the event log. The parameter accepts a
comma-separated string
of values.
Type: Int64[]
Position: 1
-List
Type: SwitchParameter
Position: Named
-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
-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
-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
-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
-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
Inputs
None
Outputs
System.Diagnostics.EventLogEntry. System.Diagnostics.EventLog. System.String
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
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
PowerShell
Get-HotFix
PowerShell
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.
PowerShell
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.
PowerShell
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.
Type: String[]
Position: Named
Specifies a user account that has permission to access the computer and run
commands. The default is
the current user
7 Note
Type: PSCredential
Position: Named
-Description
Get-HotFix uses the Description parameter to specify hotfix types. Wildcards are
permitted.
Type: String[]
Position: Named
-Id
Filters the Get-HotFix results for specific hotfix Ids. Wildcards aren't accepted.
Type: String[]
Aliases: HFID
Position: 0
Inputs
String
Outputs
ManagementObject
Notes
This cmdlet is only available on Windows platforms.
Related Links
about_Arrays
Add-Content
Get-ComputerRestorePoint
Get-Credential
Win32_QuickFixEngineering class
Get-Item
Reference
Module: Microsoft.PowerShell.Management
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
PowerShell
Get-Item .
Directory: C:\
PowerShell
Get-Item *
Directory: C:\ps-test
PowerShell
Get-Item C:
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.
PowerShell
(Get-Item C:\Windows).LastAccessTime
Get-Item
HKLM:\Software\Microsoft\Powershell\1\Shellids\Microsoft.Powershell\
PowerShell
Parameters
-CodeSigningCert
Type: SwitchParameter
Position: Named
-Credential
7 Note
Type: PSCredential
Position: Named
-DnsName
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.
Type: DnsNameRepresentation
Position: Named
-DocumentEncryptionCert
Type: SwitchParameter
Position: Named
Default value: None
-Eku
Type: String
Position: Named
-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
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.
Type: Int32
Position: Named
-Filter
Type: String
Position: Named
-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
-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
-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.
Type: String[]
Aliases: PSPath
Position: Named
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
-SSLServerAuthentication
Type: SwitchParameter
Position: Named
-Stream
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.
Type: String[]
Position: Named
-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
Inputs
String
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
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
PowerShell
Get-ItemProperty C:\Windows
PowerShell
PowerShell
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.
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\
PowerShellVersion : 2.0
RuntimeVersion : v2.0.50727
CTPVersion : 5
PSCompatibleVersion : 1.0,2.0
Parameters
-Credential
7 Note
Type: PSCredential
Position: Named
-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
-Filter
Type: String
Position: Named
-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
-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.
Type: String[]
Aliases: PSPath
Position: Named
-Name
Type: String[]
Aliases: PSProperty
Position: 1
-Path
Type: String[]
Position: 0
Default value: None
-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
Inputs
String
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
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
PowerShell
94253-50000-11141-AA785
PowerShell
PowerShell
Name : C:\
FullName : C:\
Parent :
Exists : True
Root : C:\
Extension :
Mode : d--hs-
BaseName : C:\
Target : {}
LinkType :
Parameters
-Credential
2 Warning
Type: PSCredential
Position: Named
-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
-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
-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
-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
-Name
Type: String[]
Aliases: PSProperty
Position: 1
-Path
Type: String[]
Position: 0
-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
Inputs
String
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
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.
PowerShell
Path
----
C:\Windows
Path
----
HKLM:\Software\Microsoft
Path
----
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:\Windows>Push-Location System32
C:\Windows\System32\WindowsPowerShell>Get-Location -Stack
Path
----
C:\Windows
C:\
Path
----
C:\Windows\System32
PowerShell
PS C:\>
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
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
-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
-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
-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
-UseTransaction
Type: SwitchParameter
Aliases: usetx
Position: Named
Inputs
None
Outputs
PathInfo
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 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
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.
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 .
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.
$A = Get-Process
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 ).
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.
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.
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.
$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 third command uses the GetOwner method to get the owner of the process in $p .
The output
reveals that the owner is Domain01\user01 .
Get-Process 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.
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
-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.
Type: SwitchParameter
Position: Named
-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
-IncludeUserName
Indicates that the UserName value of the Process object is returned with results of
the command.
Type: SwitchParameter
Position: Named
-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
-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
-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
Inputs
Process
Outputs
Process
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
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.
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
PS C:\> Get-PSDrive
Alias Alias
Cert Certificate \
Env Environment
Function Function
Variable Variable
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:).
PS C:\foo> Get-PSDrive D
A A:\
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.
} else {
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.
A A:\
X Registry HKLM:\Network
----------------------------------------------------------------------------
---
A: 4
C: 3 Windows 988877418496
771926069248
D: 3 Big! 1990045179904
689684144128
E: 5
G: 4 \\Music\GratefulDead 988877418496
771926069248
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
Type: String[]
Position: 0
-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
-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
-Scope
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.
Type: String
Position: Named
-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
Inputs
None
Outputs
PSDriveInfo
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
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
Get-PSProvider
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
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.
Path
----
C:\Users\User01
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
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
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
each
service.
PowerShell
Get-Service
PowerShell
Get-Service "wmi*"
PowerShell
PowerShell
PowerShell
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 .
PowerShell
Get-Service |
Where-Object {$_.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.
To list running services first, use the Descending parameter of the Sort-Object cmdlet.
PowerShell
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.
PowerShell
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
-DependentServices
Indicates that this cmdlet gets only the services that depend upon the specified
service.
Type: SwitchParameter
Aliases: DS
Position: Named
Default value: None
-DisplayName
Type: String[]
Position: Named
-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
-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
-InputObject
Type: ServiceController[]
Position: Named
-Name
Type: String[]
Aliases: ServiceName
Position: 0
-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
Position: Named
Inputs
ServiceController
String
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
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
Get-TimeZone
This command gets all time zones that match the specified wildcard.
Get-TimeZone -ListAvailable
Parameters
-Id
Specifies, as a string array, the ID or IDs of the time zones that this cmdlet gets.
Type: String[]
Position: Named
Type: SwitchParameter
Position: Named
-Name
Specifies, as a string array, the name or names of the time zones that this cmdlet
gets.
Type: String[]
Position: 0
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
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
Start-Transaction
Get-Transaction
Error 1 Active
This command uses the Get-Transaction cmdlet to get the current transaction.
Get-Transaction | Get-Member
This command uses the Get-Member cmdlet to show the properties and methods of the
transaction
object.
Set-Location hklm:\software
Start-Transaction
Undo-Transaction
Get-Transaction
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
Complete-Transaction
Get-Transaction
Error 1 Committed
This command shows the property values of a transaction object for a transaction that
has been
committed.
Set-Location hklm:\software
Start-Transaction
Start-Transaction
Get-Transaction
Error 2 Active
Complete-Transaction
Get-Transaction
Error 1 Active
Complete-Transaction
Get-Transaction
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.
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.
The first Complete-Transaction command does not commit the transaction, but it
reduces the
subscriber count to 1.
Set-Location hklm:\software
Start-Transaction
Get-Transaction
Start-Transaction -Independent
Get-Transaction
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.
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.
Inputs
None
Outputs
PSTransaction
Related Links
Complete-Transaction
Start-Transaction
Undo-Transaction
Use-Transaction
New-Item
Get-WmiObject
Reference
Module: Microsoft.PowerShell.Management
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
Examples
PowerShell
PowerShell
PowerShell
PowerShell
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.
PowerShell
PowerShell
Status : OK
SMBIOSPresent : True
__GENUS : 2
__CLASS : Win32_BIOS
__SUPERCLASS : CIM_BIOSElement
__DYNASTY : CIM_ManagedSystemElement
__PROPERTY_COUNT : 27
__SERVER : Server01
__NAMESPACE : root\cimv2
BuildNumber :
CodeSet :
CurrentLanguage : en|US|iso8859-1
IdentificationCode :
InstallableLanguages : 1
InstallDate :
LanguageEdition :
ListOfLanguages : {en|US|iso8859-1}
PrimaryBIOS : True
ReleaseDate : 20101103000000.000000+000
SerialNumber : 8VDM9P1
SMBIOSBIOSVersion : A05
SMBIOSMajorVersion : 2
SMBIOSMinorVersion : 6
SoftwareElementState : 3
TargetOperatingSystem : 0
Version : DELL - 15
Scope : System.Management.ManagementScope
Options : System.Management.ObjectGetOptions
ClassPath : \\JUNE-PC\root\cimv2:Win32_BIOS
Site :
Container :
PowerShell
7 Note
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
-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.
Type: SwitchParameter
Position: Named
-Authentication
0 : Default
1 : None (No authentication in performed.)
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
Position: Named
-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
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
-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
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
[email protected] . Or, enter a
PSCredential object, such as an object that is returned
Type: PSCredential
Position: Named
-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
-EnableAllPrivileges
Enables all the privileges of the current user before the command makes the WMI
call.
Type: SwitchParameter
Position: Named
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.
Type: String
Position: Named
-Impersonation
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.
Type: ImpersonationLevel
Position: Named
Default value: None
-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
-Locale
Specifies the preferred locale for WMI objects. Enter a value in MS_<LCID> format.
Type: String
Position: Named
-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
-Property
Specifies the WMI class properties that this cmdlet gets information from. Enter the
property names.
Type: String[]
Position: 1
-Query
Runs the specified WMI Query Language (WQL) statement. This parameter does not
support event
queries.
Type: String
Position: Named
-Recurse
Searches the current namespace and all other namespaces for the class name that is
specified by the
Class parameter.
Type: SwitchParameter
Position: Named
-ThrottleLimit
Type: Int32
Position: Named
Inputs
None
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
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"
PowerShell
Invoke-Item "C:\Users\User1\Documents\*.xls"
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-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
-Filter
Type: String
Position: Named
-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
-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.
Type: String[]
Aliases: PSPath
Position: Named
-Path
Specifies the path to the selected item.
Wildcard characters are permitted.
Type: String[]
Position: 0
-UseTransaction
Type: SwitchParameter
Aliases: usetx
Position: Named
-WhatIf
Type: SwitchParameter
Aliases: wi
Position: Named
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
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
([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.
([Wmiclass]'Win32_Process').GetMethodParameters('Create')
__GENUS : 2
__CLASS : __PARAMETERS
__SUPERCLASS :
__DYNASTY : __PARAMETERS
__RELPATH :
__PROPERTY_COUNT : 3
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH :
CommandLine :
CurrentDirectory :
ProcessStartupInformation :
PSComputerName :
__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.
__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.
PowerShell
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
-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.
Type: SwitchParameter
Position: Named
-Authentication
Specifies the authentication level to be used with the WMI connection. The
acceptable values for
this parameter are:
-1 : Unchanged
0 : Default
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
Position: Named
-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
Type: String
Position: Named
-Class
Type: String
Position: 0
-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
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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
[email protected] . Or, enter a
PSCredential object, such as an object that is returned
Type: PSCredential
Position: Named
Indicates that this cmdlet enables all the privileges of the current user before the
command makes
the WMI call.
Type: SwitchParameter
Position: Named
-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.)
the caller.)
Type: ImpersonationLevel
Position: Named
-InputObject
Type: ManagementObject
Position: Named
-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
-Name
Specifies the name of the method to be invoked. This parameter is mandatory and
cannot be null or
empty.
Type: String
Position: 1
-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
-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
-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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Default value: False
Inputs
None
Outputs
None
Related Links
Get-WSManInstance
Invoke-WSManAction
New-WSManInstance
Remove-WSManInstance
Get-WmiObject
Remove-WmiObject
Set-WmiInstance
Join-Path
Reference
Module: Microsoft.PowerShell.Management
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
path\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
path\childpath
Existing directory separators \ and handled so there is only one separator between
Path and ChildPath
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.
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
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.
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
-Credential
7 Note
Type: PSCredential
Position: Named
-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
-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
-UseTransaction
Type: SwitchParameter
Aliases: usetx
Position: Named
Inputs
String
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
This command ensures that events in the Security log on the Server01 and Server02
computers are
retained for at least 7 days.
Get-EventLog -List
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
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-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).
Type: Int64
Position: Named
-OverflowAction
Specifies what happens when the event log reaches its maximum size.
DoNotOverwrite : Existing entries are retained and new entries are discarded.
the
MinimumRetentionDays property. If there are no events older than
specified by the
MinimumRetentionDays property value, new events are
discarded.
Type: OverflowAction
Aliases: OFA
-RetentionDays
Specifies the minimum number of days that an event must remain in the event log.
Type: Int32
Aliases: MRD
Position: Named
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
None
Notes
To use this cmdlet on Windows Vista and later versions of Windows, open
Windows PowerShell with
the Run as administrator option.
Related Links
Clear-EventLog
Get-EventLog
Limit-EventLog
New-EventLog
Remove-EventLog
Show-EventLog
Write-EventLog
Move-Item
Reference
Module: Microsoft.PowerShell.Management
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
PowerShell
PowerShell
PowerShell
PowerShell
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
PowerShell
PowerShell
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
Type: SwitchParameter
Aliases: cf
Position: Named
7 Note
Type: PSCredential
Position: Named
-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
-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
-Filter
Type: String
Position: Named
-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
-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
-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.
Type: String[]
Aliases: PSPath
Position: Named
-PassThru
Returns an object representing the moved item. By default, this cmdlet does not
generate any output.
Type: SwitchParameter
Position: Named
-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
-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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
String
Outputs
None
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
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
PowerShell
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-Credential
7 Note
Type: PSCredential
Position: Named
-Destination
Type: String
Position: 1
-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
-Filter
Type: String
Position: Named
-Force
Type: SwitchParameter
Position: Named
-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
-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
-Name
Type: String[]
Aliases: PSProperty
Position: 2
-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
Type: String[]
Position: 0
-UseTransaction
Type: SwitchParameter
Aliases: usetx
Position: Named
-WhatIf
Type: SwitchParameter
Aliases: wi
Position: Named
Outputs
None
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
PowerShell
PowerShell
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
-ComputerName
Creates the new event logs on the specified computers. The default is the local
computer.
Type: String[]
Aliases: CN
Position: 3
-LogName
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
-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
-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
-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
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.
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.
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
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
PowerShell
PowerShell
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.
PowerShell
7 Note
When you create a file using this method, the resulting file is encoded as UTF-8
without a
byte-order-mark (BOM).
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
PowerShell
PowerShell
Directory: C:\Temp
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.
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.
PowerShell
Directory: C:\
Directory: C:\TestFolder
PS> New-Item ./TestFile.txt -ItemType File -Value 'This is just a test file'
Directory: C:\Source\Test
Directory: C:\Source\Test
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.
Type: String
Position: Named
-Authentication
This is a dynamic parameter made available by the WSMan provider. The WSMan
provider and
this parameter are only available on Windows.
Type: Microsoft.WSMan.Management.AuthenticationMechanism
Position: Named
-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.
Type: String
Position: Named
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-ConnectionURI
This is a dynamic parameter made available by the WSMan provider. The WSMan
provider and
this parameter are only available on Windows.
Type: Uri
Position: Named
-Credential
7 Note
Type: PSCredential
Position: Named
-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
-ItemType
Specifies the provider-specified type of the new item. The available values of this
parameter depend
on the current provider you are using.
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).
Certificate Provider
Certificate
Store
StoreLocation
Type: String
Aliases: Type
Position: Named
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
-Options
This is a dynamic parameter made available by the Alias provider. For more
information, see
New-Alias.
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
Type: ScopedItemOptions
Position: Named
-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.
Type: Hashtable
Aliases: OS
Position: Named
-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
-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
-SessionOption
This is a dynamic parameter made available by the WSMan provider. The WSMan
provider and
this parameter are only available on Windows.
Type: Microsoft.WSMan.Management.SessionOption
Aliases: SO
Position: Named
-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.
Type: SwitchParameter
Position: Named
-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
-Value
Specifies the value of the new item. You can also pipe a value to New-Item .
Type: Object
Aliases: Target
Position: Named
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet isn't run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
Object
You can pipe a value for the new item to this cmdlet.
Outputs
Object
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
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.
Examples
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
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
PowerShell
PowerShell
"@
$newValue.multistring
PowerShell
$newValue.multistring[0]
a
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-Credential
7 Note
Type: PSCredential
Position: Named
-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
-Filter
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
-Force
Type: SwitchParameter
Position: Named
-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
-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.
Type: String[]
Aliases: PSPath
Position: Named
-Name
Aliases: PSProperty
Position: 1
-Path
Type: String[]
Position: 0
-PropertyType
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.
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
-UseTransaction
Type: SwitchParameter
Aliases: usetx
Position: Named
-Value
Type: Object
Position: Named
-WhatIf
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
None
Outputs
PSCustomObject
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
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.
PowerShell
$parameters = @{
Name = "MyDocs"
PSProvider = "FileSystem"
Root = "C:\Users\User01\Documents"
New-PSDrive @parameters
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.
PowerShell
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.
PowerShell
Net Use
---------------------------------------------------------
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:
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
# 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
X FileSystem X:\
# Get-Member cmdlet shows that the drives have the same object type,
# System.Management.Automation.PSDriveInfo.
TypeName: System.Management.Automation.PSDriveInfo
...
Net Use
Get-CimInstance Win32_NetworkConnection
--------------------------------------------------------
deviceid
--------
C:
D:
X:
PowerShell
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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.
7 Note
Type: PSCredential
Position: Named
Default value: Current user
-Description
To see the descriptions of all the session's drives, Get-PSDrive | Format-Table Name,
Description .
Type: String
Position: Named
-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
-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 .
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
-PSProvider
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 .
Type: String
Position: 1
-Root
Type: String
Position: 2
-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
-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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet isn't run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
None
Outputs
PSDriveInfo
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
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
$params = @{
Name = "TestService"
DependsOn = "NetLogon"
StartupType = "Manual"
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.
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.
# - or -
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.
Type: String
Position: 1
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-Credential
Specifies the account used by the service as the
Service Logon Account.
7 Note
Type: PSCredential
Position: Named
-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
-Description
Type: String
Position: Named
Default value: None
-DisplayName
Type: String
Position: Named
-Name
Type: String
Aliases: ServiceName
Position: 0
-StartupType
Sets the startup type of the service. The acceptable values for this parameter are:
Type: ServiceStartMode
Position: Named
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
None
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
PowerShell
PowerShell
$URI = "http://www.dneonline.com/calculator.asmx?wsdl"
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.
TypeName: WSProxy.Calculator
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.
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
-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: PSCredential
Aliases: Cred
Position: Named
-Namespace
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
-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
Position: 0
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
Inputs
None
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
PS C:\> Pop-Location
This command changes your location to the location most recently added to the current
stack.
This command changes your location to the location most recently added to the Stack2
location stack.
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
-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
-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
Outputs
None
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 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
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.
Examples
Example 1
This example pushes the current location onto the default location stack and then
changes the
location to C:\Windows .
PowerShell
Example 2
This example pushes the current location onto the RegFunction stack and changes the
current location
to the HKLM:\Software\Policies location.
PowerShell
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
PowerShell
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.
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
-PassThru
Passes an object representing the location to the pipeline. By default, this cmdlet
does not
generate any output.
Type: SwitchParameter
Position: Named
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
-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
the current
location stack.
Type: String
Position: Named
-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
Inputs
String
You can pipe a string that contains a path (but not a literal path) to this cmdlet.
Outputs
None
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 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
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.
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
PowerShell
PowerShell
$wmiParameters = @{
SourceIdentifier = "WMIProcess"
MessageData = "Test 01"
TimeOut = 500
Register-WmiEvent @wmiParameters
PowerShell
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.
PowerShell
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
-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
-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
-Credential
Specifies a user account that has permission to perform this action. The default is the
current
user.
Type: PSCredential
Position: Named
-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
-MaxTriggerCount
Type: Int32
Position: Named
-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
-Namespace
Type: String
Aliases: NS
Position: Named
-Query
Specifies a query in WMI Query Language (WQL) that identifies the WMI event class,
such as:
select * from __InstanceDeletionEvent .
Type: String
Position: 0
-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
-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.
Position: Named
-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
Inputs
None
Outputs
None
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
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 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
PowerShell
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.
PowerShell
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.
Position: Named
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-Force
Type: SwitchParameter
Position: Named
-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: PSCredential
Position: Named
-PassThru
Returns the results of the command. Otherwise, this cmdlet does not generate any
output.
Type: SwitchParameter
Position: Named
-Restart
Indicates that this cmdlet restarts the computers that are being removed. A restart is
often
required to make the change effective.
Type: SwitchParameter
Position: Named
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.
To specify a user account that has permission to connect to the remote computers,
use the
LocalCredential parameter.
Type: PSCredential
Aliases: Credential
Position: 0
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
-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.
Type: String
Position: Named
Inputs
String
Outputs
ComputerChangeInfo
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
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
This command deletes the MyLog event log from the local computer and unregisters its
event sources.
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.
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.
PowerShell
Get-EventLog -List
Get-EventLog -List
The first command lists the event logs on the local computer.
The third command lists the event logs again. The ZapLog event log no longer appears
in the list.
MyApp
TestApp
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
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
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
None
Outputs
None
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
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
PowerShell
Remove-Item C:\Test\*.*
PowerShell
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.
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.
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
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
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
PowerShell
Get-ChildItem
Directory: C:\temp\Downloads
Directory: C:\temp\Downloads
Get-ChildItem
Directory: C:\temp\Downloads
PowerShell
Get-Item C:\Test\Copy-Script.ps1 -Stream Zone.Identifier
FileName: \\C:\Test\Copy-Script.ps1
Stream Length
------ ------
Zone.Identifier 26
At line:1 char:1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ 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
7 Note
Type: PSCredential
Position: Named
-DeleteKey
When provided, the cmdlet deletes the private key when the certificate is deleted.
Type: SwitchParameter
Position: Named
-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
-Filter
Type: String
Position: Named
-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
-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
-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.
Type: String[]
Aliases: PSPath
Position: Named
-Path
Position: 0
-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
Type: SwitchParameter
Position: Named
-Stream
Position: Named
-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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet isn't run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
String
You can pipe a string that contains a path, but not a literal path, to this cmdlet.
Outputs
None
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
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
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
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
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
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-Credential
7 Note
Type: PSCredential
Position: Named
-Exclude
Type: String[]
Position: Named
-Filter
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
-Force
Type: SwitchParameter
Position: Named
-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
-LiteralPath
Type: String[]
Aliases: PSPath
Position: Named
-Name
Aliases: PSProperty
Position: 1
-Path
Specifies the path of the item whose properties are being removed.
Wildcard
characters are permitted.
Type: String[]
Position: 0
-UseTransaction
Type: SwitchParameter
Aliases: usetx
Position: Named
-WhatIf
Aliases: wi
Position: Named
Inputs
String
You can pipe a string that contains a path, but not a literal path, to this cmdlet.
Outputs
None
Notes
Windows PowerShell includes the following aliases for Remove-ItemProperty :
rp
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
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.
Examples
PowerShell
PowerShell
Get-PSDrive X, S | Remove-PSDrive
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
Type: SwitchParameter
Position: Named
-LiteralName
Type: String[]
Position: 0
-Name
Specifies the names of the drives to remove. Do not type a colon ( : ) after the drive
name.
Type: String[]
Position: 0
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
-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
Type: String
Position: Named
-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
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
PSDriveInfo
You can pipe a drive object, such as from the Get-PSDrive cmdlet, to this cmdlet.
Outputs
None
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
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
notepad
$np | Remove-WmiObject
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.
PowerShell
$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
-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
Type: AuthenticationLevel
Position: Named
-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
-Class
Type: String
Position: 0
-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
Type: SwitchParameter
Aliases: cf
Position: Named
-Credential
Specifies a user account that has permission to perform this action. The default is the
current
user.
Type: PSCredential
Position: Named
-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
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
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
Position: Named
-InputObject
Type: ManagementObject
Position: Named
-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
-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
-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
-ThrottleLimit
Type: Int32
Position: Named
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
ManagementObject
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.
Examples
PowerShell
The DomainCredential parameter specifies the credentials of a user who has permission
to rename
computers in the domain.
PowerShell
Parameters
-ComputerName
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 .
Type: String
Position: Named
-Confirm
Aliases: cf
Position: Named
-DomainCredential
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
-Force
Type: SwitchParameter
Position: Named
Specifies a user account that has permission to connect to the computer specified by
the
ComputerName parameter. The default is the current user.
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
-NewName
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
-PassThru
Type: SwitchParameter
Position: Named
-Protocol
Type: String
Position: Named
-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
-WhatIf
Type: SwitchParameter
Aliases: wi
Position: Named
-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
2 Warning
Type: String
Position: Named
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
RenameComputerChangeInfo
Related Links
Add-Computer
Remove-Computer
Reset-ComputerMachinePassword
Restart-Computer
Stop-Computer
Rename-Item
Reference
Module: Microsoft.PowerShell.Management
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
PowerShell
PowerShell
At line:1 char:12
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.
PowerShell
PowerShell
Get-ChildItem *.txt
Directory: C:\temp\files
Get-ChildItem *.log
Directory: C:\temp\files
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
Type: SwitchParameter
Aliases: cf
Position: Named
-Credential
7 Note
Type: PSCredential
Position: Named
-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
-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.
Type: String
Aliases: PSPath
Position: Named
-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
-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
-Path
Type: String
Position: 0
-UseTransaction
Type: SwitchParameter
Aliases: usetx
Position: Named
-WhatIf
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
String
Outputs
None
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
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
PowerShell
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-Credential
Type: PSCredential
Position: Named
-Exclude
Type: String[]
Position: Named
-Filter
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
-Force
Type: SwitchParameter
Position: Named
-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
-LiteralPath
Type: String
Aliases: PSPath
Position: Named
-Name
Type: String
Aliases: PSProperty
Position: 1
-NewName
Type: String
Position: 2
-PassThru
Type: SwitchParameter
Position: Named
-Path
Type: String
Position: 0
-UseTransaction
Type: SwitchParameter
Aliases: usetx
Position: Named
-WhatIf
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
String
You can pipe a string that contains a path, but not a literal path, to this cmdlet.
Outputs
None
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
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
Reset-ComputerMachinePassword
This command resets the computer password for the local computer. The command
runs with the
credentials of the current user.
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.
$cred = Get-Credential
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Outputs
None
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
PowerShell
PS C:\> Resolve-Path ~
Path
----
C:\Users\User01
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.
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 .
This command resolves a Universal Naming Convention (UNC) path and returns the
shares in the path.
.\Program Files
.\programs.txt
This command returns relative paths for the directories at the root of the C: drive.
PowerShell
Parameters
-Credential
Specifies a user account that has permission to perform this action. The default is the
current
user.
Type: PSCredential
Position: Named
-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
-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
-Relative
Type: SwitchParameter
Position: Named
-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
Inputs
String
Outputs
PathInfo
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
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
PowerShell
Restart-Computer
parameter accepts an
array of computer names.
PowerShell
PowerShell
$Job | Receive-Job
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.
authentication
settings.
PowerShell
PowerShell
$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.
seconds) for
PowerShell to become available on the restarted computer before it
continues.
PowerShell
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.
These settings are designed for enterprises in which DCOM-based restarts fail because
DCOM is
blocked. For example, by a firewall.
PowerShell
Server01.
The Protocol parameter specifies to use the WSMan protocol. The
WsmanAuthentication
parameter specifies the authentication method as Kerberos.
Parameters
-AsJob
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
-ComputerName
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.
Type: String[]
Position: 0
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-Credential
Specifies a user account that has permission to do this action. The default is the
current user.
Type: PSCredential
Position: 1
-DcomAuthentication
Specifies the authentication level that is used for the WMI connection. Restart-
Computer uses WMI.
Type: AuthenticationLevel
Aliases: Authentication
Position: Named
-Delay
This parameter is valid only together with the Wait and For parameters.
If the Delay parameter isn't specified, Restart-Computer uses a five second delay.
Type: Int16
Position: Named
-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.
Type: WaitForServiceTypes
-Force
Type: SwitchParameter
Aliases: f
Position: Named
-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
Position: Named
-Protocol
Specifies which protocol to use to restart the computers. The valid values are
WSMan and
DCOM.
Type: String
Position: Named
-ThrottleLimit
Type: Int32
Position: Named
-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.
Type: Int32
Aliases: TimeoutSec
Position: Named
-Wait
Restart-Computer suppresses the PowerShell prompt and blocks the pipeline until
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.
Type: SwitchParameter
Position: Named
-WhatIf
Type: SwitchParameter
Aliases: wi
Position: Named
Default value: 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.
2 Warning
Type: String
Position: Named
Inputs
String
You can pipe a string that contains a computer name to this cmdlet.
Outputs
None
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
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
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
This command restarts the services that have a display name that starts with Net, except
for the Net
Logon 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
Type: SwitchParameter
Aliases: cf
Position: Named
-DisplayName
Type: String[]
Position: Named
-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
-Force
Type: SwitchParameter
Position: Named
-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
-InputObject
Type: ServiceController[]
Position: 0
Default value: None
-Name
Type: String[]
Aliases: ServiceName
Position: 0
-PassThru
Returns an object that represents the service. By default, this cmdlet does not
generate any output.
Type: SwitchParameter
Position: Named
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
ServiceController
String
You can pipe a string that contains a service name to this cmdlet.
Outputs
None
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
Related Links
Get-Service
New-Service
Resume-Service
Set-Service
Start-Service
Stop-Service
Suspend-Service
Restore-Computer
Reference
Module: Microsoft.PowerShell.Management
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
This command restores the local computer to the restore point that has sequence
number 253.
Confirm
[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.
Get-ComputerRestorePoint
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.
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
Default value: 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
Position: 0
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
None
Outputs
None
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
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
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.
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
Aliases: cf
Position: Named
-DisplayName
Type: String[]
Position: Named
-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
-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
-InputObject
Type: ServiceController[]
Position: 0
-Name
Type: String[]
Aliases: ServiceName
Position: 0
-PassThru
Returns an object that represents the service. By default, this cmdlet does not
generate any output.
Type: SwitchParameter
Position: Named
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
ServiceController
String
You can pipe a string that contains a service name to this cmdlet.
Outputs
None
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
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
PowerShell
PowerShell
Parameters
-Append
Indicates that the cmdlet does not clear the clipboard and appends content to it.
Type: SwitchParameter
Position: Named
-AsHtml
Indicates that the cmdlet renders the content as HTML to the clipboard.
Type: SwitchParameter
Position: Named
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-Path
Specifies the path to the item that is copied to the clipboard. Wildcard characters are
permitted.
Type: String[]
Position: Named
-Value
Type: String[]
Position: 0
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
String
You can pipe a string containing the content to set to the clipboard to this cmdlet.
Outputs
None
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
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
If you need to create files or directories for the following examples, see New-Item.
Examples
PowerShell
Test1.txt
Test2.txt
Test3.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.
PowerShell
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.
Warning
Caution
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.
The following command set the content all *.txt files in the C:\Temp
directory to the
Value empty.
PowerShell
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-Credential
7 Note
Type: PSCredential
Position: Named
-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 .
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 .
Type: FileSystemCmdletProviderEncoding
Position: Named
-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
-Filter
Type: String
Position: Named
-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
-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
-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.
Type: String[]
Aliases: PSPath
Position: Named
-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
-PassThru
Returns an object that represents the content. By default, this cmdlet does not
generate any output.
Type: SwitchParameter
Position: Named
-Path
Type: String[]
Position: 0
-Stream
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 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.
Type: String
Position: Named
-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
-Value
Type: Object[]
Position: 1
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
Object
You can pipe an object that contains the new value for the item to this cmdlet.
Outputs
None
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 ,
it converts the object to a string before writing it. To write objects to
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
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
PowerShell
PowerShell
PowerShell
Set-Item -Path function:prompt -Value {'PS '+ (Get-Date -Format t) + " " +
(Get-Location) + '> '}
PowerShell
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-Credential
7 Note
Type: PSCredential
Position: Named
Default value: Current user
-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
-Filter
Type: String
Position: Named
-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
-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
-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.
Type: String[]
Aliases: PSPath
Position: Named
-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.
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
Type: ScopedItemOptions
Position: Named
-PassThru
Type: SwitchParameter
Position: Named
-Path
Type: String[]
Position: 0
-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:
REG_RESOURCE_LIST values.
Type: RegistryValueKind
Position: Named
-UseTransaction
Type: SwitchParameter
Aliases: usetx
Position: Named
-Value
Type: Object
Position: 1
-WhatIf
Type: SwitchParameter
Aliases: wi
Position: Named
You can pipe an object that represents the new value of the item to this cmdlet.
Outputs
None
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
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.
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
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
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
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
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
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 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 .
PowerShell
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-Credential
7 Note
Type: PSCredential
Position: Named
-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
-Filter
Type: String
Position: Named
-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
-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
-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
-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.
Aliases: PSPath
Position: Named
-Name
Type: String
Aliases: PSProperty
Position: 1
-PassThru
Type: SwitchParameter
Position: Named
-Path
Type: String[]
Position: 0
-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:
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.
null characters.
Used for REG_MULTI_SZ values.
Qword : Specifies a 64-bit binary number. Used for REG_QWORD values.
Type: RegistryValueKind
Position: Named
-UseTransaction
Type: SwitchParameter
Aliases: usetx
Position: Named
-Value
Type: Object
Position: 2
-WhatIf
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
PSObject
Outputs
None
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
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 HKLM:\>
This command sets the current location to the root of the HKLM: drive.
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.
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
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
-PassThru
Returns a PathInfo object that represents the location. By default, this cmdlet does
not
generate any output.
Type: SwitchParameter
Position: Named
-Path
Type: String
Position: 0
-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
-UseTransaction
Type: SwitchParameter
Aliases: usetx
Position: Named
Inputs
String
You can pipe a string that contains a path, but not a literal path, to this cmdlet.
Outputs
None
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 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 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
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
PowerShell
PowerShell
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.
Name : BITS
Name : BITS
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
PowerShell
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.
PowerShell
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.
PowerShell
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
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-Description
Type: String
Position: Named
-DisplayName
Type: String
Aliases: DN
Position: Named
Default value: None
-InputObject
Type: ServiceController
Position: Named
-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
-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
-StartupType
Sets the startup type of the service. The acceptable values for this parameter are:
Type: ServiceStartMode
Position: Named
-Status
Type: String
Position: Named
-WhatIf
Shows what would happen if Set-Service runs. The cmdlet isn't run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
ServiceController
String
You can pipe a string that contains a service name to this cmdlet.
Outputs
None
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
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
Id : UTC
BaseUtcOffset : 00:00:00
SupportsDaylightSavingTime : False
PowerShell
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 .
PowerShell
Get-TimeZone -ListAvailable
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-Id
Type: String
Position: Named
-InputObject
Type: TimeZoneInfo
Position: 0
-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
-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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
String
TimeZoneInfo
Outputs
None
TimeZoneInfo
When you use the PassThru parameter, this cmdlet returns a TimeZoneInfo object.
Related Links
Get-TimeZone
Set-WmiInstance
Reference
Module: Microsoft.PowerShell.Management
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
__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.
__GENUS : 2
__CLASS : Win32_Environment
__SUPERCLASS : CIM_SystemResource
__DYNASTY : CIM_ManagedSystemElement
__RELPATH : Win32_Environment.Name="testvar",UserName="<SYSTEM>"
__PROPERTY_COUNT : 8
__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.
__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:
Type: Hashtable
Position: Named
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
-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
client.
5 : PacketIntegrity.
All the data that is transferred between the client and the
Type: AuthenticationLevel
Position: Named
-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
-Class
Type: String
Position: 0
-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
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-Credential
Specifies a user account that has permission to perform this action. The default is the
current
user.
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
-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
-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
Position: Named
-InputObject
Type: ManagementObject
Position: Named
-Locale
Type: String
Position: Named
-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
-Path
Specifies a WMI object path of the instance that you want to create or update.
Type: String
Position: Named
-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
Position: Named
-ThrottleLimit
Type: Int32
Position: Named
-WhatIf
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
None
Outputs
None
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
PowerShell
PowerShell
cmdlet opens
it.
PowerShell
appwiz.cpl
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
-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
-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
Inputs
System.String, Microsoft.PowerShell.Commands.ControlPanelItem
You can pipe a name or control panel item object to this cmdlet.
Outputs
None
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
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
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
Inputs
None
Outputs
None
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
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
HKCU:
This command returns only the qualifier of the path. The qualifier is the drive.
Example 2: Display file names
PowerShell
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.
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.
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
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.
Parameters
-Credential
7 Note
Type: PSCredential
Position: Named
-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
-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
-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
-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
-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
-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
-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
-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
-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
Inputs
String
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
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
PowerShell
PowerShell
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.
PowerShell
PowerShell
PowerShell
$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.
PowerShell
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
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
-Credential
Specifies a user account that has permission to perform this action. By default, the
cmdlet uses the
credentials of the current user.
7 Note
Aliases: RunAs
Position: Named
-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
-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
-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
-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
-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
-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
-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
-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
-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.
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
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
-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
Position: Named
-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
Inputs
None
Outputs
None
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.
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 .
Related Links
about_Quoting_Rules
Debug-Process
Get-Process
Start-Service
Stop-Process
Wait-Process
Start-Service
Reference
Module: Microsoft.PowerShell.Management
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
PowerShell
PowerShell
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.
PowerShell
$s = Get-Service wmi
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.
PowerShell
At line:1 char:14
ExitCode : 0
Name : TlntSvr
ProcessId : 0
StartMode : Disabled
State : Stopped
Status : OK
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
Type: SwitchParameter
Aliases: cf
Position: Named
-DisplayName
Specifies the display names of the services to start. Wildcard characters are
permitted.
Type: String[]
Position: Named
-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
-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
-InputObject
Type: ServiceController[]
Position: 0
-Name
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
-PassThru
Returns an object that represents the service. By default, this cmdlet does not
generate any output.
Type: SwitchParameter
Position: Named
-WhatIf
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
ServiceController
String
You can pipe a string that contains the service name to this cmdlet.
Outputs
None
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
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
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.
feature in
Windows PowerShell. For more information, see about_Transactions.
Examples
Set-Location hkcu:\software
Start-Transaction
Undo-Transaction
These commands start and then roll back a transaction. Because the transaction is rolled
back, no
changes are made to the registry.
Set-Location hkcu:\software
Start-Transaction
Complete-Transaction
These commands start and then complete a transaction. No changes are made to the
registry until the
Complete-Transaction command is used.
Set-Location HKCU:\software
Start-Transaction
Start-Transaction
New-Item : The registry key at the specified path does not exist.
At line:1 char:9
New-Item : Cannot use transaction. The transaction has been rolled back or
has timed out.
At line:1 char:9
New-Item : The registry key at the specified path does not exist.
At line:1 char:9
Hive: HKEY_CURRENT_USER\Software
0 0 ContosoCompany {}
Complete-Transaction
# Succeeds
Set-Location HKCU:\software
Start-Transaction
Start-Transaction
Get-Transaction
Complete-Transaction
Complete-Transaction
Get-Transaction
Error 2 Active
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.
Start-Transaction
Start-Transaction -Independent
Get-Transaction
Undo-Transaction
Complete-Transaction
Get-ChildItem contoso*
Get-Transaction
Error 1 Active
Undo-Transaction
MyKey
-----
123
Complete-Transaction
Get-ChildItem contoso*
Hive: HKEY_CURRENT_USER\Software
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.
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.
Set-Location hkcu:\software
Start-Transaction
New-Item "ContosoCompany2"
Get-ChildItem contoso*
Hive: HKEY_CURRENT_USER\Software
0 0 ContosoCompany2 {}
Complete-Transaction
Get-ChildItem contoso*
Hive: HKEY_CURRENT_USER\Software
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.
Start-Transaction -Timeout 2
Get-Transaction
Start-Transaction -Timeout 2
Get-Transaction
Error 1 RolledBack
New-Item : Cannot use transaction. The transaction has been rolled back or
has timed out.
At line:1 char:9
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
Type: SwitchParameter
Aliases: cf
Position: Named
Default value: 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.
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
-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-
error occurs.
Never
The transaction is never rolled back automatically.
The default value is Error .
Type: RollbackSeverity
Position: Named
-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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Outputs
None
Related Links
Complete-Transaction
Get-Transaction
Undo-Transaction
Use-Transaction
Stop-Computer
Reference
Module: Microsoft.PowerShell.Management
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
PowerShell
PowerShell
$results = $j | Receive-Job
$results
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.
Stop-Computer uses the ComputerName parameter to specify the remote computer. The
PowerShell
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.
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
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.
Type: SwitchParameter
Position: Named
-ComputerName
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[]
Position: 0
-Confirm
Aliases: cf
Position: Named
-Credential
Specifies a user account that has permission to do this action. The default is the
current user.
7 Note
Type: PSCredential
Position: 1
-DcomAuthentication
Specifies the authentication level that this cmdlet uses with WMI. Stop-Computer uses
WMI. The
default value is Packet.
Type: AuthenticationLevel
Aliases: Authentication
Position: Named
-Force
Type: SwitchParameter
Position: Named
-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:
Type: ImpersonationLevel
Position: Named
-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.
Type: String
Position: Named
-ThrottleLimit
The throttle limit applies only to the current command, not to the session or to the
computer.
Type: Int32
Position: Named
Default value: None
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet isn't run.
Type: SwitchParameter
Aliases: wi
Position: Named
-WsmanAuthentication
Specifies the mechanism that is used to authenticate the user credentials when this
cmdlet uses the
WSMan protocol. The default value is Default.
Basic
CredSSP
Default
Digest
Kerberos
Negotiate.
U Caution
Type: String
Position: Named
Inputs
None
Outputs
None
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
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
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.
Confirm
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help
(default is "Y"):y
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.
calc
Stop-Process -InputObject $p
This series of commands starts and stops the Calc process, and then detects processes
that have
stopped.
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 .
At line:1 char:34
Warning!
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help
(default is "Y"):
[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
Type: SwitchParameter
Aliases: cf
Position: Named
-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
Type: SwitchParameter
Position: Named
Default value: None
-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
-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
-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
-PassThru
Returns an object that represents the process. By default, this cmdlet does not
generate any output.
Type: SwitchParameter
Position: Named
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
Process
Outputs
None
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
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
This command stops the Performance Logs and Alerts (SysmonLog) service on the local
computer.
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.
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
Type: SwitchParameter
Aliases: cf
Position: Named
-DisplayName
Type: String[]
Position: Named
-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
-Force
Forces the cmdlet to stop a service even if that service has dependent services.
Type: SwitchParameter
Position: Named
-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
-InputObject
Type: ServiceController[]
Position: 0
-Name
Specifies the service names of the services to stop. Wildcard characters are
permitted.
Type: String[]
Aliases: ServiceName
Position: 0
-NoWait
Type: SwitchParameter
Position: Named
-PassThru
Returns an object that represents the service. By default, this cmdlet does not
generate any output.
Type: SwitchParameter
Position: Named
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
ServiceController
String
You can pipe a string that contains the name of a service to this cmdlet.
Outputs
None
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
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
This command suspends the Telnet service (Tlntsvr) service on the local computer.
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.
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.
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
Type: SwitchParameter
Aliases: cf
Position: Named
-DisplayName
Specifies the display names of the services to be suspended. Wildcard characters are
permitted.
Type: String[]
Position: Named
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
-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
-InputObject
Type: ServiceController[]
Position: 0
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
-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
-WhatIf
Type: SwitchParameter
Aliases: wi
Position: Named
String
You can pipe a string that contains a service name to this cmdlet.
Outputs
None
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
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.
This cmdlet works much like NetDom.exe . Both NetDom and Test-ComputerSecureChannel
use the
NetLogon service to perform the actions.
Examples
Test-ComputerSecureChannel
This command tests the channel between the local computer and the domain to which it
is joined.
True
Test-ComputerSecureChannel -Repair
This command resets the channel between the local computer and its domain.
Test-ComputerSecureChannel -Verbose
True
This command uses the Verbose common parameter to request detailed messages
about the operation.
For more information about Verbose, see
about_CommonParameters.
else {
&(.\Get-Servers.ps1)
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-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
-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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
None
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
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.
Examples
PowerShell
PowerShell
PowerShell
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.
PowerShell
PowerShell
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.
PowerShell
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.
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
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.
Type: SwitchParameter
Position: Named
-BufferSize
Specifies the size, in bytes, of the buffer sent with this command. The default value is
32.
Type: Int32
Position: Named
Default value: 32
-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
Type: String[]
Position: 0
-Count
Position: Named
Default value: 4
-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
-DcomAuthentication
Specifies the authentication level that this cmdlet uses with WMI.
Test-Connection
uses WMI.
The acceptable values for this parameter are:
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
Position: Named
-Delay
Type: Int32
Position: Named
-Impersonation
Specifies the impersonation level to use when this cmdlet calls WMI. Test-
Connection uses WMI.
Type: ImpersonationLevel
Position: Named
Default value: Impersonate
-Protocol
Specifies a protocol. The acceptable values for this parameter are DCOM and
WSMan.
Type: String
Position: Named
-Quiet
The Quiet parameter returns a Boolean value in a System.Boolean object. Using this
parameter suppresses all errors.
Type: SwitchParameter
Position: Named
-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[]
Position: 1
-ThrottleLimit
The throttle limit applies only to the current command, not to the session or to the
computer.
Type: Int32
Position: Named
Default value: 32
-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
-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.
Type: String
Position: Named
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.
Related Links
Add-Computer
Restart-Computer
Stop-Computer
Test-Path
Reference
Module: Microsoft.PowerShell.Management
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
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 .
False
True
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
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 .
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 .
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
True
PowerShell
Test-Path $null
Test-Path @()
At line:1 char:11
+ Test-Path $null
+ ~~~~~
+ FullyQualifiedErrorId :
ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands
.TestPathCommand
PowerShell
Test-Path ''
True
At line:1 char:11
+ Test-Path ''
+ ~~
+ FullyQualifiedErrorId :
ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.C
ommands.TestPathCommand
Parameters
-Credential
7 Note
Type: PSCredential
Position: Named
-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
-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
-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
-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
-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
-NewerThan
Type: Nullable<T>[[DateTime]]
Position: Named
-OlderThan
Type: Nullable<T>[[DateTime]]
Position: Named
-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
-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:
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.
Type: TestPathType
Aliases: Type
Position: Named
-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
Inputs
String
You can pipe a string that contains a path, but not a literal path, to this cmdlet.
Outputs
Boolean
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
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.
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
Undo-Transaction
This command rolls back the current, active, transaction.
Set-Location hkcu:\software
Start-Transaction
Undo-Transaction
This example starts a transaction and then rolls it back. As a result, no changes are made
to the
registry.
Set-Location hkcu:\software
Start-Transaction
Get-Transaction
Error 1 Active
Start-Transaction
Get-Transaction
Error 2 Active
Undo-Transaction
Get-Transaction
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 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
Type: SwitchParameter
Aliases: cf
Position: Named
-WhatIf
Shows what would happen if the cmdlet runs.
The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
None
Outputs
None
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
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.
Windows
PowerShell. For more information, see about_Transactions.
Examples
Start-Transaction
$transactedString = New-Object
Microsoft.PowerShell.Commands.Management.TransactedString
$transactedString.Append("Hello")
$transactedString.ToString()
Hello
Hello, World
Complete-Transaction
$transactedString.ToString()
Hello, World
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 final command uses the ToString method to display the resulting value of the
variable as a
string.
Start-Transaction
$transactedString = New-Object
Microsoft.PowerShell.Commands.Management.TransactedString
$transactedString.Append("Hello")
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
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
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
-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
Inputs
None
Outputs
PSObject
Related Links
Complete-Transaction
Get-Transaction
Start-Transaction
Undo-Transaction
Wait-Process
Reference
Module: Microsoft.PowerShell.Management
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 .
Examples
Example 1: Stop a process and wait
PowerShell
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.
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.
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[]
Position: 0
-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
-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
-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
Inputs
Process
Outputs
None
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
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
This command writes an event from the MyApp source to the Application event log.
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
-ComputerName
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
-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.
Type: EventLogEntryType
Aliases: ET
Position: 3
-EventId
Specifies the event identifier. This parameter is required. The maximum value for the
EventId
parameter is 65535.
Type: Int32
Position: 2
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
-Message
Type: String
Aliases: MSG
Position: 4
-RawData
Specifies the binary data that is associated with the event, in bytes.
Type: Byte[]
Aliases: RD
Position: Named
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
Inputs
None
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
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.
(CRUD)
operations, non-CRUD actions, and association manipulation.
Export-ODataEndpointProxy generates one CDXML file per endpoint resource. You can
Examples
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
Type: SwitchParameter
Position: 10
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
-CmdletAdapter
Specifies the cmdlet adapter. The acceptable values for this parameter are:
ODataAdapter and
NetworkControllerAdapter.
Type: String
Position: 6
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-CreateRequestMethod
Specifies the request method. The acceptable values for this parameter are: PUT,
POST, and PATCH.
Type: String
Position: 4
-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
-CustomData
Type: Hashtable
Position: 9
-Force
Indicates that this cmdlet overwrites an existing generated module of the same
name in an existing
Modules folder.
Type: SwitchParameter
Position: 8
-Headers
Specifies the headers of the web request. Enter a hash table or dictionary.
Type: Hashtable
Position: 12
-MetadataUri
Type: String
Position: 2
-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
Type: String
Position: 1
-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.
Type: Hashtable
Position: 7
-UpdateRequestMethod
Specifies the update request method. The acceptable values for this parameter are:
PUT, POST, and
PATCH.
Type: String
Position: 5
Default value: None
-Uri
Type: String
Position: 0
-WhatIf
Type: SwitchParameter
Aliases: wi
Position: Named
Related Links
OData Library
What is the OData Protocol?
Invoke-RestMethod
Microsoft.PowerShell.Operation.
Validation
Reference
Microsoft.PowerShell.Operation.Validation
Get-OperationValidation 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
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 Examples
This command gets validation tests from the module named AddNumbers in the
C:\temp\modules folder.
Parameters
-ModuleName
Type: String[]
Position: 1
-TestType
Simple
Comprehensive
Type: String[]
Position: Named
Outputs
PSCustomObject
Related Links
Invoke-OperationValidation
Invoke-OperationValidation
Reference
Module: Microsoft.PowerShell.Operation.Validation
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
Module: OperationValidation
Result Name
------- --------
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
Type: SwitchParameter
Aliases: cf
Position: Named
-IncludePesterOutput
Type: SwitchParameter
Position: Named
-ModuleName
Type: String[]
Position: Named
-testFilePath
Type: String[]
Position: Named
Specifies a custom object that specifies the path to the file and the name of the test
to run.
Type: PSObject[]
Position: Named
-TestType
Simple
Comprehensive
Type: String[]
Position: Named
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
PSCustomObject
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.
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 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
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
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.
PowerShell
PS Cert:\CurrentUser\> Get-ChildItem
PowerShell
$c = Get-Item cert:\LocalMachine\My\52A149D0393CE8A8D4AF0B172ED667A9E3A1F44E
Output
DnsNameList : {SERVER01.contoso.com}
SendAsTrustedIssuer : False
PowerShell
PowerShell
PowerShell
-SSLServerAuthentication
PowerShell
-Recurse -ExpiringInDays 0}
PowerShell
$_.SendAsTrustedIssuer -and `
$_.NotAfter -gt $ValidThrough
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"
Copy-Item : Provider operation stopped because the provider does not support
this operation.
At line:1 char:1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
PSNotSupportedException
+ FullyQualifiedErrorId : NotSupported,
Microsoft.PowerShell.Commands.CopyItemCommand
Moving Certificates
Move-Item will not move certificate stores and it will not move certificates
to a different
The returned certificates are piped to the Move-Item cmdlet, which moves the
certificates to the WebHosting store.
PowerShell
-Destination cert:\LocalMachine\WebHosting
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
PowerShell
PowerShell
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
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
PowerShell
-Path cert:\LocalMachine\My\D2D38EBA60CAA1C12055A2E1C83B15AD450110C2 `
-DeleteKey
PowerShell
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.
PowerShell
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
-ComputerName Server01
PowerShell
$cred = Get-Credential
-Issuer 1b3fd224d66c6413fe20d21e38b304226d192dfe `
PowerShell
-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
CodeSigningCert
<System.Management.Automation.SwitchParameter>
Cmdlets supported
Get-Item
Get-ChildItem
Cmdlets supported
Remove-Item
This parameter deletes the associated private key when it deletes the
certificate.
) Important
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.
DocumentEncryptionCert
<System.Management.Automation.SwitchParameter>
Cmdlets supported
Get-Item
Get-ChildItem
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.
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.
ItemType <System.String>
This parameter allows you to specify the type of item created by New-Item .
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.
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.
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.
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
See also
about_Providers
about_Signing
Get-AuthenticodeSignature
Set-AuthenticodeSignature
Get-PfxCertificate
ConvertFrom-SecureString
Reference
Module: Microsoft.PowerShell.Security
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.
Examples
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.
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.
$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)
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
Type: Byte[]
Position: Named
-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
-SecureString
Type: SecureString
Position: 0
Inputs
SecureString
Outputs
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
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.
Examples
PowerShell
PS C:\> $Secure
System.Security.SecureString
PS C:\> $Encrypted
01000000d08c9ddf0115d1118c7a00c04fc297eb010000001a114d45b8dd3f4aa11ad7c0abda
e98000000000
02000000000003660000a8000000100000005df63cea84bfb7d70bd6842e7efa798200000000
04800000a000
000010000000f10cd0f4a99a8d5814d94e0687d7430b100000008bf11f1960158405b2779613
e9352c6d1400
0000e6b7bf46a9d485ff211b9b2a2df3bd6eb67aae41
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.
PowerShell
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.
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
-Force
Confirms that you understand the implications of using the AsPlainText parameter
and still want
to use it.
Type: SwitchParameter
Position: 2
-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
-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
-String
Type: String
Position: 0
Inputs
String
You can pipe a standard encrypted string to this cmdlet.
Outputs
SecureString
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
PowerShell
Get-Acl C:\Windows
PowerShell
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
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
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.
PowerShell
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.
PowerShell
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.
Type: SwitchParameter
Position: Named
-Audit
Gets the audit data for the security descriptor from the system access control list
(SACL).
Type: SwitchParameter
Position: Named
-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
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
-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
-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.
Type: PSObject
Position: Named
-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.
Type: String[]
Aliases: PSPath
Position: Named
-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.
Type: String[]
Position: 1
-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
Inputs
String
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
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:
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
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
This command gets information about the Authenticode signature in the NewScript.ps1
file. It uses
the FilePath parameter to specify the file.
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.
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.
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
-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
-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
-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
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
$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-----
Parameters
-Content
Type: String
Position: 0
-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
-Path
Type: String
Position: 1
Default value: None
Related Links
about_Providers
Protect-CmsMessage
Unprotect-CmsMessage
Get-Credential
Reference
Module: Microsoft.PowerShell.Security
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
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.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
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.
Example 4
PowerShell
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"
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
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
trust the remote computer and the application or script requesting it.
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.
7 Note
Type: PSCredential
Position: 1
-Message
Type: String
Position: Named
-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.
Type: String
Position: 1
Inputs
None
Outputs
PSCredential
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
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.
Examples
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.
PowerShell
Get-ExecutionPolicy -List
Scope ExecutionPolicy
----- ---------------
MachinePolicy Undefined
UserPolicy Undefined
Process Undefined
CurrentUser AllSigned
LocalMachine RemoteSigned
PowerShell
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.
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
PowerShell
PS> Get-ExecutionPolicy
RemoteSigned
PS> .\Start-ActivityTracker.ps1
At line:1 char:1
+ .\Start-ActivityTracker.ps1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ FullyQualifiedErrorId : UnauthorizedAccess
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 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.
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
-Scope
Type: ExecutionPolicyScope
Position: 0
Inputs
None
Outputs
ExecutionPolicy
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
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
Password: ******
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
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
-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
Inputs
String
Outputs
X509Certificate2
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 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
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
-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
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
String
You can pipe a string that is used as the catalog filename to this cmdlet.
Outputs
FileInfo
Notes
This cmdlet is only available on Windows platforms.
Related Links
Test-FileCatalog
PowerShellGet
Protect-CmsMessage
Reference
Module: Microsoft.PowerShell.Security
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
PowerShell
{[Version]
[Strings]
szOID_ENHANCED_KEY_USAGE = "2.5.29.37"
szOID_DOCUMENT_ENCRYPTION = "1.3.6.1.4.1.311.80.1"
[NewRequest]
Subject = "[email protected]"
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%"
# 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
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.
PS C:\> cd Cert:\CurrentUser\My
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
-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
-OutFile
Specifies the path and file name of a file to which you want to send the encrypted
content.
Type: String
Position: 2
-Path
Type: String
Position: 1
Default value: None
-To
Specifies one or more CMS message recipients, identified in any of the following
formats:
Type: CmsMessageRecipient[]
Position: 0
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
Examples
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.
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.
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.
$isProtected = $true
$preserveInheritance = $true
$NewAcl.SetAccessRuleProtection($isProtected, $preserveInheritance)
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.
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.
# Set properties
$identity = "BUILTIN\Administrators"
$fileSystemRights = "FullControl"
$type = "Allow"
$NewAcl.SetAccessRule($fileSystemAccessRule)
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
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
-CentralAccessPolicy
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.
Type: String
Position: 2
-ClearCentralAccessPolicy
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.
Type: SwitchParameter
Position: Named
Default value: False
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-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
-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
-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.
Type: PSObject
Position: 0
-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.
Type: String[]
Aliases: PSPath
Position: Named
-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
-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.
is included in the
security object.
Type: String[]
Position: 0
-UseTransaction
Type: SwitchParameter
Aliases: usetx
Position: Named
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
ObjectSecurity
CommonSecurityDescriptor
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
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
PowerShell
$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
PowerShell
$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.
Type: X509Certificate2
Position: 1
Default value: None
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-FilePath
Type: String[]
Position: 1
-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
-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.
Type: String
Position: Named
-IncludeChain
Determines which certificates in the certificate trust chain are included in the digital
signature.
NotRoot is the default.
Type: String
Position: Named
-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
-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
-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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
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
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.
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
Get-ExecutionPolicy -List
Scope ExecutionPolicy
----- ---------------
MachinePolicy Undefined
UserPolicy Undefined
Process Undefined
CurrentUser RemoteSigned
LocalMachine RemoteSigned
PowerShell
overridden by the Group Policy applied to your system. Due to the override,
your shell will retain
Hive: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds
Name Property
---- --------
Microsoft.PowerShell Path :
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
ExecutionPolicy : Restricted
PowerShell
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.
PowerShell
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.
PowerShell
Get-ExecutionPolicy -List
Scope ExecutionPolicy
----- ---------------
MachinePolicy Undefined
UserPolicy Undefined
Process Undefined
CurrentUser Undefined
LocalMachine RemoteSigned
policy.
The Scope parameter specifies the CurrentUser. To view the execution policy
settings, use
the Get-ExecutionPolicy cmdlet with the List parameter.
PowerShell
Scope ExecutionPolicy
----- ---------------
MachinePolicy Undefined
UserPolicy Undefined
Process AllSigned
CurrentUser RemoteSigned
LocalMachine RemoteSigned
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
PowerShell
PS> Get-ExecutionPolicy
RemoteSigned
PS> .\Start-ActivityTracker.ps1
At line:1 char:1
+ .\Start-ActivityTracker.ps1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ FullyQualifiedErrorId : UnauthorizedAccess
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 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.
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
Type: SwitchParameter
Aliases: cf
Position: Named
-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.
Type: ExecutionPolicy
Position: 0
-Force
Suppresses all the confirmation prompts. Use caution with this parameter to avoid
unexpected
results.
Type: SwitchParameter
Position: Named
Specifies the scope that is affected by an execution policy. The default scope is
LocalMachine.
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
Position: 1
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
ExecutionPolicy
String
You can pipe a string that contains the name of an execution policy to this cmdlet.
Outputs
None
Notes
Set-ExecutionPolicy doesn't change the MachinePolicy and UserPolicy scopes because
they
are set by Group Policies.
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.
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.
Examples
Valid
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
Type: SwitchParameter
Aliases: cf
Position: Named
-Detailed
Type: SwitchParameter
Position: Named
-FilesToSkip
Type: String[]
Position: Named
-Path
A folder or array of files that should be validated against the catalog file.
Type: String[]
Position: 1
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
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
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
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'
Parameters
-Content
Position: 0
-EventLogRecord
Type: PSObject
Position: 0
-IncludeContext
Type: SwitchParameter
Position: Named
-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
-Path
Type: String
Position: 0
-To
Specifies one or more CMS message recipients, identified in any of the following
formats:
Type: CmsMessageRecipient[]
Position: 1
Inputs
EventLogRecord
String
You can pipe an object containing encrypted content to this cmdlet.
Outputs
String
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.
ConvertFrom-StringData Converts a string containing one or more key and value pairs to
a hash table.
ConvertTo-Html Converts .NET objects into HTML that can be displayed in a Web
browser.
Format-Wide Formats objects as a wide table that displays only one property
of each object.
Get-FileHash Computes the hash value for a file by using a specified hash
algorithm.
Get-PSBreakpoint Gets the breakpoints that are set in the current session.
Group-Object Groups objects that contain the same value for specified
properties.
Import-PowerShellDataFile Imports values from a .PSD1 file without invoking its contents.
Measure-Command Measures the time it takes to run script blocks and cmdlets.
Set-Date Changes the system time on the computer to a time that you
specify.
Set-Variable Sets the value of a variable. Creates the variable if one with the
requested name does not exist.
Update-List Adds items to and removes items from a property value that
contains a collection of objects.
Wait-Debugger Stops a script in the debugger before running the next statement
in the script.
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
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 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.Status
Done
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.Size
2394
PowerShell
$A = "A string"
$A.StringUse
Display
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
$A.SizeInMB()
0.43
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
$d = [ordered]@{Name="Server30";System="Server Core";PSVersion="4.0"}
Name Value
---- -----
Name Server30
PSVersion 4.0
PowerShell
$obj = [pscustomobject]@{
Name = 'Doris'
Age = '20'
$obj | Get-Member
$obj
TypeName: System.Management.Automation.PSCustomObject
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.
PowerShell
$user = [pscustomobject]@{
Name = 'User1'
Age = 29
StartDate = [datetime]'2019-05-05'
Position = [pscustomobject]@{
DepartmentName = 'IT'
Role = 'Manager'
$addMemberSplat = @{
MemberType = 'ScriptProperty'
Name = 'Title'
$user | Get-Member
TypeName: System.Management.Automation.PSCustomObject
Name : User1
Age : 29
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
-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
-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
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
Position: 0
-Name
Type: String
Position: 1
Type: IDictionary
Position: 0
-NotePropertyName
Type: String
Position: 0
-NotePropertyValue
Type: Object
Position: 1
-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.
Type: SwitchParameter
Position: Named
-SecondValue
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
-TypeName
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.
Type: String
Position: Named
-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
Inputs
PSObject
Outputs
None
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
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
PowerShell
$Source = @"
return (a + b);
return (a * b);
"@
[BasicTest]::Add(4, 3)
$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
...
TypeName: BasicTest
$BasicTestObject | Get-Member
TypeName: BasicTest
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 .
PowerShell
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.
PowerShell
$Signature = @"
"@
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.
command
output.
PowerShell
[VBFromFile]::SayHello(", World")
# From Hello.vb
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.
PowerShell
Add-Type @'
class FRectangle {
$rect = [FRectangle]::new()
$rect
Length Height
------ ------
0 0
PowerShell
Add-Type -Path "FSharp.Compiler.CodeDom.dll"
$FSharpCode = @"
"@
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
-CodeDomProvider
Type: CodeDomProvider
Aliases: Provider
Position: Named
-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
-IgnoreWarnings
Ignores compiler warnings. Use this parameter to prevent Add-Type from handling
compiler warnings
as errors.
Type: SwitchParameter
Position: Named
-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
Position: Named
Default value: CSharp
-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
-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
-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
-Namespace
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
-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
-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.
ConsoleApplication
Library
WindowsApplication
Type: OutputAssemblyType
Aliases: OT
Position: Named
-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
-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
-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.
Type: String[]
Aliases: RA
Position: Named
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
-UsingNamespace
Specifies other namespaces that are required for the class. This is much like the C#
keyword,
Using .
Type: String[]
Aliases: Using
Position: Named
Inputs
None
Outputs
None
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 .
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
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
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.
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
Type: SwitchParameter
Aliases: cf
Position: Named
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
-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
-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
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
-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
-Scope
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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
None
Outputs
None
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
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.
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
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
InputObject SideIndicator
----------- -------------
cat =>
racoon =>
dog <=
squirrel <=
Because the command uses the ExcludeDifferent parameter, the output only contains
lines
contained in both files, as shown by the SideIndicator ( == ).
PowerShell
$objects = @{
InputObject SideIndicator
----------- -------------
bird ==
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.
PowerShell
$a = $True
Compare-Object -IncludeEqual $a $a
InputObject SideIndicator
----------- -------------
True ==
TypeName: System.Management.Automation.PSCustomObject
True
TypeName: System.Boolean
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.
PowerShell
Compare-Object -ReferenceObject 'abc' -DifferenceObject 'xyz' -Property
Length -IncludeEqual
Length SideIndicator
------ -------------
3 ==
PowerShell
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) ==
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
InputObject SideIndicator
----------- -------------
00:00:01 ==
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
Type: SwitchParameter
Position: Named
-Culture
Position: Named
-DifferenceObject
Type: PSObject[]
Position: 1
-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.
Type: SwitchParameter
Position: Named
-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
-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
-Property
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:
Type: Object[]
Position: Named
Type: PSObject[]
Position: 0
-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
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
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.
PowerShell
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 = $J[1..($J.count - 1)]
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]
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.
PowerShell
(Get-Culture).TextInfo.ListSeparator
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
-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
-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
-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
Inputs
String
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
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.
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
DisplayHint : 2
Day : 13
DayOfWeek : 5
DayOfYear : 13
Hour : 20
Kind : 2
Millisecond : 400
Minute : 6
Month : 1
Second : 31
Ticks : 634620819914009002
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.
PowerShell
[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.
PowerShell
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
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
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.
Examples
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.
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.
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.
$user = [ADSI]"LDAP://CN=username,CN=Users,DC=domain,DC=com"
The first command uses Active Directory Service Interfaces (ADSI) to get the user object
and saves it in the variable.
It uses the -Type parameter to specify that SDDL string represents an Active Directory
security descriptor.
Parameters
-Sddl
Type: String
Position: 0
-Type
FileSystemRights
RegistryRights
ActiveDirectoryRights
MutexRights
SemaphoreRights
CryptoKeyRights
EventWaitHandleRights
Type: Object
Position: Named
Inputs
String
Related Links
Security Descriptor Definition Language
ConvertFrom-String
Reference
Module: Microsoft.PowerShell.Utility
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.
Examples
P1 P2
-- --
Hello World
This command generates an object with default property names, P1 and P2.
PowerShell
TypeName: System.Management.Automation.PSCustomObject
PowerShell
P1 P2
-- --
Contoso Administrator
PowerShell
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 = @'
'@
$testText = @'
'@
$PersonalData
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.
425-123-6789
(206) 987-4321
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.
PowerShell
$template = @'
'@
$testText = @'
'@
$PersonalData
$PersonalData | Get-Member
TypeName: System.Management.Automation.PSCustomObject
The Get-Member cmdlet is used to show that the age property is an integer.
Parameters
-Delimiter
Type: String
Aliases: DEL
Position: Named
-IncludeExtent
Indicates that this cmdlet includes an extent text property that is removed by default.
Type: SwitchParameter
Aliases: IE
Position: Named
-InputObject
Specifies strings received from the pipeline, or a variable that contains a string
object.
Type: String
Position: 0
-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
-TemplateContent
Type: String[]
Aliases: TC
Position: Named
-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
-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
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.
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 = @'
'@
Name Value
---- -----
PowerShell
Name = Disks.ps1
# Category is optional.
Category = Storage
Cost = Free
'@
Name Value
---- -----
Cost Free
Category Storage
Name Disks.ps1
PowerShell
$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.
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
---- -----
StringData
and the result in the $Hash variable.
PowerShell
$Here = @'
'@
$Hash
Name Value
---- -----
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
Name : Vincentio
PowerShell
Name Value
---- -----
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
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
Inputs
String
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
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
"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.
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.
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.
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.
$ExamplePatterns = @(
Id: ProcessName
4368: AGSService
4420: AppleMobileDeviceService
...
11140: git-bash
0: Idle
...
...
13028: WmiPrvSE
2724: WUDFHost
2980: WUDFHost
3348: WUDFHost
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.
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.
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.
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:
7 Note
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
-InputObject
Type: String
Position: Named
Default value: None
Inputs
String
Outputs
String
Related Links
ConvertFrom-String
ConvertTo-Csv
Get-Process
Out-String
Select-Object
ConvertTo-Csv
Reference
Module: Microsoft.PowerShell.Utility
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
PowerShell
"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.
PowerShell
$Date = Get-Date
"DisplayHint";"DateTime";"Date";"Day";"DayOfWeek";"DayOfYear";"Hour";"Kind";
"Millisecond";"Minute";"Month";"Second";"Ticks";"TimeOfDay";"Year"
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.
PowerShell
(Get-Culture).TextInfo.ListSeparator
"Message","Id","Version","Qualifiers","Level","Task","Opcode","Keywords","Re
cordId", ...
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
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
-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
-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
-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
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.
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
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.
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.
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.
Get-Process |
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.
<html>
<head>
<title>HTML TABLE</title>
...
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.
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.
<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>
<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.
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.
$htmlParams = @{
Body = Get-Date
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
Position: Named
-Body
Specifies the text to add after the opening <BODY> tag. By default, there is no text in
that
position.
Type: String[]
Position: 3
-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
Position: Named
-Fragment
Generates only an HTML table. The <HTML> , <HEAD> , <TITLE> , and <BODY> tags are
omitted.
Type: SwitchParameter
Position: Named
-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
-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
-PostContent
Specifies text to add after the closing </TABLE> tag. By default, there is no text in that
position.
Type: String[]
Position: Named
-PreContent
Specifies text to add before the opening <TABLE> tag. By default, there is no text in
that
position.
Type: String[]
Position: Named
-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:
FormatString - <string>
Width - <int32> - must be greater than 0
Type: Object[]
Position: 0
-Title
Specifies a title for the HTML file, that is, the text that appears between the <TITLE>
tags.
Type: String
Position: 2
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:
Related Links
about_Calculated_Properties
ConvertTo-Csv
ConvertTo-Json
ConvertTo-Xml
Export-Clixml
Import-Clixml
ConvertTo-Json
Reference
Module: Microsoft.PowerShell.Utility
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.
Examples
Example 1
PowerShell
(Get-UICulture).Calendar | ConvertTo-Json
"MinSupportedDateTime": "\/Date(-62135596800000)\/",
"MaxSupportedDateTime": "\/Date(253402300799999)\/",
"AlgorithmType": 1,
"CalendarType": 1,
"Eras": [
],
"TwoDigitYearMax": 2029,
"IsReadOnly": false
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
"DisplayHint": 2,
"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
Example 4
PowerShell
DisplayHint : 2
DayOfWeek : 5
DayOfYear : 285
Hour : 22
Kind : 2
Millisecond : 768
Minute : 55
Month : 10
Second : 52
Ticks : 636749817527683372
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
Type: SwitchParameter
Position: Named
-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
-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
Inputs
Object
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
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.
Examples
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:
Type: String
Position: Named
-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
-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
-NoTypeInformation
Type: SwitchParameter
Position: Named
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
Related Links
ConvertTo-Csv
ConvertTo-Html
Export-Clixml
Get-Date
Import-Clixml
Debug-Runspace
Reference
Module: Microsoft.PowerShell.Utility
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
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
PowerShell
At C:\TestWFVar1.ps1:83 char:1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
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
Type: SwitchParameter
Aliases: cf
Position: Named
-Id
Specifies the ID number of a runspace. You can run Get-Runspace to show runspace
IDs.
Type: Int32
Position: 0
-InstanceId
Specifies a runspace by its instance ID, a GUID that you can show by running Get-
Runspace .
Type: Guid
Position: 0
-Name
Specifies a runspace by its name. You can run Get-Runspace to show the names of
runspaces.
Type: String
Position: 0
-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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
Runspace
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.
Related Links
about_Debuggers
Debug-Job
Get-Runspace
Get-Process
Enter-PSHostProcess
Enter-PSSession
Disable-PSBreakpoint
Reference
Module: Microsoft.PowerShell.Utility
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
PowerShell
$B | Disable-PSBreakpoint
As a result of this command, the value of the Enabled property of the breakpoint object
in $B
is False.
PowerShell
Disable-PSBreakpoint -Id 0
PowerShell
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.
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
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-PassThru
Returns an object representing the enabled breakpoints. By default, this cmdlet does
not generate
any output.
Type: SwitchParameter
Position: Named
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Outputs
None
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
Disable-RunspaceDebug
Get-RunspaceDebug
Parameters
-AppDomainName
The name of the application domain that hosts the PowerShell runspace.
Type: String[]
Position: 1
-ProcessName
Type: String
Position: 0
Type: Runspace[]
Position: 0
-RunspaceId
Type: Int32[]
Position: 0
-RunspaceInstanceId
Type: Guid[]
Position: 0
-RunspaceName
Type: String[]
Position: 0
Default value: None
Related Links
Enable-RunspaceDebug
Get-RunspaceDebug
Enable-PSBreakpoint
Reference
Module: Microsoft.PowerShell.Utility
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.
PowerShell
Get-PSBreakpoint | Enable-PSBreakpoint
PowerShell
Enable-PSBreakpoint -Id 0, 1, 5
PowerShell
$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.
we see that
the value of the Enabled property is True.
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.
Parameters
-Breakpoint
Type: Breakpoint[]
Position: 0
-Confirm
Aliases: cf
Position: Named
-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
-PassThru
Returns an object representing the breakpoint being enabled. By default, this cmdlet
doesn't
generate any output.
Type: SwitchParameter
Position: Named
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet isn't run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
Breakpoint
Outputs
None
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
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
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
Enable-RunspaceDebug
Get-RunspaceDebug
Parameters
-AppDomainName
The name of the application domain that hosts the PowerShell runspace.
Type: String[]
Position: 1
-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
-ProcessName
Type: String
Position: 0
-Runspace
Type: Runspace[]
Position: 0
-RunspaceId
Type: Int32[]
Position: 0
Type: Guid[]
Position: 0
-RunspaceName
Type: String[]
Position: 0
Related Links
Disable-RunspaceDebug
Get-RunspaceDebug
Export-Alias
Reference
Module: Microsoft.PowerShell.Utility
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
This command exports current alias information to a file named Alias.csv in the current
directory.
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.
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
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
-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
Position: Named
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-Description
Type: String
Position: Named
-Force
Overwrites the output file, even if the read-only attribute is set on the file.
The Force parameter cannot force Export-Alias to overwrite files with the hidden
attribute.
Type: SwitchParameter
Position: Named
-LiteralPath
Type: String
Aliases: PSPath
Position: Named
-Name
Specifies the names as an array of the aliases to export.
Wildcards are permitted.
Type: String[]
Position: 1
-NoClobber
Indicates that this cmdlet prevents Export-Alias from overwriting any files, even if
the Force parameter is used in the command.
NoClobber does not prevent the Append parameter from adding content to an
existing file.
Type: SwitchParameter
Aliases: NoOverwrite
Position: Named
-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
-Path
Type: String
Position: 0
-Scope
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)
Type: String
Position: Named
-WhatIf
Aliases: wi
Position: Named
Inputs
None
Outputs
None
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
Related Links
Get-Alias
Import-Alias
New-Alias
Set-Alias
Export-Clixml
Reference
Module: Microsoft.PowerShell.Utility
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.
Examples
PowerShell
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.
PowerShell
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.
PowerShell
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.
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
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-Encoding
Specifies the type of encoding for the target file. The default value is Unicode.
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.
Type: String
Position: Named
-Force
Causes the cmdlet to clear the read-only attribute of the output file if necessary. The
cmdlet will
attempt to reset the read-only attribute when the command completes.
Type: SwitchParameter
Position: Named
-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
-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
-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
-Path
Specifies the path to the file where the XML representation of the object will be
stored.
Type: String
Position: 0
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet isn't run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
PSObject
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
PowerShell
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
"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.
PowerShell
"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
"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.
PowerShell
#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.
PowerShell
"DisplayName","Status"
"Application Identity","Running"
"Windows Audio","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.
PowerShell
"DateTime","Day","DayOfWeek","DayOfYear"
"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.
PowerShell
At line:1 char:15
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ FullyQualifiedErrorId :
FileOpenFailure,Microsoft.PowerShell.Commands.ExportCsvCommand
"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 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
The appended object does not have a property that corresponds to the
following column:
the command.
At line:1 char:22
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ FullyQualifiedErrorId :
CannotAppendCsvWithMismatchedPropertyNames,Microsoft.PowerShell. ...
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
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.
Type: SwitchParameter
Position: Named
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-Delimiter
Type: Char
Position: 1
-Encoding
Specifies the encoding for the exported CSV file. The default value is ASCII .
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.
Type: String
Position: Named
-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
-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
-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
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
-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
-Path
A required parameter that specifies the location to save the CSV output file.
Type: String
Position: 0
-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
-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
Inputs
PSObject
You can pipe any object with an Extended Type System (ETS) adapter to this cmdlet.
Outputs
None
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.
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
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.
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
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.
Get-Process p*
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 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
Type: SwitchParameter
Position: Named
Default value: None
-IncludeScriptBlock
Because script blocks contain code and can be used maliciously, they are not
exported by default.
Type: SwitchParameter
Position: Named
-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
-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
-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.
Type: SwitchParameter
Aliases: NoOverwrite
Position: Named
-Path
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
Inputs
ExtendedTypeDefinition
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
PowerShell
PowerShell
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.
PowerShell
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
PowerShell
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
Remove-PSSession $S
Import-Module Server01
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
-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
-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
-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
-CommandType
Exports only the specified types of command objects. Use CommandType or its alias,
Type.
The acceptable values for this parameter are as follows:
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.
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
Position: Named
-Encoding
Specifies the type of encoding for the target file. The default value is UTF8 .
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.
Type: String
Position: Named
-Force
Overwrites one or more existing output files, even if the file has the read-only
attribute.
Type: SwitchParameter
Position: Named
-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
-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.
Type: ModuleSpecification[]
Position: Named
-Module
Exports only the commands in the specified PowerShell snap-ins and modules. Enter
the snap-in and
module names. Wildcards are not permitted.
Type: String[]
Aliases: PSSnapin
Position: Named
-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
Position: 1
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
Inputs
None
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
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.
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
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
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.
PowerShell
class DateTime
DayOfWeek = Friday
$_ / $null = #ERR
class DateTime
DayOfWeek = Friday
$_ / $null =
+ FullyQualifiedErrorId : PSPropertyExpressionError
Parameters
-Depth
Specifies the number of columns in the display.
Type: Int32
Position: Named
-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
-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.
Type: String
Position: Named
-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
-GroupBy
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:
Type: Object
Position: Named
-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
-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:
Type: Object[]
Position: 0
-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
-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
Inputs
PSObject
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
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
PowerShell
00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
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.
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
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.
PowerShell
Path:
00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
00000000 01 02 03 E8 03 ...è.
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 .
Non-ASCII characters in the input are output as literal ? characters resulting in a loss
of
information.
Type: String
Position: Named
-InputObject
Specifies the objects to be formatted. Enter a variable that contains the objects or
type a command
or expression that gets the objects.
[string]
[byte]
[int] , [int32]
[long] , [int64]
Type: Object
Position: Named
-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
-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
-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
Inputs
String
You can pipe a string to this cmdlet.
Outputs
ByteCollection
Notes
Windows PowerShell includes the following aliases for Format-Hex :
fhx
Generally, each byte is interpreted as a Unicode code point, which means that:
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
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.
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.
PowerShell
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
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.
PowerShell
DayOfWeek : Friday
$_ / $null : #ERR
DayOfWeek : Friday
$_ / $null :
+ 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
-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:
Both . Displays the properties of the collection object and the properties of
objects in the
collection.
Type: String
Position: Named
-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
-GroupBy
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:
Type: Object
Position: Named
-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
-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:
Type: Object[]
Position: 0
-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
-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
Inputs
PSObject
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 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 .
Related Links
about_Calculated_Properties
Format-Custom
Format-Hex
Format-Table
Format-Wide
Format-Table
Reference
Module: Microsoft.PowerShell.Utility
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
PowerShell
PowerShell
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.
PowerShell
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.
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
Directory: C:\Test
includes
the CreationTime column.
The default Format-Table output for Get-ChildItem doesn't include the CreationTime
column.
PowerShell
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 .
PowerShell
Get-Process notepad |
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.
PowerShell
Expression={(Get-Date) - $_.CreationDate}
----------- ------------------
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
DayOfWeek $_ / $null
--------- ------------
Wednesday #ERR
DayOfWeek $_ / $null
--------- ------------
Wednesday
+ 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
-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
-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:
Type: String
Position: Named
-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
-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:
Type: Object
Position: Named
-HideTableHeaders
Type: SwitchParameter
Position: Named
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
-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:
Type: Object[]
Position: 0
-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
-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
-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
-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
Inputs
PSObject
Outputs
Microsoft.PowerShell.Commands.Internal.Format
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 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 .
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
PowerShell
PowerShell
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
PowerShell
#ERR
+ 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
-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
-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
-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 .
Both : Displays the properties of the collection object and the properties of
objects in the
collection.
Type: String
Position: Named
-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
-GroupBy
Type: Object
Position: Named
-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
-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:
FormatString - <string>
For more information, see
about_Calculated_Properties.
Type: Object
Position: 0
-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
-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
Inputs
PSObject
You can pipe any object to this cmdlet.
Outputs
Microsoft.PowerShell.Commands.Internal.Format
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
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.
Examples
Get-Alias
CommandType Name
----------- ----
...
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.
This command gets all aliases that begin with gp or sp, except for aliases that end with
ps.
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
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 .
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
-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
-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
-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
Inputs
String
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
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
Get-Culture
This command displays information about the regional settings on the computer.
PS C:\> $C = Get-Culture
Parent : en
LCID : 1033
KeyboardLayoutId : 1033
Name : en-US
IetfLanguageTag : en-US
TwoLetterISOLanguageName : en
ThreeLetterISOLanguageName : eng
ThreeLetterWindowsLanguageName : ENU
IsNeutralCulture : False
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
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
LongTimePattern : h:mm:ss tt
MonthDayPattern : MMMM dd
PMDesignator : PM
ShortDatePattern : M/d/yyyy
ShortTimePattern : h:mm tt
SortableDateTimePattern : yyyy'-'MM'-'dd'T'HH':'mm':'ss
TimeSeparator : :
IsReadOnly : False
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
Outputs
CultureInfo
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
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
PowerShell
Get-Date
PowerShell
Get-Date uses the DisplayHint parameter with the Date argument to get only the date.
PowerShell
The .NET format specifiers used in this example are defined as follows:
Specifier Definition
MM Month number
PowerShell
The UFormat format specifiers used in this example are defined as follows:
Specifier Definition
%m Month number
For a list of valid UFormat format specifiers, see the Notes section.
The Gregorian calendar has 365 days, except for leap years that have 366 days. For
example, December
31, 2020 is day 366.
PowerShell
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.
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.
PowerShell
$Time = Get-Date
$Time.ToUniversalTime()
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.
PowerShell
Directory: C:\Test
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.
Get-Date -Date "6/25/2019 12:30:22" returns Tuesday, June 25, 2019 12:30:22
Type: DateTime
Aliases: LastWriteTime
Position: 0
-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
-DisplayHint
Type: DisplayHintType
Position: Named
-Format
Displays the date and time in the Microsoft .NET Framework format indicated by the
format specifier.
The Format parameter outputs a String object.
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.
Type: String
Position: Named
-Hour
Type: Int32
Position: Named
-Millisecond
Type: Int32
Position: Named
-Minute
Type: Int32
Position: Named
-Month
Type: Int32
Position: Named
-Second
Type: Int32
Position: Named
-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
-Year
Type: Int32
Position: Named
Inputs
DateTime
Outputs
DateTime
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.
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.
) Important
%G Same as 'Y'
%g Same as 'y'
%h Same as 'b'
Format Meaning Example
specifier
%k Same as 'H'
%M Minutes 35
%m Month number 06
%n newline character
%p AM or PM
%S Seconds 05
%U Same as 'W'
%w Same as 'u'
%X Same as 'T'
7 Note
Related Links
ForEach-Object
Get-Culture
Get-Member
New-Item
New-TimeSpan
Set-Date
Get-Event
Reference
Module: Microsoft.PowerShell.Utility
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
This command gets events in which the value of the SourceIdentifier property is
PowerShell.ProcessCreated.
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
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.
Parameters
-EventIdentifier
Specifies the event identifiers for which this cmdlet gets events.
Type: Int32
Aliases: Id
Position: 0
-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
Inputs
None
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.
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.
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
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
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
TypeName: System.Timers.Timer
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.
PowerShell
$Timer.Interval = 500
$params = @{
InputObject = $Timer
EventName = 'Elapsed'
SourceIdentifier = 'Timer.Random'
Register-ObjectEvent @params
$Timer.Enabled = $True
($Subscriber.action).gettype().fullname
System.Management.Automation.PSEventJob
State : Running
Module : __DynamicModule_6b5cbe82-d634-41d1-ae5e-ad7fe8d57fe0
StatusMessage :
HasMoreData : True
Location :
JobStateInfo : Running
Finished : System.Threading.ManualResetEvent
InstanceId : 88944290-133d-4b44-8752-f901bd8012e2
Id : 1
Name : Timer.Random
ChildJobs : {}
...
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 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.
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
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
-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
Inputs
None
Outputs
PSEventSubscriber
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
PowerShell
Algorithm : SHA256
Hash : 908B64B1971A979C7E3E8CE4621945CBA84854CB98D76367B791A6E22B5F6D53
Path : C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
PowerShell
Algorithm : SHA384
Hash :
20AB1C2EE19FC96A7C66E33917D191A24E3CE9DAC99DB7C786ACCE31E559144FEAFC695C58E5
08E2EBBC9D3C96F21FA3
Path : C:\Users\user1\Downloads\Contoso8_1_ENT.iso
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'
True
PowerShell
$stringAsStream = [System.IO.MemoryStream]::new()
$writer = [System.IO.StreamWriter]::new($stringAsStream)
$writer.write("Hello world")
$writer.Flush()
$stringAsStream.Position = 0
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
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
Position: Named
-InputStream
Type: Stream
Position: Named
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
-Path
Specifies the path to one or more files as an array. Wildcard characters are permitted.
Type: String[]
Position: 0
Inputs
String
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
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.
Examples
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
PowerShell
$F
TypeName FormatViewDefinition
-------- --------------------
$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
CommandType Undefined 15
Name Undefined 50
Version Undefined 10
Source Undefined 0
$A = Get-FormatData
Import-Module bitstransfer
$B = Get-FormatData
Compare-Object $A $B
InputObject SideIndicator
----------- -------------
Microsoft.BackgroundIntelligentTransfer.Management.BitsJob =>
Get-Content c:\test\bits.format.ps1xml
<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.
PowerShell
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
-TypeName
Specifies the type names that this cmdlet gets for the formatting data.
Enter the type
names.
Wildcards are permitted.
Type: String[]
Position: 0
Inputs
None
Outputs
ExtendedTypeDefinition
Related Links
Export-FormatData
Update-FormatData
Get-Host
Reference
Module: Microsoft.PowerShell.Utility
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
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.
$H = Get-Host
$Win = $H.UI.RawUI.WindowSize
$Win.Height = 10
$Win.Width = 10
$H.UI.RawUI.Set_WindowSize($Win)
(Get-Host).Version
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.
(Get-Host).CurrentCulture | Format-List
Parent : en
LCID : 1033
KeyboardLayoutId : 1033
Name : en-US
IetfLanguageTag : en-US
TwoLetterISOLanguageName : en
ThreeLetterISOLanguageName : eng
ThreeLetterWindowsLanguageName : ENU
IsNeutralCulture : False
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.
(Get-Host).CurrentCulture.DateTimeFormat | Format-List
AMDesignator : AM
Calendar : System.Globalization.GregorianCalendar
DateSeparator : /
FirstDayOfWeek : Sunday
CalendarWeekRule : FirstDay
LongTimePattern : h:mm:ss tt
MonthDayPattern : MMMM dd
PMDesignator : PM
ShortDatePattern : M/d/yyyy
ShortTimePattern : h:mm tt
SortableDateTimePattern : yyyy'-'MM'-'dd'T'HH':'mm':'ss
TimeSeparator : :
IsReadOnly : False
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.
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
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.
$Host.PrivateData.ErrorBackgroundColor = "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.
Inputs
None
You can't pipe objects to this cmdlet.
Outputs
System.Management.Automation.Internal.Host.InternalHost
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.
Related Links
Clear-Host
Read-Host
Write-Host
Get-Member
Reference
Module: Microsoft.PowerShell.Utility
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
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
DependentServices Property
System.ServiceProcess.ServiceController[] DependentServices {get;}
ServiceHandle Property
System.Runtime.InteropServices.SafeHandle ServiceHandle {get;}
ServicesDependedOn Property
System.ServiceProcess.ServiceController[] ServicesDependedOn {get;}
StartType Property
System.ServiceProcess.ServiceStartMode StartType {get;}
Status Property
System.ServiceProcess.ServiceControllerStatus Status {get;}
PowerShell
(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
PowerShell
TypeName: System.ServiceProcess.ServiceController
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
TypeName: System.Diagnostics.Eventing.Reader.EventLogRecord
The MemberType parameter gets only objects with a value of NoteProperty for their
MemberType property.
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
TypeName: System.Diagnostics.Process
TypeName: System.ServiceProcess.ServiceController
PowerShell
$array = @(1,'hello')
$array | Get-Member
TypeName: System.Int32
...
TypeName: System.String
TypeName: System.Object[]
...
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.
PowerShell
Name
----
PSPath
PSParentPath
PSChildName
PSDrive
PSProvider
PSIsContainer
IsReadOnly
CreationTime
CreationTimeUtc
LastAccessTime
LastAccessTimeUtc
LastWriteTime
LastWriteTimeUtc
Attributes
PowerShell
$d = [ordered]@{Name="Server30";System="Server Core";PSVersion="4.0"}
Name Value
---- -----
Name Server30
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:
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
By default, Get-Member gets these properties in all views except Base and Adapted,
but
doesn't display them.
Type: SwitchParameter
Position: Named
-InputObject
Using the InputObject parameter isn't the same as piping an object to Get-Member .
The
differences are as follows:
Type: PSObject
Position: Named
-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.
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
-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
-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
Specifies that this cmdlet gets only particular types properties and methods. Specify
one or more of
the values. The default is Adapted, Extended.
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
Type: PSMemberViewTypes
Position: Named
Inputs
PSObject
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
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.
Examples
PowerShell
Get-PSBreakpoint
PowerShell
Get-PSBreakpoint -Id 2
Function :
IncrementAction :
Enabled :
TrueHitCount : 0
Id : 2
Script : C:\ps-test\sample.ps1
ScriptName : C:\ps-test\sample.ps1
PowerShell
$B = `Set-PSBreakpoint` -Script "sample.ps1" -Command "Increment"
$B.Id | Get-PSBreakpoint
the breakpoint
object in the $B variable is piped to the Get-PSBreakpoint cmdlet to
display the breakpoint
information.
PowerShell
This command does not get other breakpoints that might be set in other scripts or on
functions in
the session.
PowerShell
PowerShell
PowerShell
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
-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
-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
-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
Type: BreakpointType[]
Position: 0
-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
Inputs
Int32
BreakpointType
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
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.
Examples
$p = $args[0]
Command : my-alias
Action :
Enabled : True
HitCount : 0
Id : 0
my-alias get-content
[DBG]: PS C:\ps-test> s
$p = $args[0]
[DBG]: PS C:\ps-test> s
[DBG]: PS C:\ps-test>get-pscallstack
prompt {} {}
prompt
my-alias {} {get-content}
prompt
prompt {} {}
prompt
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
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
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.
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.
Examples
PowerShell
Get-Random
3951433
47
56
18.08467273887
PowerShell
1, 2, 3, 5, 8, 13 | Get-Random
PowerShell
1, 2, 3, 5, 8, 13 | Get-Random -Count 3
13
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
13
PowerShell
yellow
Because SetSeed produces non-random behavior, it's typically used only to reproduce
results,
such as when debugging or analyzing a script.
PowerShell
74
56
84
46
74
74
74
56
84
46
PowerShell
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
Name Count
---- -----
1 206
2 199
3 196
4 226
5 185
6 188
Parameters
-Count
Type: Int32
Position: Named
-InputObject
Type: Object[]
Position: 0
-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.
Position: 0
-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
-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
Position: Named
Inputs
Object
You can pipe any object to this cmdlet. It selects values randomly from the piped
objects.
Outputs
Int32
Int64
Double
PSObject
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.
SByte Double
Byte Double
Int16 Double
Input Type Output Type
UInt16 Double
Int32 Int32
UInt32 Double
Int64 Int64
UInt64 Double
Double Double
Single Double
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
Get-Runspace
Get-Runspace -Id 2
PowerShell
Parameters
-Id
Specifies the Id of a runspace
Type: Int32[]
Position: 0
-InstanceId
Type: Guid[]
Position: 0
-Name
Type: String[]
Position: 0
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
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
Get-RunspaceDebug
Parameters
-AppDomainName
The name of the application domain that hosts the PowerShell runspace.
Type: String[]
Position: 1
-ProcessName
Type: String
Position: 0
Type: Runspace[]
Position: 0
-RunspaceId
Type: Int32[]
Position: 0
-RunspaceInstanceId
Type: Guid[]
Position: 0
-RunspaceName
Type: String[]
Position: 0
Default value: None
Related Links
Disable-RunspaceDebug
Enable-RunspaceDebug
Get-TraceSource
Reference
Module: Microsoft.PowerShell.Utility
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
This command gets all of the trace sources that have names that include provider.
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
Inputs
String
You can pipe a string that contains the name of a trace source to this cmdlet.
Outputs
PSTraceSource
Related Links
Set-TraceSource
Trace-Command
Get-TypeData
Reference
Module: Microsoft.PowerShell.Utility
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.
Examples
PowerShell
Get-TypeData
PowerShell
TypeName Members
-------- -------
System.IO.DirectoryInfo {[Mode,
System.Management.Automation.Runspaces.CodePropert…
System.IO.FileInfo {[Mode,
System.Management.Automation.Runspaces.CodePropert…
PowerShell
(Get-TypeData *EventLogEntry*).Members.EventID
PowerShell
(Get-TypeData -TypeName System.DateTime).Members["DateTime"].GetScriptBlock
"{0}" -f $this.ToLongDateString()
"{0}" -f $this.ToLongTimeString()
else {
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
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
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
Get-UICulture
Get-UICulture | Format-List *
This command displays the values of all of the properties of the current UI culture in a
list.
(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 .
(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
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
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
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 .
PowerShell
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.
PowerShell
PowerShell
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
Type: SwitchParameter
Position: Named
-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
-OnType
Indicates that this cmdlet returns only one object of each type.
Type: SwitchParameter
Position: Named
Inputs
PSObject
Outputs
PSObject
This cmdlet returns its input objects without duplicates.
Notes
Windows PowerShell includes the following aliases for Get-Unique :
gu
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
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
PowerShell
Get-Variable m*
Get-Variable m* -ValueOnly
PowerShell
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
Parameters
-Exclude
Specifies an array of items that this cmdlet excludes from the operation.
Wildcards
are permitted.
Type: String[]
Position: Named
Specifies an array of items upon which the cmdlet will act, excluding all others.
Wildcards are permitted.
Type: String[]
Position: Named
-Name
Type: String[]
Position: 0
-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)
Type: String
Position: Named
-ValueOnly
Indicates that this cmdlet gets only the value of the variable.
Type: SwitchParameter
Position: Named
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
This example uses the NoElement parameter to omit the members of the group.
PowerShell
$files |
Count Name
----- ----
365 .xml
231 .cdxml
197
169 .ps1xml
142 .txt
114 .psd1
63 .psm1
49 .xsd
36 .dll
15 .mfl
15 .mof
...
PowerShell
10 0 {2, 4, 6, 8...}
10 1 {1, 3, 5, 7...}
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
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.
PowerShell
1 {System.Diagnostics.Process (Idle)}
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
Count Name
----- ----
2 csrss
5 svchost
2 winlogon
2 wmiprvse
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
Name Value
---- -----
$A.Get
...
PowerShell
@(
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
-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
-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
Type: String
Position: Named
-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.
Type: PSObject
Position: Named
-NoElement
Indicates that this cmdlet omits the members of a group from the results.
Type: SwitchParameter
Position: Named
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:
Type: Object[]
Position: 0
Inputs
PSObject
Outputs
GroupInfo
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:
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.
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
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.
Examples
Import-Alias test.txt
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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:
If the corresponding alias is read-only, it will be displayed in the value of the Options
property.
Type: SwitchParameter
Position: Named
-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
-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
-Path
Type: String
Position: 0
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)
Type: String
Position: Named
-WhatIf
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
String
Outputs
None
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
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.
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
) Important
PowerShell
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.
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
-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
-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
-Path
Type: String[]
Position: 0
-Skip
Ignores the specified number of objects and then gets the remaining objects. Enter
the number of
objects to skip.
Type: UInt64
Position: Named
Inputs
String
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
PowerShell
$P | Get-Member
TypeName: System.Management.Automation.PSCustomObject
...
$P | Format-Table
...
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.
PowerShell
$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
PowerShell
(Get-Culture).TextInfo.ListSeparator
PowerShell
$A = $A[1..($A.Count - 1)]
$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]
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.
PowerShell
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 | Get-Member
TypeName: System.Management.Automation.PSCustomObject
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.
PowerShell
ProjectID,ProjectName,,Completed
13,Inventory,Redmond,True
440,,FarEast,True
469,Marketing,Europe,False
WARNING: One or more headers were not specified. Default names starting with
"H" have been used in
WARNING: One or more headers were not specified. Default names starting with
"H" have been used in
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
( , ).
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 (,)
-Encoding
Specifies the type of encoding for the target file. The default value is Default .
(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.
Type: String
Position: Named
-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
-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
-Path
Type: String[]
Position: 0
-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
Inputs
String
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 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.
Examples
PowerShell
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.
PowerShell
Name Value
---- -----
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 .
PowerShell
PS C:\> # In C:\Test\en-US\Test.psd1:
ConvertFrom-StringData @'
# English strings
'@
# In C:\Test\Test.ps1
Write-Host $Messages.Msg2
# In Windows PowerShell
PS C:\> .\Test.ps1
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.
PowerShell
PS C:\> # In TestScript.ps1
$UserMessages = DATA
{ ConvertFrom-StringData @'
# English strings
'@
$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 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
PowerShell
PS C:\> # In Day1.ps1
# In Day2.ps1
PS C:\> .\Day1.ps1
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
-BindingVariable
Specifies the variable into which the text strings are imported. Enter a variable name
without a
dollar sign ( $ ).
Type: String
Aliases: Variable
Position: 0
-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.
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
-SupportedCommand
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
-UICulture
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
Type: String
Position: 1
Inputs
None
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 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
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.
Related Links
Write-Host
Import-PowerShellDataFile
about_Data_Files
Import-PowerShellDataFile
Reference
Module: Microsoft.PowerShell.Utility
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
Examples
PowerShell
Get-Content .\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
-Path
The path to the file being imported. Wildcards are allowed but only the first
matching file is
imported.
Type: String[]
Position: 0
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
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.
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
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
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
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
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.
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.
Receive-Job $batch
Because imported commands might take longer to run than local commands, Import-
PSSession adds an
AsJob parameter to every imported command. The AsJob parameter
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-
The fourth command uses the Receive-Job cmdlet to get the results of the job in the
$batch
variable.
The first command creates a PSSession on the Server01 computer and saves it in the $S
variable.
The third command uses the Module parameter of Import-PSSession to import the
cmdlets and
functions in the module into the current session.
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
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 : {}
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.
PS C:\> Get-Date
09074
Microsoft.PowerShell.Utility
PS C:\> Microsoft.PowerShell.Utility\Get-Date
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.
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.
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.
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
-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
-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.
Type: X509Certificate2
Position: Named
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
-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:
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
Position: Named
-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:
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
-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.
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
-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.
It's also Required to specify at least one of the three below keys.
ModuleVersion - Specifies a minimum acceptable version of the module.
Type: ModuleSpecification[]
Position: Named
-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.
Type: String[]
Aliases: PSSnapin
Position: Named
-Prefix
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
-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
Inputs
None
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
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.
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.
command. You
might see the progress bar while the command is running.
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.
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
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
Examples
$Command = "Get-Process"
$Command
Get-Process
Invoke-Expression $Command
...
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.
"C:\ps-test\testscript.ps1" | Invoke-Expression
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.
$Cmdlet_name = "Get-ComputerInfo"
$Example_number = 1
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
Type: String
Position: 0
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
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.
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
Title pubDate
----- -------
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
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {
$True }
# The search variable contents are later embedded in the body variable.
$Server = 'server.contoso.com'
$Url = "https://${server}:8089/services/search/jobs/export"
# 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
$Body = @{
search = $Search
output_mode = "csv"
earliest_time = "-2d@d"
latest_time = "-1d@d"
{"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"}}
PowerShell
$headers = @{
'userId' = 'UserIDValue'
'token' = 'TokenValue'
For example:
PowerShell
$R = Invoke-WebRequest https://website.com/login.aspx
$R.Forms[0].Name = "MyName"
$R.Forms[0].Password = "MyPassword"
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
$x
$x = 0
$x
30
$x = 0
$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
-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.
Type: X509Certificate
Position: Named
-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.
Type: String
Position: Named
-ContentType
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
-Credential
Specifies a user account that has permission to send the request. The default is the
current user.
7 Note
Type: PSCredential
Position: Named
-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
-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
-InFile
Enter a path and file name. If you omit the path, the default is the current location.
Type: String
Position: Named
-MaximumRedirection
Type: Int32
Position: Named
Default value: 5
-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
-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.
Type: String
Position: Named
-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
-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
-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.
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
-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
Creates a variable containing the web request session. Enter a variable name without
the dollar sign
( $ ) symbol.
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
-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
-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
Position: Named
-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.
Type: Uri
Position: 0
-UseBasicParsing
Indicates that the cmdlet uses basic parsing. The cmdlet returns the raw HTML in a
String
object.
Type: SwitchParameter
Position: Named
-UseDefaultCredentials
Uses the credentials of the current user to send the web request.
Type: SwitchParameter
Position: Named
-UserAgent
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
-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,
You cannot use the SessionVariable and WebSession parameters in the same
command.
Type: WebRequestSession
Position: Named
Inputs
Object
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
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.
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
PowerShell
$Response.AllElements | Where-Object {
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.
PowerShell
# This command stores the first form in the Forms property of the $R
variable in the $Form variable.
$Form = $R.Forms[0]
$Form.fields
Key Value
--- -----
...
pass
...
# These commands populate the username and password of the respective Form
fields.
$Form.Fields["email"]="[email protected]"
$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.
# Now the Invoke-WebRequest cmdlet is used to sign into the Facebook web
service.
# 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.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.
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.
PowerShell
try
$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.
$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 = @()
$params = $using:file
Invoke-WebRequest @params
}
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.
$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 -
Type: Object
Position: Named
-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.
Type: X509Certificate
Position: Named
-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.
Type: String
Position: Named
-ContentType
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
-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.
7 Note
Type: PSCredential
Position: Named
-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
-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
-InFile
Enter a path and file name. If you omit the path, the default is the current location.
Type: String
Position: Named
-MaximumRedirection
Type: Int32
Position: Named
-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
-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
-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
-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
-ProxyCredential
Specifies a user account that has permission to use the proxy server specified by the
Proxy
parameter. The default is the current user.
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
-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
-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.
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
-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
-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
Position: Named
-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.
Type: Uri
Position: 0
-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
-UseDefaultCredentials
Indicates that the cmdlet uses the credentials of the current user to send the web
request.
Type: SwitchParameter
Position: Named
-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
-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,
Type: WebRequestSession
Position: Named
Inputs
Object
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
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
PowerShell
The second command measures the time it takes to process a recursive Get-ChildItem
command that
uses the provider-specific Filter parameter.
PowerShell
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
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
PowerShell
# Perform a simple operation to demonstrate the InputObject parameter
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
PowerShell
# 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
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
$foo
Value 2
Value 2
Parameters
-Expression
Specifies the expression that is being timed. Enclose the expression in braces ( {} ).
Type: ScriptBlock
Position: 0
-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
Inputs
PSObject
Outputs
TimeSpan
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
PowerShell
Get-ChildItem | Measure-Object
PowerShell
The first command uses Set-Content to add some default text to a file.
PowerShell
4 4 15
PowerShell
$services = Get-Service
$processes = Get-Process
Count : 682
Average :
Sum :
Maximum :
Minimum :
Property :
Count : 290
Average :
Sum :
Maximum :
Minimum :
Property : DisplayName
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
PowerShell
Count : 126
Average : 0.0634920634920635
Sum : 8
Maximum : 1
Minimum : 0
StandardDeviation :
Property : PSIsContainer
PowerShell
"One`nTwo`nThree"
One
Two
Three
# The second string is separated into two lines by the newline character.
3 5
Parameters
-Average
Indicates that the cmdlet displays the average value of the specified properties.
Type: SwitchParameter
Position: Named
-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
-IgnoreWhiteSpace
Type: SwitchParameter
Position: Named
-InputObject
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.
Type: PSObject
Position: Named
-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
-Maximum
Indicates that the cmdlet displays the maximum value of the specified properties.
Type: SwitchParameter
Position: Named
-Minimum
Indicates that the cmdlet displays the minimum value of the specified properties.
Type: SwitchParameter
Position: Named
-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
-Sum
Indicates that the cmdlet displays the sum of the values of the specified properties.
Type: SwitchParameter
Position: Named
-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
Inputs
PSObject
Outputs
GenericMeasureInfo
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
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
This command creates an alias named List to represent the Get-ChildItem cmdlet.
Example 2: Create a read-only alias for a cmdlet
PowerShell
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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
Indicates that the cmdlet acts like Set-Alias if the alias named already exists.
Type: SwitchParameter
Position: Named
-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
-Option
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.
Type: ScopedItemOptions
Position: Named
-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
-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).
Type: String
Position: Named
-Value
Specifies the name of the cmdlet or command element that is being aliased.
Type: String
Position: 1
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
None
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
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
This command creates a new event in the PowerShell event queue. It uses a
Windows.Timer object
to send the event.
$Identifier = "WMI.ProcessCreated"
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
Type: PSObject[]
Position: 2
-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
-Sender
Specifies the object that raises the event. The default is the PowerShell engine.
Type: PSObject
Position: 1
-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
Inputs
None
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
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
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
1 2 3 4
PowerShell
# The following command gets the same results as the example above.
$IE2.Navigate2("www.microsoft.com")`
$IE2.Visible = $True`
PowerShell
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
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-
PowerShell
$objshell | Get-Member
$objshell.ToggleDesktop()
TypeName: System.__ComObject#{866738b9-6cf2-4de8-8767-f794ebe74f4e}
PowerShell
$parameters = @{
TypeName = 'System.Collections.Generic.HashSet[string]'
ArgumentList = ([string[]]$array,
[System.StringComparer]::OrdinalIgnoreCase)
7 Note
This example uses parameter splatting for readability. For more information, see
about_Splatting.
$set
New-Object : Cannot find an overload for "HashSet`1" and the argument count:
"3".
At line:1 char:8
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ 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
$cert = New-Object
System.Security.Cryptography.X509Certificates.X509Certificate -ArgumentList
(,$bytes)
Aliases: Args
Position: 1
-ComObject
Type: String
Position: 0
-Property
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
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
-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
Inputs
None
Outputs
Object
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
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.
On Windows platforms:
Examples
$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
Type: SwitchParameter
Aliases: cf
Position: Named
-WhatIf
Type: SwitchParameter
Aliases: wi
Position: Named
Outputs
FileInfo
This cmdlet returns a FileInfo object that represents the temporary file.
New-TimeSpan
Reference
Module: Microsoft.PowerShell.Utility
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.
Examples
PowerShell
$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
This command does not require the Start parameter, because the default value of the
Start
parameter is the current date and time.
PowerShell
(Get-Date) + $90days
These commands return the date that is 90 days after the current date.
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
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
Type: Int32
Position: Named
-End
Type: DateTime
Position: 1
-Hours
Type: Int32
Position: Named
-Minutes
Type: Int32
Position: Named
-Seconds
Type: Int32
Position: Named
Type: DateTime
Aliases: LastWriteTime
Position: 0
Inputs
DateTime
You can pipe a DateTime object representing the start time to this cmdlet.
Outputs
TimeSpan
Related Links
Get-Date
Set-Date
New-Variable
Reference
Module: Microsoft.PowerShell.Utility
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
New-Variable days
This command creates a new variable named days. You are not required to type the
Name parameter.
This command creates a variable named zipcode and assigns it the value 98033.
At line:1 char:1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ FullyQualifiedErrorId :
VariableAlreadyExists,Microsoft.PowerShell.Commands.NewVariableCommand
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.
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.
PowerShell
PS C:\> Get-Variable c*
Name Value
---- -----
Culture en-US
ConsoleFileName
ConfirmPreference High
CommandLineParameters {}
PS C:\> $counter
At line:1 char:1
+ $counter
+ ~~~~~~~~
+ 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
Name Value
---- -----
abc123xyz
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-Description
Type: String
Position: Named
-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
-Name
Type: String
Position: 0
-Option
Specifies the value of the Options property of the variable. The acceptable values for
this
parameter are:
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.
Type: ScopedItemOptions
Position: Named
-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
-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
-Value
Type: Object
Position: 1
-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:
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
Position: Named
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
Object
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
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
PowerShell
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.
PowerShell
At line:1 char:15
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
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.
PowerShell
$Procs = Get-Process
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.
PowerShell
PS> Get-Location
Path
----
Alias:\
CommandType Name
----------- ----
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-
PowerShell
function DemoDefaultOutFileWidth() {
try {
$PSDefaultParameterValues['out-file:width'] = 2000
$logFile = "$pwd\logfile.txt"
finally {
$PSDefaultParameterValues.Remove('out-file:width')
DemoDefaultOutFileWidth
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
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-Encoding
Specifies the type of encoding for the target file. The default value is unicode .
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 .
Type: String
Position: 1
-FilePath
Type: String
Position: 0
-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
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
-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
-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
-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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
-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
Inputs
PSObject
Outputs
None
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
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
Examples
PowerShell
Get-Process | Out-GridView
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 .
PowerShell
PowerShell
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 .
PowerShell
The examle uses ogv , which is the alias for the Out-GridView cmdlet. The Title
parameter
specifies the window title.
PowerShell
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.
PowerShell
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
Type: PSObject
Position: Named
-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.
Single . Zero items or one item. Use this value when the next command can
Type: OutputModeOption
Position: Named
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
-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
-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
Inputs
PSObject
Outputs
None
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.
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.
Enter or In column header row, sort column data (toggle A-Z, Z-A).
Spacebar
To reorder columns:
You can drag and drop columns into the desired location. Or use the following steps:
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.
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.
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:
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.
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.
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.
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.
Related Links
Out-File
Out-Printer
Out-String
Out-Printer
Reference
Module: Microsoft.PowerShell.Utility
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
Examples
PowerShell
to
Out-Printer , which sends it to the default printer.
PowerShell
The Name parameter selects a specific printer, rather than the default.
PowerShell
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
-Name
Sends the output to the specified printer. The parameter name Name is optional.
Type: String
Aliases: PrinterName
Position: 0
Inputs
PSObject
Outputs
None
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
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
PowerShell
Parent : en
LCID : 1033
KeyboardLayoutId : 1033
Name : en-US
IetfLanguageTag : en-US
TwoLetterISOLanguageName : en
ThreeLetterISOLanguageName : eng
ThreeLetterWindowsLanguageName : ENU
IsNeutralCulture : False
NumberFormat : System.Globalization.NumberFormatInfo
DateTimeFormat : System.Globalization.DateTimeFormatInfo
Calendar : System.Globalization.GregorianCalendar
OptionalCalendars : {System.Globalization.GregorianCalendar,
System.Globalization.GregorianCalendar}
UseUserOverride : True
IsReadOnly : False
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.
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.
PowerShell
Name Value
---- -----
TestKey xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
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
-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
-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
Inputs
PSObject
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
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
PowerShell
PowerShell
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
-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
Inputs
None
You can't pipe objects to this cmdlet.
Outputs
String
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
Invoke-Command -Session $S {
Register-EngineEvent -SourceIdentifier
([System.Management.Automation.PsEngineEvent]::Exiting) -Forward
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.
PowerShell
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.
While ($True) {
Start-Sleep -seconds 2
Start-Sleep -seconds 4
Get-EventSubscriber
Get-Job
SubscriptionId : 12
SourceObject :
EventName :
SourceIdentifier : MyEventSource
Action : System.Management.Automation.PSEventJob
HandlerDelegate :
SupportEvent : False
ForwardEvent : False
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.
PowerShell
PS> Get-Job
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
-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
-MaxTriggerCount
Specifies the maximum number of times that the action is executed for the event
subscription.
Type: Int32
Position: Named
-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
-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
-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
Inputs
None
Outputs
None
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.
PowerShell
PowerShell
$newEventArgs = @{
SourceIdentifier = 'PowerShell.ProcessCreated'
Sender = $Sender
EventArguments = $EventArgs.NewEvent.TargetInstance
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.
PowerShell
# ProcessCreationEvent.ps1
function Enable-ProcessCreationEvent {
$objectEventArgs = @{
EventName = 'EventArrived'
SourceIdentifier = 'WMI.ProcessCreated'
MessageData = 'Test'
Forward = $True
Register-ObjectEvent @objectEventArgs
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.
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.Interval = 500
$Timer.Enabled = $True
$objectEventArgs = @{
InputObject = $Timer
EventName = 'Elapsed'
SourceIdentifier = 'Timer.Random'
State : Running
Module : __DynamicModule_53113769-31f2-42dc-830b-8749325e28d6
StatusMessage :
HasMoreData : True
Location :
JobStateInfo : Running
Finished : System.Threading.ManualResetEvent
InstanceId : 47b5ec9f-bfe3-4605-860a-4674e5d44ca8
Id : 7
Name : Timer.Random
ChildJobs : {}
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.
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
-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
-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
-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
Type: Int32
Position: Named
-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
-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
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
Inputs
None
Outputs
None
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
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
This command deletes the event with an event ID of 30 from the event queue.
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-EventIdentifier
Specifies the event identifier for which the cmdlet deletes. An EventIdentifier or
SourceIdentifier parameter is required in every command.
Type: Int32
Position: 0
-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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
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
New-Event
Register-EngineEvent
Register-ObjectEvent
Remove-Event
Unregister-Event
Wait-Event
Remove-PSBreakpoint
Reference
Module: Microsoft.PowerShell.Utility
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.
Examples
PowerShell
Get-PSBreakpoint | Remove-PSBreakpoint
PowerShell
$B | Remove-PSBreakpoint
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.
PowerShell
Remove-PSBreakpoint -Id 2
PowerShell
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
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-Id
Type: Int32[]
Position: 0
-WhatIf
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
Breakpoint[]
Int32[]
Runspace
Outputs
None
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
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
Examples
PowerShell
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-Date).DateTime
TypeName Members
-------- -------
System.DateTime {[DateTime,
System.Management.Automation.Runspaces.ScriptPropertyData]}
PowerShell
Get-Module | Remove-TypeData
PowerShell
in the $S variable.
PowerShell
Invoke-Command -Session $S {Get-TypeData -TypeName *CIM* | Remove-TypeData}
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-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
-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
Type: String
Position: 0
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
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
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
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
Remove-Variable Smp
Parameters
-Confirm
Prompts you for confirmation before running the cmdlet.
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-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
-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
-Name
Specifies the name of the variable to be removed. The parameter name (Name) is
optional.
Wildcards are permitted
Type: String[]
Position: 0
-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)
Type: String
Position: Named
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
PSVariable
Outputs
None
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
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.
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
PowerShell
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 |
Format-List
ProcessName : explorer
ModuleName : explorer.exe
FileName : C:\WINDOWS\explorer.exe
BaseAddress : 140697278152704
ModuleMemorySize : 3919872
EntryPointAddress : 140697278841168
InternalName: explorer
OriginalFilename: EXPLORER.EXE.MUI
ProductVersion: 10.0.17134.1
...
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
PowerShell
PowerShell
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.
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"
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
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
PowerShell
$object = [pscustomobject]@{Name="CustomObject";Expand=@(1,2,3,4,5)}
# 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.
TypeName: System.Int32
PowerShell
$customObject
MyCustomProperty
----------------
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
ProcessName $_.StartTime.DayOfWeek
---- ----------------------
alg Wednesday
ati2evxx Wednesday
ati2evxx Thursday
...
# 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',
# You can also shorten the name of your label key to 'l' and your expression
key
# to 'e'.
PowerShell
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
-ExpandProperty
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.
2 Warning
Type: String
Position: Named
-First
Specifies the number of objects to select from the beginning of an array of input
objects.
Type: Int32
Position: Named
-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
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
-Last
Specifies the number of objects to select from the end of an array of input objects.
Type: Int32
Position: Named
-Property
The value of the Property parameter can be a new calculated property. To create a
calculated,
property, use a hash table.
Type: Object[]
Position: 0
-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
-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
Specifies that if a subset of the input objects has identical properties and values, only
a single
member of the subset should be selected.
Type: SwitchParameter
Position: Named
-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.
Type: SwitchParameter
Position: Named
Inputs
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
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
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.
PowerShell
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.
PowerShell
Select-String -Path "$PSHOME\en-US\*.txt" -Pattern '\?'
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.
PowerShell
function Search-Help
$PSHelp = "$PSHOME\en-US\*.txt"
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.
PowerShell
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.
PowerShell
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.
PowerShell
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.
PowerShell
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.
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.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.
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'
Name Value
---- -----
Name foo
Category bar
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
Type: SwitchParameter
Position: Named
-CaseSensitive
Indicates that the cmdlet matches are case-sensitive. By default, matches aren't case-
sensitive.
Type: SwitchParameter
Position: Named
-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
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
-Encoding
Specifies the type of encoding for the target file. The default value is default .
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.
Type: String
Position: Named
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
-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
-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
-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.
Type: SwitchParameter
Position: Named
-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
-NotMatch
The NotMatch parameter finds text that doesn't match the specified pattern.
Type: SwitchParameter
Position: Named
-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
-Pattern
Specifies the text to find on each line. The pattern value is treated as a regular
expression.
Type: String[]
Position: 0
-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
-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
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
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.
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:
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.
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
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
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"
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.
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
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,
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"
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
...
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 = @"
<Book>
<projects>
<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>
"@
En.Book1.com
Ge.Book1.Com
Fr.Book1.com
Pl.Book1.com
En.Book1.com
Ge.Book1.Com
Fr.Book1.com
Pl.Book1.com
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"}
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
-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
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
-Path
Specifies the path and file names of the XML files to search. Wildcard characters are
permitted.
Type: String[]
Position: 1
-Xml
Type: XmlNode[]
Aliases: Node
Position: 1
Default value: None
-XPath
Type: String
Position: 0
Inputs
System.String or System.Xml.XmlNode
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
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
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
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.
PowerShell
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.
PowerShell
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.
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
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 <[email protected]> .
Type: String[]
Position: Named
-Body
Type: String
Position: 2
-BodyAsHtml
Type: SwitchParameter
Aliases: BAH
Position: Named
-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
<[email protected]> .
Type: String[]
Position: Named
-Credential
Specifies a user account that has permission to perform this action. The default is the
current
user.
7 Note
Type: PSCredential
Position: Named
-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.
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
Position: Named
-Encoding
Specifies the type of encoding for the target file. The default value is Default .
(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.
Type: Encoding
Aliases: BE
Position: Named
-From
The From parameter is required. This parameter specifies the sender's email address.
Enter a
name (optional) and email address, such as Name <[email protected]> .
Type: String
Position: Named
-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
-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
Position: Named
-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
-Subject
The Subject parameter is required. This parameter specifies the subject of the email
message.
Type: String
Aliases: sub
Position: 1
-To
The To parameter is required. This parameter specifies the recipient's email address.
Enter
names (optional) and the email address, such as Name <[email protected]> .
Type: String[]
Position: 0
-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
Inputs
String
You can pipe the path and file names of attachments to this cmdlet.
Outputs
None
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
CommandType Name
----------- ----
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.
PowerShell
CommandType Name
----------- ----
CommandType Name
----------- ----
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.
PowerShell
Definition : Get-Location
Options : ReadOnly
Description :
Name : loc
CommandType : Alias
Definition : Get-Location
Options : ReadOnly
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.
PowerShell
CommandType Name
----------- ----
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.
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
PowerShell
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 .
Using the example above we will set the alias Go as ReadOnly and Private .
PowerShell
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
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-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
-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
-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 .
AllScope - The alias is copied to any new scopes that are created.
Constant - Cannot be changed or deleted.
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
Position: Named
-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
-Scope
Specifies the scope in which this alias is valid. The default value is Local. For more
information, see about_Scopes.
Type: String
Position: Named
-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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Outputs
None
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
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
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
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
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
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
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
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
-DisplayHint
Specifies which elements of the date and time are displayed.The acceptable values
for this parameter
are:
Type: DisplayHintType
Position: Named
-WhatIf
Aliases: wi
Position: Named
Inputs
DateTime
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
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.
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.
Examples
PowerShell
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.
PowerShell
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.
PowerShell
PowerShell
Set-PSBreakpoint -Script Sample.ps1 -Command "write*"
PowerShell
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.
PowerShell
Id : 0
Command : checklog
Enabled : True
HitCount : 0
Action :
function CheckLog {
>>}
>>
PS> Checklog
PowerShell
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.
Type: ScriptBlock
Position: Named
-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
-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
-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
-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
Position: Named
-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
-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
Inputs
None
Outputs
CommandBreakpoint
LineBreakpoint
VariableBreakpoint
Notes
Windows PowerShell includes the following aliases for Set-PSBreakpoint :
sbp
When you set a breakpoint on more than one line, command, or variable, Set-
PSBreakpoint
generates a breakpoint object for each entry.
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
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.
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
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
-Force
Indicates that the cmdlet overwrites a read-only file. Use with the FilePath
parameter.
Type: SwitchParameter
Position: Named
-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
Position: Named
-Name
Specifies which components are traced. Enter the name of the trace source of each
component.
Wildcards are permitted.
Type: String[]
Position: 0
-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
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
Position: 1
-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
-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
-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
Type: String[]
Position: Named
Inputs
String
Outputs
None
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 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.
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
PowerShell
Name Value
---- -----
desc A description
PowerShell
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.
PowerShell
$Counter
26
Get-Variable c*
Name Value
---- -----
Culture en-US
ConsoleFileName
ConfirmPreference High
CommandLineParameters {}
Counter 26
Get-Variable c*
Name Value
---- -----
Culture en-US
ConsoleFileName
ConfirmPreference High
CommandLineParameters {}
$counter
.\use-counter.ps1
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
Type: SwitchParameter
Aliases: cf
Position: Named
-Description
Type: String
Position: Named
-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
-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
-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
-Name
Type: String[]
Position: 0
-Option
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 .
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
Position: Named
-PassThru
Returns an object representing the new variable. By default, this cmdlet does not
generate any
output.
Type: SwitchParameter
Position: Named
-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).
Type: String
Position: Named
-Value
Type: Object
Position: 1
-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.
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
Position: Named
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
Object
You can pipe an object representing the value of the variable to this cmdlet.
Outputs
None
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
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.
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
PowerShell
Show-Command
PowerShell
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.
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.
PowerShell
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
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.
PowerShell
$C = Show-Command -PassThru
$C
Invoke-Expression $C
PowerShell
$P
Parameters
-ErrorPopup
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
-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
-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
-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
-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
-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
Outputs
None
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
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
PowerShell
Get-ChildItem -Path C:\Test | Sort-Object
Directory: C:\Test
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
PowerShell
Directory: C:\Test
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.
PowerShell
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.
PowerShell
Id CommandLine
-- -----------
9 $PSVersionTable
3 Get-ChildItem | Get-Member
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.
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 |
...
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.
PowerShell
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.
PowerShell
# All items unsorted
localhost
server01
server25
LOCALHOST
Server19
server3
localhost
localhost
LOCALHOST
localhost
server01
Server19
server25
server3
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.
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
12345
1500
2800
3500
4100
500
6200
77
88
99999
# Integer sorted
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
Directory: C:\Test
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.
PowerShell
@(
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
Type: SwitchParameter
Position: Named
-Culture
Specifies the cultural configuration to use for sorts. Use Get-Culture to display the
system's
culture configuration.
Type: String
Position: Named
-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
-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
-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.
Type: Object[]
Position: 0
-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
Inputs
PSObject
Outputs
PSObject
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.
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
PowerShell
PowerShell
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
-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
Inputs
Int32
Outputs
None
Notes
Windows PowerShell includes the following aliases for Start-Sleep :
sleep
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
PowerShell
...
PowerShell
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 .
PowerShell
Get-ChildItem -Path D: -File -System -Recurse |
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.
Type: SwitchParameter
Position: Named
-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
-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
-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
-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
Inputs
PSObject
Outputs
PSObject
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
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
PowerShell
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:
PowerShell
$A = "i*"
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.
Type: Object[]
Aliases: Args
Position: Named
-Command
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
-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
-Expression
Specifies the expression that's being processed during the trace. Enclose the
expression in braces
( {} ).
Type: ScriptBlock
Position: 1
-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
-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
-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
-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
Type: TraceOptions
Position: Named
-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
-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
Scope
Data : Constructor , Dispose , Finalizer , Property , Verbose , WriteLine
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
Position: 2
-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
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
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.
PowerShell
PowerShell
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
FileName: C:\ps-test\Start-ActivityTracker.ps1
Stream Length
------ ------
Zone.Identifier 26
PS C:\> C:\ps-test\Start-ActivityTracker.ps1
At line:1 char:1
+ c:\ps-test\Start-ActivityTracker.ps1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ FullyQualifiedErrorId : UnauthorizedAccess
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-Path
Type: String[]
Position: 0
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
String
Outputs
None
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
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
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.
This command cancels the event subscription that has a subscription identifier of 2.
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.
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-SourceIdentifier
Type: String
Position: 0
-SubscriptionId
Type: Int32
Position: 0
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
PSEventSubscriber
Outputs
None
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
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.
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
Examples
Example 1: Reload previously loaded formatting files
PowerShell
Update-FormatData
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.
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.
Use this parameter to add a file that formats a .NET object that is not referenced in
the built-in
formatting files.
Type: String[]
Position: 0
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
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
-WhatIf
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
String
You can pipe a string that contains the append path to this cmdlet.
Outputs
None
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
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'
Show() {
Write-Host
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.
PowerShell
$deck = [Cards]::new('Deck')
$deck.NewDeck()
$deck.Shuffle()
$deck.Show()
$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♦
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 .
PowerShell
# Player 1 wants two new cards - remove 2 cards & add 2 cards
$player1.Show()
$deck.Show()
Player 1 : J♦ A♣ J♣ 9♦ 6♣
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
-InputObject
Specifies the objects to be updated. You can also pipe the object to be updated to
Update-List .
Type: PSObject
Position: Named
-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
-Remove
Type: Object[]
Position: Named
Specifies a new collection. This parameter replaces all items in the original collection
with the
items specified by this parameter.
Type: Object[]
Position: Named
Inputs
PSObject
Outputs
PSListModifier
Object
When you specify the Property parameter, this cmdlet returns the updated object.
Related Links
Select-Object
Update-TypeData
Reference
Module: Microsoft.PowerShell.Utility
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.
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.
"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.
Update-TypeData
This command updates the extended type configuration from the Types.ps1xml files
that have already
been used in the 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
PowerShell
else {"Q4"}
(Get-Date).Quarter
Q1
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.
PowerShell
Get-Date | Format-List
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.
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.
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[]
Position: 0
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-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.
Type: String
Position: Named
-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.
Type: String[]
Position: Named
-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.
Type: String[]
Position: Named
-Force
Indicates that the cmdlet uses the specified type data, even if type data has already
been specified
for that type.
Type: SwitchParameter
Position: Named
-InheritPropertySerializationSet
Indicates whether the set of properties that are serialized is inherited. The default
value is
$Null . The acceptable values for this parameter are:
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.
Position: Named
-MemberName
Use this parameter with the TypeName, MemberType, Value and SecondValue
parameters
to add or change a property or method of a type.
Type: String
Position: Named
-MemberType
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
Position: Named
-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
-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
-SecondValue
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.
Type: Object
Position: Named
-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.
Type: Int32
Position: Named
Default value: 1
-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
Type: String
Position: Named
-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
Specifies the type to which object of this type are converted when they are
deserialized.
Type: Type
Position: Named
-TypeAdapter
Type: Type
Position: Named
-TypeConverter
Type: Type
Position: Named
-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 .
Type: TypeData[]
Position: 0
-TypeName
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.
Type: String
Position: Named
-Value
Use this parameter with the MemberName, MemberType, Value and SecondValue
parameters
to add or change a property or method of a type.
Type: Object
Position: Named
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
String
You can pipe a string that contains the values of the AppendPath, TypeName, or
TypeData
parameters to this cmdlet.
Outputs
None
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
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
[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 (! $fileExists)
$this.CopyFile()
else
if ($fileExists)
[bool] Test()
return $present
else
return (! $present)
[FileResource] Get()
if ($present)
$this.CreationTime = $file.CreationTime
$this.Ensure = [Ensure]::Present
else
$this.CreationTime = $null
$this.Ensure = [Ensure]::Absent
return $this
[void] CopyFile()
Wait-Debugger
Inputs
None
Outputs
None
Related Links
Enable-DscDebug
Wait-Event
Reference
Module: Microsoft.PowerShell.Utility
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:
Examples
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
PowerShell
$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
SourceIdentifier : Timer.Elapsed
MessageData :
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
-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
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
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
PowerShell
PowerShell
PS> $DebugPreference
SilentlyContinue
PS>
PowerShell
function Test-Debug {
[CmdletBinding()]
param()
PS> Test-Debug
$DebugPreference is SilentlyContinue
Confirm
[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
Parameters
-Message
Type: String
Aliases: Msg
Position: 0
Inputs
String
You can pipe a string that contains a debug message to this cmdlet.
Outputs
None
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
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.
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.
Examples
Get-ChildItem | ForEach-Object {
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.
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.
$E = [System.Exception]@{Source="Get-
ParameterNames.ps1";HelpLink="https://go.microsoft.com/fwlink/?
LinkID=113425"}
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
Type: ErrorCategory
Position: Named
-CategoryActivity
Type: String
Aliases: Activity
Position: Named
-CategoryReason
Type: String
Aliases: Reason
Position: Named
Specifies the name of the object that was being processed when the error occurred.
Type: String
Aliases: TargetName
Position: Named
-CategoryTargetType
Specifies the type of the object that was being processed when the error occurred.
Type: String
Aliases: TargetType
Position: Named
-ErrorId
Specifies an ID string to identify the error. The string should be unique to the error.
Type: String
Position: Named
-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
-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
-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
-RecommendedAction
Specifies the action that the user should take to resolve or prevent the error.
Type: String
Position: Named
-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
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
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
"Example 5")
Examples
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.
This command displays the even numbers from two through twelve. The Separator
parameter is used
to add the string , +2= (comma, space, + , 2 , = , space).
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.
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
Position: Named
-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
Position: Named
-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
-Object
Type: Object
Position: 0
-Separator
Type: Object
Position: Named
Inputs
Object
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
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
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.
Examples
PowerShell
Get-Process -Name p*
PowerShell
$message = "To filter your results for PowerShell, pipe your results to the
Where-Object cmdlet."
Get-Process -Name p*
To filter your results for PowerShell, pipe your results to the Where-Object
cmdlet.
PowerShell
function Test-Info
Get-Process P*
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
-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
Inputs
None
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" .
Examples
PowerShell
$P = Get-Process
Write-Output $P
PowerShell
PowerShell
Count : 3
...
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
-NoEnumerate
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
Type: SwitchParameter
Position: Named
Inputs
PSObject
You can pipe objects to this cmdlet.
Outputs
PSObject
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
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
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.
$OuterLoopProgressParameters = @{
Activity = 'Updating'
Status = 'Progress->'
PercentComplete = $I * 10
CurrentOperation = 'OuterLoop'
Write-Progress @OuterLoopProgressParameters
$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.
Clear-Host
$i = 0
$out = ""
} -Process {
$out=$out + $_.Message
$i = $i+1
# The Activity and Status parameters create the first and second lines
of the progress bar
# heading, respectively.
} -End {
$out
This command displays the progress of a command to find the string "bios" in the
System event log.
foreach ( $i in 1..10 ) {
foreach ( $j in 1..10 ) {
foreach ( $k in 1..10 ) {
Step 1
Processing
Step 1 - Substep 2
Processing
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
-Completed
Indicates whether the progress bar is visible. If this parameter is omitted, Write-
Progress
displays progress information.
Type: SwitchParameter
Position: Named
-CurrentOperation
Specifies the line of text below the progress bar. This text describes the operation
that's
currently taking place.
Type: String
Position: Named
-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
-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
-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
-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
-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
-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
Inputs
None
Outputs
None
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.
Related Links
Write-Debug
Write-Error
Write-Host
Write-Output
Write-Progress
Write-Verbose
Write-Warning
Write-Verbose
Reference
Module: Microsoft.PowerShell.Utility
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
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"
These commands use the Write-Verbose cmdlet to display a status message. By default,
the message
is not displayed.
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
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
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
PowerShell
string directly to
Write-Warning .
PowerShell
$w = "This is only a test warning."
$w | Write-Warning
PowerShell
PS> $WarningPreference
Continue
At line:1 char:14
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.
PowerShell
Confirm
[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.
Parameters
-Message
Type: String
Aliases: Msg
Position: 0
Inputs
String
You can pipe a string that contains the warning to this cmdlet.
Outputs
None
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.
New-WSManSessionOption Creates session option hash table to use as input parameters for
WS-Management cmdlets.
SHORT DESCRIPTION
Provides an overview of Web Services for Management (WS-Management) as
background for using the WS-Management cmdlets in Windows PowerShell.
LONG DESCRIPTION
This topic provides an overview of Web Services for Management (WS-Management)
as
background for using the WS-Management cmdlets in Windows PowerShell. This
topic
also provides links to more information about WS-Management. The
Microsoft
implementation of WS-Management is also known as Windows Remote
Management
(WinRM).
About WS-Management
Windows Remote Management is the Microsoft implementation of the WS-
Management
protocol, a standard SOAP-based, firewall-friendly protocol that allows
hardware and operating systems from different vendors to interoperate. The
WS-
Management protocol specification provides a common way for systems to
access and
exchange management information across an information technology
(IT) infrastructure.
WS-Management and Intelligent Platform Management
Interface (IPMI), along with the
Event Collector, are components of the
Windows Hardware Management features.
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.
Connection Cmdlets
Connect-WSMan: Connects the local computer to 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.
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.
WS-Management-Specific Cmdlets
New-WSManSessionOption: Creates a WSManSessionOption object to use as input
to one or more parameters of a WS-Management cmdlet.
WS-Management Protocol
Resource URIs
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 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.
7 Note
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).
WSMan:\localhost
--- Client
--- Service
--- Shell
--- Listener
------ <Specific_Listener>
--- Plugin
--------- InitializationParameters
--------- Resources
------------ Security
------ Microsoft.Powershell
--------- InitializationParameters
--------- Resources
------------ Security
--------- 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>
PowerShell
Set-Location WSMan:
To return to a file system drive, type the drive name. For example, type.
PowerShell
Set-Location C:
PowerShell
7 Note
The above command assume that a connection to the remote system already
exists.
PowerShell
If you are in the WSMan: drive, you can omit the drive name.
PowerShell
7 Note
The above command assume that a connection to the remote system already
exists.
PowerShell
# You do not need to specify the -Path parameter name when using Set-Item.
PowerShell
PowerShell
-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
PowerShell
-ResourceUri http://schemas.dmtf.org/wbem/wscim/3/cim-schema `
-Capability "Enumerate"
PowerShell
$path = "WSMan:\localhost\Plugin\TestPlugin\Resources\Resource_5967683"
-Sddl "O:NSG:BAD:P(A;;GA;;;BA)S:P(AU;FA;GA;;;WD)(AU;SA;GWGX;;;WD)"
PowerShell
$cred = Get-Credential
-Issuer 1b3fd224d66c6413fe20d21e38b304226d192dfe `
-URI wmicimv2/* `
-Credential $cred;
PowerShell
-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
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.
7 Note
This operation is not valid for a URI if Shell operations are also
supported.
7 Note
This operation is not valid for a URI if Shell operations are also
supported.
7 Note
This operation is not valid for a URI if Shell operations are also
supported.
7 Note
This operation is not valid for a URI if Shell operations are also
supported.
7 Note
This operation is not valid for a URI if Shell operations are also
supported.
7 Note
This operation is not valid for a URI if Shell operations are also
supported.
7 Note
This operation is not valid for a URI if Shell operations are also
supported.
7 Note
This operation is not valid for a URI if ANY other operation is also
supported.
7 Note
Cmdlets supported
New-Item
CertificateThumbprint <String>
Specifies the thumbprint of the service certificate.
Cmdlets supported
New-Item
Enabled <Boolean>
Specifies whether the listener is enabled or disabled. The default is True.
Cmdlets Supported
New-Item
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
Cmdlets Supported
New-Item
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.
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.
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.
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:
Cmdlets Supported
New-Item
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
See also
about_Providers
Connect-WSMan
Reference
Module: Microsoft.WSMan.Management
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
PS C:\> cd wsman:
PS WSMan:\>
PS WSMan:\> dir
WSManConfig: Microsoft.WSMan.Management\WSMan::WSMan
ComputerName Type
------------ ----
localhost Container
server01 Container
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.
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.
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.
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 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>
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
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-
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
Position: Named
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.
Type: String
Position: Named
-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
-ConnectionURI
<Transport>://<Server>:<Port>/<ApplicationName>
The following string is a correctly formatted value for this parameter:
http://Server01:8080/WSMAN
Type: Uri
Position: Named
-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
[email protected] . 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
-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
-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
-SessionOption
Type: Microsoft.WSMan.Management.SessionOption
Aliases: so
Position: Named
-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.
Type: SwitchParameter
Position: Named
Inputs
None
Outputs
None
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
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.
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
This command disables CredSSP on the client, which prevents delegation to servers.
This command disables CredSSP on the server, which prevents delegation from clients.
Parameters
-Role
Disables CredSSP on the server. This cmdlet sets the WS-Management setting
<localhost|computername>\Client\Auth\CredSSP to false.
Type: String
Position: 0
Inputs
None
Outputs
None
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
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
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
Inputs
None
Outputs
None
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
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.
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
PowerShell
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
7 Note
PowerShell
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
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.
PowerShell
PowerShell
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
-Force
Type: SwitchParameter
Position: Named
-Role
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.
If you specify Server, the following actions are performed. This policy setting allows
the
server to act as a delegate for clients.
Type: String
Position: 0
Inputs
None
Outputs
XmlElement
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.
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
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.
Inputs
None
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
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.
Examples
This command returns only the status of the Spooler service on the remote server01
computer.
This command returns endpoint references that correspond to all the services on the
local computer.
This command lists all of the services that meet the following criteria on the remote
Server01
computer:
This command lists the WS-Management listener configuration on the local computer
for the listener
that matches the criteria in the selector set.
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
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.
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>
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
-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
-Authentication
Basic - Basic is a scheme in which the user name and password are sent in
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,
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
Position: Named
-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
Position: Named
-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.
Type: String
Position: Named
-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
-ConnectionURI
<Transport>://<Server>:<Port>/<ApplicationName>
Type: Uri
Aliases: CURI, CU
Position: Named
-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
[email protected]. 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
-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
-Enumerate
Indicates that this cmdlet returns all of the instances of a management resource.
Type: SwitchParameter
Position: Named
-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:
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
-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
-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
-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
-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.
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
-ReturnType
Specifies the type of data to be returned. The acceptable values for this parameter
are:
Object
EPR
ObjectAndEPR
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
Position: Named
-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
-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
-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
-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.
Type: SwitchParameter
Aliases: SSL
Position: Named
Inputs
None
Outputs
XmlElement
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
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.
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.
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:\ .
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
Type: String
Position: 1
-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
-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
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
Position: Named
-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.
Type: String
Position: Named
-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
-ConnectionURI
Specifies the connection endpoint. The format of this string is:
<Transport>://<Server>:<Port>/<ApplicationName>
http://Server01:8080/WSMAN
Type: Uri
Aliases: CURI, CU
Position: Named
-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
[email protected]. 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
-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 -
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
-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
-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
-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.
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
-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
-SessionOption
Type: Microsoft.WSMan.Management.SessionOption
Aliases: so
Position: Named
-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
-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
Inputs
None
Outputs
XmlElement
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
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
PowerShell
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
-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
Position: Named
-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.
Type: String
Position: Named
-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
-ConnectionURI
Specifies the connection endpoint.
The format of this string is:
<Transport>://<Server>:<Port>/<ApplicationName>
http://Server01:8080/WSMAN
Type: Uri
Aliases: CURI, CU
Position: Named
-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
"[email protected]". 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
-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 -
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
-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
-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
-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.
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
-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
-SessionOption
Type: Microsoft.WSMan.Management.SessionOption
Aliases: so
Position: Named
-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.
Type: SwitchParameter
Position: Named
-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
Inputs
None
Outputs
XmlElement
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
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 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
-NoEncryption
Indicates that the connection does not use encryption for remote operations over
HTTP.
Type: SwitchParameter
Position: Named
-OperationTimeout
Type: Int32
Aliases: OperationTimeoutMSec
Position: Named
-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
ProxyNoProxyServer - Do not use a proxy server. Resolve all host names locally.
Type: Microsoft.WSMan.Management.ProxyAccessType
Position: Named
-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
Type: Microsoft.WSMan.Management.ProxyAuthentication
Position: Named
-ProxyCredential
Specifies a user account that has permission to gain access through an intermediate
Web proxy.
Type: PSCredential
Position: Named
-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
-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
-SkipRevocationCheck
Indicates that the connection does not validate the revocation status on the server
certificate.
Type: SwitchParameter
Position: Named
-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
-UseUTF16
Indicates that the connection encodes the request in UTF16 format instead of UTF8
format. The
default is UTF8 encoding.
Type: SwitchParameter
Position: Named
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
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
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>
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
-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
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,
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
Position: Named
-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.
Type: String
Position: Named
-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
-ConnectionURI
<Transport>://<Server>:<Port>/<ApplicationName>
Type: Uri
Position: Named
-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
[email protected] . Or, enter a
PSCredential object, such as one returned by the Get-
Type: PSCredential
Aliases: cred, c
Position: Named
-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
-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
-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.
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
-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
-SessionOption
Type: Microsoft.WSMan.Management.SessionOption
Aliases: so
Position: Named
-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.
Type: SwitchParameter
Aliases: ssl
Position: Named
Inputs
None
Outputs
None
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
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
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 :
) Important
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
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 :
) Important
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
-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
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
Position: Named
-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.
Type: String
Position: Named
-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
-ConnectionURI
<Transport>://<Server>:<Port>/<ApplicationName>
The following string is a properly formatted value for this parameter:
http://Server01:8080/WSMAN
Type: Uri
Position: Named
-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
[email protected] . 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
-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
-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:
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
-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
-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
-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
-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.
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
-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
Type: Microsoft.WSMan.Management.SessionOption
Aliases: so
Position: Named
-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.
Type: SwitchParameter
Aliases: ssl
Position: Named
-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
Inputs
None
Outputs
None
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
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.
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.
Examples
PowerShell
Set-WSManQuickConfig
PowerShell
Set-WSManQuickConfig -UseSSL
7 Note
HTTPS requires manual configuration. For more information, see the UseSSL
parameter's
description.
Parameters
-Force
Type: SwitchParameter
Position: Named
-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.
Type: SwitchParameter
Position: Named
-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
Outputs
None
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
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
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
This command determines whether the WinRM service is running on the server01
computer.
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.
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>
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
-Authentication
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
Type: Microsoft.WSMan.Management.AuthenticationMechanism
Aliases: auth, am
Position: Named
-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.
Position: Named
-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
-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
[email protected]. 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
-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
-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.
Type: SwitchParameter
Position: Named
Inputs
None
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.
Syntax
PowerShell
Disable-PSTrace
[-AnalyticOnly]
[<CommonParameters>]
Description
This cmdlet disables the Operational and Analytic event logs of the Microsoft-Windows-
PowerShell
event provider.
Examples
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
Inputs
None
Outputs
None
Notes
This cmdlet uses the Get-LogProperties and Set-LogProperties cmdlets.
Related Links
Get-LogProperties
Set-LogProperties
Enable-PSTrace
Disable-PSWSManCombinedTrace
Reference
Module: PSDiagnostics
Syntax
PowerShell
Disable-PSWSManCombinedTrace []
Description
This cmdlet stops the logging session started by Enable-PSWSManCombinedTrace .
Examples
Disable-PSWSManCombinedTrace
Inputs
None
Outputs
None
This cmdlet returns no output.
Related Links
Event Tracing
Stop-Trace
Enable-PSWSManCombinedTrace
Disable-WSManTrace
Reference
Module: PSDiagnostics
Syntax
PowerShell
Disable-WSManTrace []
Description
This cmdlet stops the WSMan logging session started by Enable-WSManTrace.
Examples
Disable-WSManTrace
Inputs
None
Outputs
None
This cmdlet returns no output.
Related Links
Event Tracing
Stop-Trace
Enable-WSManTrace
Enable-PSTrace
Reference
Module: PSDiagnostics
Syntax
PowerShell
Enable-PSTrace
[-Force]
[-AnalyticOnly]
Description
This cmdlet enables the Operational and Analytic event logs of the Microsoft-Windows-
PowerShell
event provider.
Examples
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
-Force
Type: SwitchParameter
Position: Named
Inputs
None
Outputs
None
Notes
This cmdlet uses the Get-LogProperties and Set-LogProperties cmdlets.
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
Examples
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
Inputs
None
Outputs
None
Related Links
Event Tracing
Start-Trace
Disable-PSWSManCombinedTrace
Enable-WSManTrace
Reference
Module: PSDiagnostics
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
Examples
Inputs
None
Outputs
None
Related Links
Event Tracing
Start-Trace
Disable-WSManTrace
Get-LogProperties
Reference
Module: PSDiagnostics
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
Enabled : True
Type : Admin
Retention : False
AutoBackup : False
MaxLogSize : 15728640
Parameters
-Name
The name of the event provider.
Type: Object
Position: 0
Inputs
Object
Outputs
Microsoft.PowerShell.Diagnostics.LogDetails
Related Links
Set-LogProperties
Enable-PSTrace
Disable-PSTrace
Set-LogProperties
Reference
Module: PSDiagnostics
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.
Examples
$logDetails.Retention = $True
Enabled : True
Type : Admin
Retention : True
AutoBackup : False
MaxLogSize : 15728640
Parameters
-Force
Type: SwitchParameter
Position: Named
-LogDetails
Type: Microsoft.PowerShell.Diagnostics.LogDetails
Position: 0
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
Notes
You must run this cmdlet from an elevated PowerShell session.
Related Links
Get-LogProperties
Enable-PSTrace
Disable-PSTrace
Start-Trace
Reference
Module: PSDiagnostics
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.
Enable-PSWSManCombinedTrace
Enable-WSManTrace
Examples
$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
Type: Int32
Position: Named
Default value: 0
-ETS
Type: SwitchParameter
Position: Named
-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
Position: Named
-MaxBuffers
Type: Int32
Position: Named
-MaxLogFileSizeInMB
Sets the maximum log file size in megabytes (MB) or number of records for SQL logs.
Type: Int32
Position: Named
-MinBuffers
Position: Named
Default value: 0
-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
-ProviderFilePath
Type: String
Position: 2
-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
Inputs
None
Outputs
None
Related Links
Event Tracing
Stop-Trace
Disable-PSWSManCombinedTrace
Disable-WSManTrace
Enable-PSWSManCombinedTrace
Enable-WSManTrace
Stop-Trace
Reference
Module: PSDiagnostics
Syntax
PowerShell
Stop-Trace
[-SessionName] <Object>
[-ETS]
[<CommonParameters>]
Description
This cmdlet stops a Windows Event Trace logging session.
Disable-PSWSManCombinedTrace
Disable-WSManTrace
Examples
Parameters
-ETS
Send commands to Event Trace Sessions directly without saving or scheduling.
Type: SwitchParameter
Position: Named
-SessionName
Type: Object
Position: 0
Inputs
None
Outputs
None
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.
PSReadLine
Get-PSReadLineKeyHandler Gets the key bindings for the PSReadLine module.
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 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.
PowerShell
PowerShell
You can bind a ScriptBlock to a key. The ScriptBlock can do pretty much
anything you
want. Some useful examples include
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'
ScriptBlock = {
$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)
[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
$template -f $token
PowerShell
PSReadLine 2.2.6
PSReadLine 2.2.5
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
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.
Using the
Microsoft.PowerShell.PSConsoleReadLine class
The following functions are available in the class
Microsoft.PowerShell.PSConsoleReadLine.
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.
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.
BackwardKillLine
Clear the input from the start of the input to the cursor. The cleared text is
placed in the
kill-ring.
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.
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.
DeleteLine
Deletes the current line, enabling undo.
DeleteLineToFirstChar
Deletes text from the cursor to the first non-blank character of the line.
DeleteWord
Delete the next word.
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.
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.
) 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.
PasteBefore
Paste the clipboard before the cursor, moving the cursor to the end of the
pasted text.
PrependAndAccept
Prepend a '#' and accept the line.
Redo
Undo an undo.
Cmd: <Ctrl+y>
Vi insert mode: <Ctrl+y>
Vi command mode: <Ctrl+y>
RepeatLastCommand
Repeat the last text modification.
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.
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.
ViAcceptLineOrExit
Like DeleteCharOrExit in Emacs mode, but accepts the line instead of deleting a
character.
ViAppendLine
A new line is inserted below the current line.
ViBackwardDeleteGlob
Deletes the previous word, using only whitespace as the word delimiter.
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.
ViDeleteEndOfGlob
Delete to the end of the word.
ViDeleteGlob
Delete the next glob (whitespace delimited word).
ViDeleteToBeforeChar
Deletes until given character.
ViDeleteToBeforeCharBackward
Deletes until given character.
ViDeleteToChar
Deletes until given character.
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.
ViInsertAtEnd
Switch to Insert mode and position the cursor at the end of the line.
ViInsertLine
A new line is inserted above the current line.
ViInsertWithAppend
Append from the current line position.
ViInsertWithDelete
Delete the current character and switch to Insert mode.
ViJoinLines
Joins the current line and the next line.
ViReplaceLine
Erase the entire command line.
Vi command mode: <S> , <c,c>
ViReplaceToBeforeChar
Replaces until given character.
ViReplaceToBeforeCharBackward
Replaces until given character.
ViReplaceToChar
Deletes until given character.
ViReplaceToCharBackward
Replaces until given character.
ViYankBeginningOfLine
Yank from the beginning of the buffer to the cursor.
ViYankEndOfGlob
Yank from the cursor to the end of the WORD(s).
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.
ViYankLine
Yank the entire buffer.
ViYankNextGlob
Yank from cursor to the start of the next WORD(s).
ViYankNextWord
Yank the word(s) after the cursor.
ViYankPercent
Yank to/from matching brace.
ViYankPreviousGlob
Yank from beginning of the WORD(s) to cursor.
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.
ViYankToEndOfLine
Yank from the cursor to the end of the buffer.
ViYankToFirstChar
Yank from the first non-whitespace character to the cursor.
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.
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>
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.
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.
GotoFirstNonBlankOfLine
Move the cursor to the first non-blank character in the line.
MoveToEndOfLine
Move the cursor to the end of the input.
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>
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>
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.
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.
ViNextGlob
Moves to the next word, using only whitespace as a word delimiter.
ViNextWord
Move the cursor forward to the start of the next word. Word boundaries are
defined by
a configurable set of characters.
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.
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.
ViTabCompletePrevious
Ends the current edit group, if needed, and invokes TabCompletePrevious.
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 .
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.
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.
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.
RepeatLastCharSearchBackwards
Repeat the last recorded character search, but in the opposite direction.
RepeatSearchBackward
Repeat the last search in the same direction as before.
SearchChar
Read the next character and then find it, going forward, and then back off a
character.
This is for 't' functionality.
SearchCharBackward
Read the next character and then find it, going backward, and then back off a
character.
This is for 'T' functionality.
SearchCharBackwardWithBackoff
Read the next character and then find it, going backward, and then back off a
character.
This is for 'T' functionality.
SearchCharWithBackoff
Read the next character and then find it, going forward, and then back off a
character.
This is for 't' functionality.
SearchForward
Prompts for a search string and initiates search upon AcceptLine.
C#
C#
void ClearKillRing()
C#
C#
void Ding()
C#
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]
C#
Microsoft.PowerShell.PSConsoleReadLineOptions GetOptions()
C#
C#
void Insert(char c)
void Insert(string s)
C#
System.Management.Automation.EngineIntrinsics engineIntrinsics)
C#
C#
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#
Move the cursor to the given offset. Cursor movement isn't tracked for undo.
C#
C#
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
See Also
about_PSReadLine
Get-PSReadLineKeyHandler
Reference
Module: PSReadLine
Syntax
PowerShell
Get-PSReadLineKeyHandler
[-Bound]
[-Unbound]
[<CommonParameters>]
Description
The Get-PSReadLineKeyHandler cmdlet returns the currently bound key bindings.
Examples
PowerShell
...
PowerShell
Get-PSReadLineKeyHandler
...
Parameters
-Bound
Type: SwitchParameter
Position: Named
-Unbound
Type: SwitchParameter
Position: Named
Inputs
None
Outputs
KeyHandler
Related Links
Remove-PSReadLineKeyHandler
Get-PSReadLineOption
Set-PSReadLineOption
Set-PSReadLineKeyHandler
Get-PSReadLineOption
Reference
Module: PSReadLine
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
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
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
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
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
Syntax
PowerShell
Remove-PSReadLineKeyHandler
[-Chord] <String[]>
[-ViMode <ViMode>]
[<CommonParameters>]
Description
The Remove-PSReadLineKeyHandler cmdlet removes a specified key binding.
Examples
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
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
-ViMode
Specify which vi mode the binding applies to. Possible values are: Insert, Command.
Type: ViMode
Position: Named
Inputs
None
Outputs
None
Related Links
Get-PSReadLineKeyHandler
Get-PSReadLineOption
Set-PSReadLineOption
Set-PSReadLineKeyHandler
Set-PSReadLineKeyHandler
Reference
Module: PSReadLine
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
PowerShell
[Microsoft.PowerShell.PSConsoleReadLine]::RevertLine()
[Microsoft.PowerShell.PSConsoleReadLine]::Insert('build')
[Microsoft.PowerShell.PSConsoleReadLine]::AcceptLine()
Parameters
-BriefDescription
Type: String
Position: Named
-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
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
-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
-Function
Type: String
Position: 1
Default value: None
-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
-ViMode
Insert
Command
Type: ViMode
Position: Named
Inputs
None
Related Links
Get-PSReadLineKeyHandler
Remove-PSReadLineKeyHandler
Get-PSReadLineOption
Set-PSReadLineOption
Set-PSReadLineOption
Reference
Module: 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
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" .
PowerShell
7 Note
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.
PowerShell
Set-PSReadLineOption -Colors @{
Command = 'Magenta'
Number = 'DarkGray'
Member = 'DarkGray'
Operator = 'DarkGray'
Type = 'DarkGray'
Variable = 'DarkGreen'
Parameter = 'DarkGreen'
ContinuationPrompt = 'DarkGray'
Default = 'DarkGray'
}
PowerShell
Set-PSReadLineOption -Colors @{
"Error" = [ConsoleColor]::DarkRed
"String" = "$([char]0x1b)[38;5;100m"
# RGB value
"Command" = "#8181f7"
PowerShell
function OnViModeChange {
} else {
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.
Parameters
-AddToHistoryHandler
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 .
Type: Func<T,TResult>[System.String,System.Object]
Position: Named
Default value: None
-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
-BellStyle
Type: BellStyle
Position: Named
-Colors
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.
256 color
24-bit color
Foreground, background, or both
Inverse, bold
For more information about ANSI color codes, see ANSI escape code in Wikipedia.
Position: Named
-CommandValidationHandler
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.
Type: Action<T>[CommandAst]
Position: Named
-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
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
-DingDuration
Type: Int32
Position: Named
-DingTone
Specifies the tone in Hertz (Hz) of the beep when BellStyle is set to Audible.
Type: Int32
Position: Named
-EditMode
Specifies the command line editing mode. Using this parameter resets any key
bindings set by
Set-PSReadLineKeyHandler .
Use Get-PSReadLineKeyHandler to see the key bindings for the currently configured
EditMode.
Type: EditMode
Position: Named
-ExtraPromptLineCount
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
-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.
Using the following command, you can set the property value directly:
(Get-PSReadLineOption).HistoryNoDuplicates = $False
Type: SwitchParameter
Position: Named
-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 .
$env:APPDATA\Microsoft\Windows\PowerShell\PSReadLine\$($Host.Name)_history.txt
Type: String
Position: Named
-HistorySaveStyle
Type: HistorySaveStyle
Position: Named
-HistorySearchCaseSensitive
Using the following command, you can set the property value directly:
(Get-PSReadLineOption).HistorySearchCaseSensitive = $False
Type: SwitchParameter
Position: Named
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.
Using the following command, you can set the property value directly:
(Get-PSReadLineOption).HistorySearchCursorMovesToEnd = $False
Type: SwitchParameter
Position: Named
-MaximumHistoryCount
Type: Int32
Position: Named
-MaximumKillRingCount
Type: Int32
Position: Named
Default value: 10
-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:
Then set:
Type: String[]
Position: Named
-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 .
(Get-PSReadLineOption).ShowToolTips = $False
Type: SwitchParameter
Position: Named
-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 .
Type: ScriptBlock
Position: Named
-ViModeIndicator
This option sets the visual indication for the current Vi mode. Either insert mode or
command
mode.
Type: ViModeStyle
Position: Named
Default value: None
-WordDelimiters
Specifies the characters that delimit words for functions like ForwardWord or
KillWord.
Type: String
Position: Named
Inputs
None
Outputs
None
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.
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 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.
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.
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
The Get-ScheduledJob cmdlet gets the scheduled jobs on the local computer.
PowerShell
Get-ScheduledJob
Output
PowerShell
Output
PowerShell
-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
PowerShell
Get-ScheduledJob ProcessJob
Output
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
Output
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.
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
PowerShell
Unregister-ScheduledJob ProcessJob
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.
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.
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.
PowerShell
Get-ChildItem $HOME\AppData\Local\Microsoft\Windows\PowerShell\ScheduledJobs
Output
Directory: C:\Users\User01\AppData\Local
\Microsoft\Windows\PowerShell\ScheduledJobs
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
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
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
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.
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.
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
PowerShell
Output
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
PowerShell
The following command deletes the execution history and the current saved
results of
the ProcessJob scheduled job.
PowerShell
PowerShell
Get-ScheduledJob |
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.
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.
PowerShell
Output
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
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.
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
PowerShell
Output
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
PowerShell
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
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.
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-
True.
PowerShell
Set-ScheduledJobOption -WakeToRun
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
PowerShell
Import-Module PSScheduledJob
Get-Job
PowerShell
Output
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
Output
Name Id BeginTime
---- -- ---------
7 Note
PowerShell
Import-Module PSScheduledJob
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.
7 Note
To get a list of all instances of a scheduled job, use the Get-Job cmdlet.
PowerShell
Import-Module PSScheduledJob
Get-Job ProcessJob
Output
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
Output
Name Id PSBeginTime
---- -- ---------
PowerShell
Receive-Job -ID 50
$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
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.
PowerShell
Import-Module PSScheduledJob
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
PowerShell
Import-Module PSScheduledJob
Receive-Job -ID 50
Output
PowerShell
Import-Module PSScheduledJob
Output
PowerShell
Output
PowerShell
Get-ScheduledJob
PowerShell
(Get-ScheduledJob <JobName>).ExecutionHistoryLength
PowerShell
(Get-ScheduledJob ProcessJob).ExecutionHistoryLength
PowerShell
PowerShell
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.
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.
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
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
PowerShell
Output
Id Enabled
-- -------
1 True
2 True
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
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
Check the Task Scheduler event log for errors. To check the log, use Event
Viewer or a
PowerShell command such as the following:
PowerShell
Check the job record in Task Scheduler. PowerShell scheduled jobs are stored in
the
following Task Scheduled folder:
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.
$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>
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
Verify the value of the Name parameter, and then try the command again.
PSArgumentException
+ FullyQualifiedErrorId : JobWithSpecifiedNameNotFound,Microsoft.PowerShell.
Commands.GetJobCommand
PowerShell
Get-Job
Get-ScheduledJob ProcessJob
Output
PowerShell
Get-Job ProcessJob
Output
See also
about_Scheduled_Jobs
about_Scheduled_Jobs_Basics
about_Scheduled_Jobs_Advanced
PSScheduledJob module cmdlets
Task Scheduler
Add-JobTrigger
Reference
Module: PSScheduledJob
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.
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.
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.
Examples
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.
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
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.
Type: Int32[]
Position: 0
-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
-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
-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
Inputs
Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger
You can pipe a job trigger to this cmdlet.
Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition
Outputs
None
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
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.
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.
Examples
PowerShell
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.
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
These commands disable all job triggers on two scheduled jobs and display the results.
PowerShell
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
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger
Outputs
None
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
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.
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.
Examples
PowerShell
This command disables the scheduled job with ID 2 on the local computer.
PowerShell
1 ArchiveProje... {} C:\Scripts\Archive-DxProjects.ps1
False
You can re-enable scheduled job by using the Enable-ScheduledJob cmdlet and run a
disabled
scheduled job by using the Start-Job cmdlet.
PowerShell
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.
PowerShell
PowerShell
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
Type: SwitchParameter
Aliases: cf
Position: Named
Default value: False
-Id
Disables the scheduled job with the specified identification number (ID).
Enter the ID
of a scheduled job.
Type: Int32
Position: 0
-InputObject
Type: Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition
Position: 0
-Name
Disables the scheduled jobs with the specified names. Enter the name of a scheduled
job. Wildcards
are supported.
Type: String
Position: 0
-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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition
Outputs
None
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
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 .
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.
Examples
Example 1: Enable a job trigger
PowerShell
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.
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.
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
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
Type: SwitchParameter
Aliases: cf
Position: Named
Type: Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger[]
Position: 0
-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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Outputs
None
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
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 .
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.
Examples
PowerShell
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.
PowerShell
Get-ScheduledJob | Enable-ScheduledJob
The Get-ScheduledJob cmdlet gets all scheduled jobs and pipes them to Enable-
ScheduledJob cmdlet
to enable them.
PowerShell
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.
This command enables scheduled jobs that have "test" in their names on two remote
computers, Srv01
and Srv10.
Parameters
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-Id
Enables the scheduled job with the specified identification number (ID). Enter the ID
of a scheduled
job.
Type: Int32
Position: 0
-InputObject
Type: Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition
Position: 0
-Name
Enables the scheduled jobs with the specified names. Enter the name of a scheduled
job. Wildcards
are supported.
Type: String
Position: 0
-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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition
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
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 .
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.
Examples
The command uses the Name parameter of Get-JobTrigger to get the job triggers of
the BackupJob
scheduled job.
PowerShell
Get-ScheduledJob
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 ).
PowerShell
This command gets the job triggers of all jobs that have Backup or Archive in their
names.
PowerShell
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.
PowerShell
Get-ScheduledJob | Get-JobTrigger |
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.
PowerShell
(Get-ScheduledJob Test-HelpFiles).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
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.
Type: Int32
Position: 0
-InputObject
Type: Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition
Position: 0
-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
-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
Inputs
Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition
Outputs
Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger
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
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.
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
PowerShell
Get-ScheduledJob
PowerShell
PowerShell
PowerShell
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
-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
Inputs
None
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
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.
Examples
PowerShell
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.
PowerShell
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.
PowerShell
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.
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
Type: Int32
Position: 0
-InputObject
Type: Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition
Position: 0
-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
Inputs
Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition
Outputs
Microsoft.PowerShell.ScheduledJob.ScheduledJobOptions
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
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.
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.
Examples
PowerShell
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.
PowerShell
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.
PowerShell
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
This command creates a job trigger to start a scheduled job whenever the domain
administrator logs
onto the computer.
PowerShell
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.
PowerShell
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.
PowerShell
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.
PowerShell
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.
PowerShell
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 ).
PowerShell
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
-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
-AtStartup
Type: SwitchParameter
Position: 0
-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
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
-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[]
Position: Named
-Once
Position: 0
-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
-RepeatIndefinitely
Type: SwitchParameter
Position: Named
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 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
-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
-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
-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
-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
Inputs
None
Outputs
Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger
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.
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
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.
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.
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.
Examples
PowerShell
New-ScheduledJobOption
PowerShell
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 .
PowerShell
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 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.
PowerShell
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
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.
Type: SwitchParameter
Position: Named
-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.
Type: SwitchParameter
Position: Named
-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.
Type: SwitchParameter
Position: Named
-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.
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
-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.
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
-MultipleInstancePolicy
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
Position: Named
-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.
Type: SwitchParameter
Position: Named
-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).
Type: SwitchParameter
Position: Named
-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
-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
-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
-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.
Type: SwitchParameter
Position: Named
-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
Inputs
None
Outputs
Microsoft.PowerShell.ScheduledJob.ScheduledJobOptions
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:
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
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.
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.
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.
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.
Examples
Example 1: Create a scheduled job
This example creates a scheduled job on the local computer.
PowerShell
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.
PowerShell
$path = "\\Srv01\Scripts\UpdateVersion.ps1"
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.
PowerShell
$T = @{
Frequency="Weekly"
At="9:00PM"
DaysOfWeek="Monday"
Interval=2
$O = @{
WakeToRun=$true
StartIfNotIdle=$false
MultipleInstancePolicy="Queue"
PowerShell
$Cred = Get-Credential
$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 Register-ScheduledJob @params command creates the scheduled job with the
parameters from the
script block.
PowerShell
$Admin = Get-Credential
$T = New-JobTrigger -Weekly -At "9:00 PM" -DaysOfWeek Monday -WeeksInterval
2
$params = @{
AsJob = $true
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 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
-Authentication
Specifies the mechanism that is used to authenticate the user's credentials. The
default value is
Default.
Default
Basic
Credssp
Digest
Kerberos
Negotiate
NegotiateWithImplicitCredential
U Caution
Type: AuthenticationMechanism
Position: Named
-Confirm
Type: SwitchParameter
Aliases: cf
Position: Named
-Credential
Specifies a user account that has permission to run the scheduled job. The default is
the current
user.
7 Note
Type: PSCredential
Position: Named
-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
-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.
Type: ScriptBlock
Position: Named
-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
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
-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
-RunAs32
Type: SwitchParameter
Position: Named
-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
-RunNow
Type: SwitchParameter
Position: Named
-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.
MultipleInstancePolicy="IgnoreNew"}
Type: Microsoft.PowerShell.ScheduledJob.ScheduledJobOptions
Position: Named
-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.
Type: ScriptBlock
Position: 1
-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.
For example:
Type: Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger[]
Position: Named
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet isn't run.
Type: SwitchParameter
Aliases: wi
Position: Named
Outputs
Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition
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 doesn't run, use the following methods to find the reason:
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
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.
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.
Examples
This command deletes all job triggers from scheduled job that have names that begin
with Test.
This command deletes only the third trigger (ID = 3) from the BackupArchive scheduled
job.
function Delete-AtStartup
}
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.
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.
Type: Int32[]
Position: 0
-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
-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
-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
Inputs
Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition
Outputs
None
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
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.
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.
Examples
PowerShell
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-
This command is not required; it is included only to show the effect of the trigger
change.
PowerShell
2 AtStartup
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.
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 .
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
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,
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
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
-AtStartup
Type: SwitchParameter
Position: Named
-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
-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
-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[]
Position: Named
-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
-Once
Type: SwitchParameter
Position: Named
-PassThru
Returns the job triggers that changed. By default, this cmdlet does not generate any
output.
Type: SwitchParameter
Position: Named
-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
-RepeatIndefinitely
Type: SwitchParameter
Position: Named
-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 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
-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
-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
-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
-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
Inputs
Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger
Outputs
None
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
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.
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.
Examples
PowerShell
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
This command is not required; it is included only to show the effect of the script change.
PowerShell
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.
PowerShell
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
-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
Type: AuthenticationMechanism
Position: Named
-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
-Credential
Specifies a user account that has permission to run the scheduled job. The default is
the current
user.
Type: PSCredential
Position: Named
-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
-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.
Type: ScriptBlock
Position: Named
-InputObject
If you specify multiple scheduled jobs, Set-ScheduledJob makes the same changes to
all jobs.
Type: Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition
Position: 0
-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
To delete the current execution history and job results, use the
ClearExecutionHistory
parameter.
Type: Int32
Position: Named
-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
-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
-RunAs32
Type: SwitchParameter
Position: Named
-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
-RunNow
Type: SwitchParameter
Position: Named
-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 .
Type: Microsoft.PowerShell.ScheduledJob.ScheduledJobOptions
Position: Named
-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.
Type: ScriptBlock
Position: Named
-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.
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
Type: Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger[]
Position: Named
Inputs
Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition
Outputs
None
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
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.
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.
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.
Examples
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 :
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.
Get-ScheduledJob |
Get-ScheduledJobOption |
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.
Type: SwitchParameter
Position: Named
-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.
Type: SwitchParameter
Position: Named
-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.
Type: SwitchParameter
Position: Named
-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
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
-InputObject
Type: Microsoft.PowerShell.ScheduledJob.ScheduledJobOptions
Position: 0
-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
Position: Named
-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
-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
-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).
Type: SwitchParameter
Position: Named
-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
-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
-StartIfOnBattery
Starts the scheduled job even if the computer is running on batteries at the
scheduled start time.
The default value is $false .
Type: SwitchParameter
Position: Named
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.
Type: SwitchParameter
Position: Named
-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
Inputs
Microsoft.PowerShell.ScheduledJob.ScheduledJobOptions
You can pipe a scheduled job options object to this cmdlet.
Outputs
None
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
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.
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.
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.
Examples
Unregister-ScheduledJob TestJob
This command deletes the TestJob scheduled job on the local computer.
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.
Both commands use the Force parameter, which deletes a scheduled job even if an
instance of the
job is running.
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
Type: SwitchParameter
Aliases: cf
Position: Named
-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
-Id
Deletes the scheduled jobs with the specified identification numbers (ID). Enter the
IDs of
scheduled jobs on the computer.
Type: Int32[]
Position: 0
-InputObject
JobTrigger .
Type: Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition[]
Position: 0
-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
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter
Aliases: wi
Position: Named
Inputs
Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition
Outputs
None
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.
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
Several of the activity common parameters are also workflow common parameters
or
Windows PowerShell common parameters. Other activity common parameters are
unique to activities.
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
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.
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
Stop . Displays the error message and stops executing the command.
Input <Object[]>
Submits a collection of objects to