Category Archives: Invoke

Invoke-WmiMethod

NAME
    Invoke-WmiMethod

SYNOPSIS
    Calls Windows Management Instrumentation (WMI) methods.

SYNTAX
    Invoke-WmiMethod [-Class] <string> [[-ArgumentList] <Object[]>] [-Authentication {Default | None | Connect | Call | Packet | PacketIntegrity | PacketPrivacy | Unchanged}] [-Authority <string>] [-ComputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {Default | Anonymous | Identify | Impersonate | Delegate}] [-Locale <string>] [-Namespace <string>] [-Name] <string> [-AsJob] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

    Invoke-WmiMethod [-Authentication {Default | None | Connect | Call | Packet | PacketIntegrity | PacketPrivacy | Unchanged}] [-Authority <string>] [-ComputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {Default | Anonymous | Identify | Impersonate | Delegate}] [-Locale <string>] [-Namespace <string>] [-Name] <string> [-AsJob] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

    Invoke-WmiMethod -InputObject <ManagementObject> [-ArgumentList <Object[]>] [-Name] <string> [-AsJob] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

    Invoke-WmiMethod -Path <string> [-ArgumentList <Object[]>] [-Authentication {Default | None | Connect | Call | Packet | PacketIntegrity | PacketPrivacy | Unchanged}] [-Authority <string>] [-ComputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {Default | Anonymous | Identify | Impersonate | Delegate}] [-Locale <string>] [-Namespace <string>] [-Name] <string> [-AsJob] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

    Invoke-WmiMethod [-Authentication {Default | None | Connect | Call | Packet | PacketIntegrity | PacketPrivacy | Unchanged}] [-Authority <string>] [-ComputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {Default | Anonymous | Identify | Impersonate | Delegate}] [-Locale <string>] [-Namespace <string>] [-Name] <string> [-AsJob] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

    Invoke-WmiMethod [-Authentication {Default | None | Connect | Call | Packet | PacketIntegrity | PacketPrivacy | Unchanged}] [-Authority <string>] [-ComputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {Default | Anonymous | Identify | Impersonate | Delegate}] [-Locale <string>] [-Namespace <string>] [-Name] <string> [-AsJob] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>]

DESCRIPTION
    The Invoke-WmiMethod cmdlet calls WMI methods.

PARAMETERS
    -ArgumentList <Object[]>
        Specifies the parameters to pass to the called method. The value of this parameter must be an array of objects and they must appear in the order required by the called method.

        Important: A second value of $null is required, otherwise the command will generate an error, such as “Unable to cast object of type ‘System.Byte’ to type ‘System.Array’.”.

        An example using an array of objects ($binSD) followed by a null value ($null) follows:

        PS C:\> $acl = Get-Acl test.txt
        PS C:\> $binSD = $acl.GetSecurityDescriptorBinaryForm()
        PS C:\> Invoke-WmiMethod -Class Win32_SecurityDescriptorHelper -Name BinarySDToSDDL -ArgumentList $binSD, $null

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -AsJob [<SwitchParameter>]
        Runs the command as a background job. Use this parameter to run commands that take a long time to finish.

        When you use the AsJob parameter, the command returns an object that represents the background job and then displays the command prompt. You can continue to work in the session while the job finishes. If Invoke-WmiMethod is used against a remote computer, the job is created on the local computer, and the results from remote computers are automatically returned to the local computer. To manage the job, use the cmdlets that contain the Job noun (the Job cmdlets). To get the job results, use the Receive-Job cmdlet.

        Note: To use this parameter with remote computers, the local and remote computers must be configured for remoting. Additionally, you must start Windows PowerShell by using the “Run as administrator” option in Windows Vista and later versions of Windows. For more information, see about_remote_requirements.

        For more information about Windows PowerShell background jobs, see about_jobs and about_remote_Jobs.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Authentication <AuthenticationLevel>
        Specifies the authentication level to be used with the WMI connection. Valid values are:

        -1: Unchanged
        0: Default
        1: None (No authentication in performed.)
        2: Connect (Authentication is performed only when the client establishes a relationship with the application.)
        3: Call (Authentication is performed only at the beginning of each call when the application receives the request.)
        4: Packet (Authentication is performed on all the data that is received from the client.)
        5: PacketIntegrity (All the data that is transferred between the client and the application is authenticated and verified.)
        6: PacketPrivacy (The properties of the other authentication levels are used, and all the data is encrypted.)

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Authority <string>
        Specifies the authority to use to authenticate the WMI connection. You can specify standard NTLM or Kerberos authentication. To use NTLM, set the authority setting to ntlmdomain:<DomainName>, where <DomainName> identifies a valid NTLM domain name. To use Kerberos, specify kerberos:<DomainName\ServerName>. You cannot include the authority setting when you connect to the local computer.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Class <string>
        Specifies the WMI class that contains a static method to call.

        Required?                    true
        Position?                    1
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -ComputerName <string[]>
        Specifies the computer against which you want to run the management operation. The value can be a fully qualified domain name, a NetBIOS name, or an Internet Protocol (IP) address. Use the local computer name, use localhost, or use a dot (.) to specify the local computer. The local computer is the default. When the remote computer is in a different domain from the user, a fully qualified domain name is required. You can also set the value of this parameter by piping the value to the parameter.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Credential <PSCredential>
        Specifies a user account that has permission to perform this action. The default is the current user. Type a user name, such as “User01”, “Domain01\User01”, or User@Contoso.com. Or, enter a PSCredential object, such as an object that is returned by the Get-Credential cmdlet. When you type a user name, you will be prompted for a password.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -EnableAllPrivileges [<SwitchParameter>]
        Enables all the privileges of the current user before the command makes the WMI call.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Impersonation <ImpersonationLevel>
        Specifies the impersonation level to use. Valid values are:

        0: Default (Reads the local Registry for the default impersonation level, which is usually set to “3: Impersonate”.)
        1: Anonymous (Hides the credentials of the caller.)
        2: Identify (Allows objects to query the credentials of the caller.)
        3: Impersonate (Allows objects to use the credentials of the caller.)
        4: Delegate (Allows objects to permit other objects to use the credentials of the caller.)

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -InputObject <ManagementObject>
        Specifies a ManagementObject object to use as input. When this parameter is used, all other parameters except the Flag and Argument parameters are ignored.

        Required?                    true
        Position?                    named
        Default value
        Accept pipeline input?     true (ByValue)
        Accept wildcard characters? false

    -Locale <string>
        Specifies the preferred locale for WMI objects. Specify the value of the Locale parameter as an array in the MS_<LCID> format in the preferred order.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Name <string>
        Specifies the name of the method to be invoked. This parameter is mandatory and cannot be null or empty.

        Required?                    true
        Position?                    2
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Namespace <string>
        When used with the Class parameter, this parameter specifies the WMI repository namespace where the referenced WMI class or object is located.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Path <string>
        Specifies the WMI object path of a WMI class, or specifies the WMI object path of an instance of a WMI class. The class or the instance that you specify must contain the method that is specified in the Name parameter.

        Required?                    true
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -ThrottleLimit <int>
        Allows the user to specify a throttling value for the number of WMI operations that can be executed simultaneously. This parameter is used together with the AsJob parameter. The throttle limit applies only to the current command, not to the session or to the computer.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Confirm [<SwitchParameter>]
        Prompts you for confirmation before executing the command.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -WhatIf [<SwitchParameter>]
        Describes what would happen if you executed the command without actually executing the command.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    <CommonParameters>
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer and OutVariable. For more information, type,
        “Get-Help about_CommonParameters“.

INPUTS
    None
        This cmdlet does not accept any input.

OUTPUTS
    None
        This cmdlet does not generate any output.

NOTES

    ————————– EXAMPLE 1 ————————–

    C:\PS>Invoke-WmiMethod -path win32_process -Name create -ArgumentList notepad.exe

    __GENUS         : 2
    __CLASS         : __PARAMETERS
    __SUPERCLASS     :
    __DYNASTY        : __PARAMETERS
    __RELPATH        :
    __PROPERTY_COUNT : 2
    __DERIVATION     : {}
    __SERVER         :
    __NAMESPACE     :
    __PATH         :
    ProcessId        : 4844
    ReturnValue     : 0

    Description
    ———–
    This command starts an instance of Notepad by calling the Create method of the Win32_Process class.

    Note: The ReturnValue property is populated with a 0, and the ProcessId property is populated with an integer (the next process ID number) if the command is completed.

    ————————– EXAMPLE 2 ————————–

    C:\PS>Invoke-WmiMethod -path “CIM_DataFile.Name=’C:\scripts\test.txt'” -Name Rename -ArgumentList “C:\scripts\test_bu.txt”

    __GENUS         : 2
    __CLASS         : __PARAMETERS
    __SUPERCLASS     :
    __DYNASTY        : __PARAMETERS
    __RELPATH        :
    __PROPERTY_COUNT : 1
    __DERIVATION     : {}
    __SERVER         :
    __NAMESPACE     :
    __PATH         :
    ReturnValue     : 0

    Description
    ———–
    This command renames a file. It uses the Path parameter to reference an instance of the CIM_DataFile class. Then, it applies the Rename method to that particular instance.

    Note: The ReturnValue property is populated with a 0 if the command is completed.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=113346
    Get-WmiObject
    Remove-WmiObject
    Set-WmiInstance
    Get-WSManInstance
    Invoke-WSManAction
    New-WSManInstance
    Remove-WSManInstance

Invoke-WSManAction

NAME
    Invoke-WSManAction

SYNOPSIS
    Invokes an action on the object that is specified by the Resource URI and by the selectors.

SYNTAX
    Invoke-WSManAction [-ApplicationName <string>] [-ComputerName <string>] [-Credential <PSCredential>] [-Credential <PSCredential>] [-Credential <PSCredential>] [-Credential <PSCredential>] [-Credential <PSCredential>] [-Credential <PSCredential>] [-Credential <PSCredential>] [-Credential <PSCredential>] [-Credential <PSCredential>] [-Port <int>] [-Port <int>] [-Port <int>] [-Port <int>] [-Port <int>] [-Port <int>] [-Port <int>] [-Port <int>] [-Port <int>] [-UseSSL] [-ResourceURI] <Uri> [-Action] <string> [-Authentication <AuthenticationMechanism>] [-FilePath <File>] [-OptionSet <hashtable>] [-SelectorSet <hashtable>] [-SessionOption <hashtable>] [-ValueSet <hashtable>] [<CommonParameters>]

    Invoke-WSManAction [-ConnectionURI <Uri>] [-ResourceURI] <Uri> [-Action] <string> [-Authentication <AuthenticationMechanism>] [-FilePath <File>] [-OptionSet <hashtable>] [-SelectorSet <hashtable>] [-SessionOption <hashtable>] [-ValueSet <hashtable>] [<CommonParameters>]

DESCRIPTION
    The Invoke-WSManAction runs an action on the object that is specified by RESOURCE_URI, where parameters are specified by key value pairs.

    This cmdlet uses the WSMan connection/transport layer to run the action.

PARAMETERS
    -Action <string>
        Indicates the method to run on the management object specified by the ResourceURI and selectors.

        Required?                    true
        Position?                    2
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -ApplicationName <string>
        Specifies the application name in the connection. The default value of the ApplicationName parameter is WSMan. The complete identifier for the remote endpoint is in the following format:

             <transport>://<server>:<port>/<ApplicationName>

        For example:

             http://server01:8080/WSMAN

        Internet Information Services (IIS), which hosts the session, forwards requests with this endpoint to the specified application. This default setting of “WSMAN” is appropriate for most uses. This parameter is designed to be used when numerous computers establish remote connections to one computer running Windows PowerShell. In this case, IIS hosts Web Services for Management (WS-Management) for efficiency.

        Required?                    false
        Position?                    named
        Default value                WSMan
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Authentication <AuthenticationMechanism>
        Specifies the authentication mechanism to be used at the server. Possible values are:

        – Basic: Basic is a scheme in which the user name and password are sent in clear text to the server or proxy.
        – Default : Use the authentication method implemented by the WS-Management protocol. This is the default.
        – Digest: Digest is a challenge-response scheme that uses a server-specified data string for the challenge.
        – Kerberos: The client computer and the server mutually authenticate by using Kerberos Certificates.
        – Negotiate: Negotiate is a challenge-response scheme that negotiates with the server or proxy to determine the scheme to use for authentication. For example, this parameter value allows negotiation to determine whether the Kerberos protocol or NTLM is used.
        – CredSSP: Use Credential Security Service Provider (CredSSP) authentication, which allows the user to delegate credentials. This option is designed for commands that run on one remote computer but collect data from or run additional commands on other remote computers.

        Caution: CredSSP delegates the user’s credentials from the local computer to a remote computer. This practice increases the security risk of the remote operation. If the remote computer is compromised, when credentials are passed to it, the credentials can be used to control the network session.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -ComputerName <string>
        Specifies the computer against which you want to run the management operation. The value can be a fully qualified domain name, a NetBIOS name, or an IP address. Use the local computer name, use localhost, or use a dot (.) to specify the local computer. The local computer is the default. When the remote computer is in a different domain from the user, you must use a fully qualified domain name must be used. You can pipe a value for this parameter to the cmdlet.

        Required?                    false
        Position?                    named
        Default value                localhost
        Accept pipeline input?     false
        Accept wildcard characters? false

    -ConnectionURI <Uri>
        Specifies the connection endpoint. The format of this string is:

             <Transport>://<Server>:<Port>/<ApplicationName>

        The following string is a properly formatted value for this parameter:

             http://Server01:8080/WSMAN

        The URI must be fully qualified.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Credential <PSCredential>
        Specifies a user account that has permission to perform this action. The default is the current user. Type a user name, such as “User01”, “Domain01\User01”, or User@Domain.com. Or, enter a PSCredential object, such as one returned by the Get-Credential cmdlet. When you type a user name, you will be prompted for a password.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -FilePath <File>
        Specifies the path of a file that is used to update a management resource. You specify the management resource by using the ResourceURI parameter and the SelectorSet parameter. For example, the following command uses the FilePath parameter:

        Invoke-WSManAction -Action stopservice -ResourceURI wmicimv2/Win32_Service -SelectorSet @{Name=”spooler”} -FilePath:c:\input.xml -Authentication default

        This command calls the StopService method on the Spooler service by using input from a file. The file, Input.xml, contains the following content:

        <p:StopService_INPUT xmlns:p=”http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Service”/>

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -OptionSet <hashtable>
        Passes a set of switches to a service to modify or refine the nature of the request. These are similar to switches used in command-line shells because they are service specific. Any number of options can be specified.

        The following example demonstrates the syntax that passes the values 1, 2, and 3 for the a, b, and c parameters:

             -OptionSet @{a=1;b=2;c=3}

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     true (ByValue, ByPropertyName)
        Accept wildcard characters? false

    -Port <int>
        Specifies the port to use when the client connects to the WinRM service. When the transport is HTTP, the default port is 80. When the transport is HTTPS, the default port is 443. When you use HTTPS as the transport, the value of the ComputerName parameter must match the server’s Certificate common name (CN). However, if the SkipCNCheck parameter is specified as part of the SessionOption parameter, then the Certificate common name of the server does not have to match the host name of the server. The SkipCNCheck parameter should be used only for trusted machines.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -ResourceURI <Uri>
        Contains the Uniform Resource Identifier (URI) of the resource class or instance. The URI is used to identify a specific type of resource, such as disks or processes, on a computer.

        A URI consists of a prefix and a path to a resource. For example:

             http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_LogicalDisk
             http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_NumericSensor

        Required?                    true
        Position?                    1
        Default value
        Accept pipeline input?     true (ByValue, ByPropertyName)
        Accept wildcard characters? false

    -SelectorSet <hashtable>
        Specifies a set of value pairs that are used to select particular management resource instances. The SelectorSet parameter is used when more than one instance of the resource exists. The value of the SelectorSet parameter must be a hash table.

        The following example shows how to enter a value for this parameter:

            -SelectorSet @{Name=”WinRM”;ID=”yyy”}

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -SessionOption <hashtable>
        Defines a set of extended options for the WS-Management session. Enter a SessionOption object that you create by using the New-WSManSessionOption cmdlet. For more information about the options that are available, see New-WSManSessionOption.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -UseSSL [<SwitchParameter>]
        Specifies that the Secure Sockets Layer (SSL) protocol should be used to establish a connection to the remote computer. By default, SSL is not used.

        WS-Management encrypts all the Windows PowerShell content that is transmitted over the network. The UseSSL parameter lets you specify the additional protection of HTTPS instead of HTTP. If SSL is not available on the port that is used for the connection and you specify this parameter, the command fails.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -ValueSet <hashtable>
        Specifies a hash table that helps modify a management resource. You specify the management resource by using the ResourceURI parameter and the SelectorSet parameter. The value of the ValueSet parameter must be a hash table.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    <CommonParameters>
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer and OutVariable. For more information, type,
        “Get-Help about_CommonParameters“.

INPUTS
    None
        This cmdlet does not accept any input.

OUTPUTS
    None
        This cmdlet does not generate any output.

NOTES

    ————————– EXAMPLE 1 ————————–

    C:\PS>Invoke-WSManAction -Action startservice -ResourceURI wmicimv2/win32_service -SelectorSet @{name=”spooler”} -Authentication default

    xsi         : http://www.w3.org/2001/XMLSchema-instance
    p         : http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Service
    cim         : http://schemas.dmtf.org/wbem/wscim/1/common
    lang        : en-US
    ReturnValue : 0

    Description
    ———–
    This command calls the StartService method of the Win32_Service WMI class instance that corresponds to the Spooler service.

    The return value indicates whether the action was successful. In this case, a return value of 0 indicates success. A return value of 5 indicates that the service is already started.

    ————————– EXAMPLE 2 ————————–

    C:\PS>Invoke-WSManAction -Action stopservice -ResourceURI wmicimv2/Win32_Service -SelectorSet @{Name=”spooler”} -FilePath:input.xml -Authentication default

    xsi         : http://www.w3.org/2001/XMLSchema-instance
    p         : http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Service
    cim         : http://schemas.dmtf.org/wbem/wscim/1/common
    lang        : en-US
    ReturnValue : 0

    Description
    ———–
    This command calls the StopService method on the Spooler service by using input from a file. The file, Input.xml, contains the following content:

     <p:StopService_INPUT xmlns:p=”http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Service”/>

    The return value indicates whether the action was successful. In this case, a return value of 0 indicates success. A return value of 5 indicates that the service is already started.

    ————————– EXAMPLE 3 ————————–

    C:\PS>Invoke-WSManAction -Action create -ResourceURI wmicimv2/win32_process -ValueSet @{commandline=”notepad.exe”;currentdirectory=”C:\”}

    xsi         : http://www.w3.org/2001/XMLSchema-instance
    p         : http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Process
    cim         : http://schemas.dmtf.org/wbem/wscim/1/common
    lang        : en-US
    ProcessId : 6356
    ReturnValue : 0

    Description
    ———–
    This command calls the Create method of the Win32_Process class. It passes the method two parameter values, Notepad.exe and “C:\”. As a result, a new process is created to run Notepad, and the current directory of the new process is set to “C:\”.

    ————————– EXAMPLE 4 ————————–

    C:\PS>Invoke-WSManAction -Action startservice -ResourceURI wmicimv2/win32_service -SelectorSet @{name=”spooler”} -computername server01 -Authentication default

    xsi         : http://www.w3.org/2001/XMLSchema-instance
    p         : http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Service
    cim         : http://schemas.dmtf.org/wbem/wscim/1/common
    lang        : en-US
    ReturnValue : 0

    Description
    ———–
    This command calls the StartService method of the Win32_Service WMI class instance that corresponds to the Spooler service. Because the ComputerName parameter is specified, the command runs against the remote server01 computer.

    The return value indicates whether the action was successful. In this case, a return value of 0 indicates success. A return value of 5 indicates that the service is already started.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkId=141446
    Connect-WSMan
    Disable-WSManCredSSP
    Disconnect-WSMan
    Enable-WSManCredSSP
    Get-WSManCredSSP
    Get-WSManInstance
    New-WSManInstance
    New-WSManSessionOption
    Remove-WSManInstance
    Set-WSManInstance
    Set-WSManQuickConfig
    Test-WSMan
    Invoke-WmiMethod

Invoke-Command

NAME
    Invoke-Command

SYNOPSIS
    Runs commands on local and remote computers.

SYNTAX
    Invoke-Command [-ScriptBlock] <scriptblock> [[-ComputerName] <string[]>] [-ApplicationName <string>] [-AsJob] [-Authentication {Default | Basic | Negotiate | NegotiateWithImplicitCredential | Credssp | Digest | Kerberos}] [-CertificateThumbprint <string>] [-ConfigurationName <string>] [-Credential <PSCredential>] [-HideComputerName] [-JobName <string>] [-Port <int>] [-SessionOption <PSSessionOption>] [-ThrottleLimit <int>] [-UseSSL] [-ArgumentList <Object[]>] [-InputObject <psobject>] [<CommonParameters>]

    Invoke-Command [-FilePath] <string> [[-ComputerName] <string[]>] [-ApplicationName <string>] [-AsJob] [-Authentication {Default | Basic | Negotiate | NegotiateWithImplicitCredential | Credssp | Digest | Kerberos}] [-ConfigurationName <string>] [-Credential <PSCredential>] [-HideComputerName] [-JobName <string>] [-Port <int>] [-SessionOption <PSSessionOption>] [-ThrottleLimit <int>] [-UseSSL] [-ArgumentList <Object[]>] [-InputObject <psobject>] [<CommonParameters>]

    Invoke-Command [-FilePath] <string> [[-Session] <PSSession[]>] [-AsJob] [-HideComputerName] [-JobName <string>] [-ThrottleLimit <int>] [-ArgumentList <Object[]>] [-InputObject <psobject>] [<CommonParameters>]

    Invoke-Command [-FilePath] <string> [[-ConnectionURI] <Uri[]>] [-AllowRedirection] [-AsJob] [-Authentication {Default | Basic | Negotiate | NegotiateWithImplicitCredential | Credssp | Digest | Kerberos}] [-ConfigurationName <string>] [-Credential <PSCredential>] [-HideComputerName] [-JobName <string>] [-SessionOption <PSSessionOption>] [-ThrottleLimit <int>] [-ArgumentList <Object[]>] [-InputObject <psobject>] [<CommonParameters>]

    Invoke-Command [-ScriptBlock] <scriptblock> [-ArgumentList <Object[]>] [-InputObject <psobject>] [<CommonParameters>]

    Invoke-Command [-ScriptBlock] <scriptblock> [[-Session] <PSSession[]>] [-AsJob] [-HideComputerName] [-JobName <string>] [-ThrottleLimit <int>] [-ArgumentList <Object[]>] [-InputObject <psobject>] [<CommonParameters>]

    Invoke-Command [-ScriptBlock] <scriptblock> [[-ConnectionURI] <Uri[]>] [-AllowRedirection] [-AsJob] [-Authentication {Default | Basic | Negotiate | NegotiateWithImplicitCredential | Credssp | Digest | Kerberos}] [-CertificateThumbprint <string>] [-ConfigurationName <string>] [-Credential <PSCredential>] [-HideComputerName] [-JobName <string>] [-SessionOption <PSSessionOption>] [-ThrottleLimit <int>] [-ArgumentList <Object[]>] [-InputObject <psobject>] [<CommonParameters>]

DESCRIPTION
    The Invoke-Command cmdlet runs commands on a local or remote computer and returns all output from the commands, including errors. With a single Invoke-Command command, you can run commands on multiple computers.

    To run a single command on a remote computer, use the ComputerName parameter. To run a series of related commands that share data, create a PSSession (a persistent connection) on the remote computer, and then use the Session parameter of Invoke-Command to run the command in the PSSession.

    You can also use Invoke-Command on a local computer to evaluate or run a string in a script block as a command. Windows PowerShell converts the script block to a command and runs the command immediately in the current scope, instead of just echoing the string at the command line.

    Before using Invoke-Command to run commands on a remote computer, read about_remote.

PARAMETERS
    -AllowRedirection [<SwitchParameter>]
        Allows redirection of this connection to an alternate URI.

        When you use the ConnectionURI parameter, the remote destination can return an instruction to redirect to a different URI. By default, Windows PowerShell does not redirect connections, but you can use the AllowRedirection parameter to allow it to redirect the connection.

        You can also limit the number of times that the connection is redirected by setting the MaximumConnectionRedirectionCount property of the $PSSessionOption preference Variable, or the MaximumConnectionRedirectionCount property of the value of the SessionOption parameter. The default value is 5. For more information, see the description of the SessionOption parameter and the help topic for the New-PSSessionOption cmdlet.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -ApplicationName <string>
        Specifies the application name segment of the connection URI. Use this parameter to specify the application name when you are not using the ConnectionURI parameter in the command.

        The default value is the value of the $PSSessionApplicationName preference Variable on the local computer. If this preference Variable is not defined, the default value is WSMan. This value is appropriate for most uses. For more information, see about_preference_variables.

        The WinRM service uses the application name to select a listener to service the connection request. The value of this parameter should match the value of the URLPrefix property of a listener on the remote computer.

        Required?                    false
        Position?                    named
        Default value                WSMan
        Accept pipeline input?     true (ByPropertyName)
        Accept wildcard characters? false

    -ArgumentList <Object[]>
        Supplies the values of local Variables in the command. The Variables in the command are replaced by these values before the command is run on the remote computer. Enter the values in a comma-separated list. Values are associated with Variables in the order that they are listed. The Alias for ArgumentList is “Args”.

        The values in ArgumentList can be actual values, such as “1024”, or they can be references to local Variables, such as “$max”.

        To use local Variables in a command, use the following command format:
        {param($<name1>[, $<name2>]…) <command-with-local-variables>} -ArgumentList <value | $local-variable>

        The “param” keyword lists the local Variables that are used in the command. The ArgumentList parameter supplies the values of the Variables, in the order that they are listed.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -AsJob [<SwitchParameter>]
        Runs the command as a background job on a remote computer. Use this parameter to run commands that take an extensive time to complete.

        When you use AsJob, the command returns an object that represents the job, and then displays the command prompt. You can continue to work in the session while the job completes. To manage the job, use the Job cmdlets. To get the job results, use Receive-Job.

        The AsJob parameter is similar to using Invoke-Command to run a Start-Job command remotely. However, with AsJob, the job is created on the local computer, even though the job runs on a remote computer, and the results of the remote job are automatically returned to the local computer.

        For more information about Windows PowerShell background jobs, see about_jobs and about_remote_Jobs.

        Required?                    false
        Position?                    named
        Default value                None
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Authentication <AuthenticationMechanism>
        Specifies the mechanism that is used to authenticate the user’s credentials. Valid values are Default, Basic, Credssp, Digest, Kerberos, Negotiate, and NegotiateWithImplicitCredential. The default value is Default.

        CredSSP authentication is available only in Windows Vista, Windows Server 2008, and later versions of Windows.

        For information about the values of this parameter, see the description of the System.Management.Automation.Runspaces.AuthenticationMechanism enumeration in MSDN.

        CAUTION: Credential Security Service Provider (CredSSP) authentication, in which the user’s credentials are passed to a remote computer to be authenticated, is designed for commands that require authentication on more than one resource, such as accessing a remote network share. This mechanism increases the security risk of the remote operation. If the remote computer is compromised, the credentials that are passed to it can be used to control the network session.

        Required?                    false
        Position?                    named
        Default value                Default
        Accept pipeline input?     false
        Accept wildcard characters? false

    -CertificateThumbprint <string>
        Specifies the digital public key Certificate (X509) of a user account that has permission to perform this action. Enter the Certificate thumbprint of the Certificate.

        Certificates are used in client Certificate-based authentication. They can only be mapped to local user accounts; they do not work with domain accounts.

        To get a Certificate thumbprint, use the Get-Item or Get-ChildItem commands in the Windows PowerShell Cert: drive.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -ComputerName <string[]>
        Specifies the computers on which the command runs. The default is the local computer.

        When you use the ComputerName parameter, Windows PowerShell creates a temporary connection that is used only to run the specified command and is then closed. If you need a persistent connection, use the Session parameter.

        Type the NETBIOS name, IP address, or fully-qualified domain name of one or more computers in a comma-separated list. To specify the local computer, type the computer name, “localhost”, or a dot (.).

        To use an IP address in the value of the ComputerName parameter, the command must include the Credential parameter. Also, the computer must be configured for HTTPS transport or the IP address of the remote computer must be included in the WinRM TrustedHosts list on the local computer. For instructions for adding a computer name to the TrustedHosts list, see “How to Add a Computer to the Trusted Host List” in about_remote_TroubleShooting.

        Note: On Windows Vista, and later versions of Windows, to include the local computer in the value of the ComputerName parameter, you must open Windows PowerShell with the “Run as administrator” option.

        Required?                    false
        Position?                    1
        Default value
        Accept pipeline input?     true (ByPropertyName)
        Accept wildcard characters? false

    -ConfigurationName <string>
        Specifies the session configuration that is used for the new PSSession.

        Enter a configuration name or the fully qualified resource URI for a session configuration. If you specify only the configuration name, the following schema URI is prepended: http://schemas.microsoft.com/powershell.

        The session configuration for a session is located on the remote computer. If the specified session configuration does not exist on the remote computer, the command fails.

        The default value is the value of the $PSSessionConfigurationName preference Variable on the local computer. If this preference Variable is not set, the default is Microsoft.PowerShell. For more information, see about_preference_variables.

        Required?                    false
        Position?                    named
        Default value                http://Schemas.Microsoft.com/PowerShell/Microsoft.PowerShell
        Accept pipeline input?     true (ByPropertyName)
        Accept wildcard characters? false

    -ConnectionURI <Uri[]>
        Specifies a Uniform Resource Identifier (URI) that defines the connection endpoint. The URI must be fully qualified.

        The format of this string is:
            <Transport>://<ComputerName>:<Port>/<ApplicationName>

        The default value is:
            http://localhost:80/WSMAN

        Valid values for the Transport segment of the URI are HTTP and HTTPS. If you do not specify a ConnectionURI, you can use the UseSSL, ComputerName, Port, and ApplicationName parameters to specify the URI values.

        If the destination computer redirects the connection to a different URI, Windows PowerShell prevents the redirection unless you use the AllowRedirection parameter in the command.

        Required?                    false
        Position?                    1
        Default value                http://localhost:80/wsman
        Accept pipeline input?     true (ByPropertyName)
        Accept wildcard characters? false

    -Credential <PSCredential>
        Specifies a user account that has permission to perform this action. The default is the current user.

        Type a user name, such as “User01” or “Domain01\User01”, or enter a Variable that contains a PSCredential object, such as one generated by the Get-Credential cmdlet. When you type a user name, you will be prompted for a password.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     true (ByPropertyName)
        Accept wildcard characters? false

    -FilePath <string>
        Runs the specified local script on one or more remote computers. Enter the path and file name of the script, or pipe a script path to Invoke-Command. The script must reside on the local computer or in a directory that the local computer can access. Use the ArgumentList parameter to specify the values of parameters in the script.

        When you use this parameter, Windows PowerShell converts the contents of the specified script file to a script block, transmits the script block to the remote computer, and runs it on the remote computer.

        Required?                    true
        Position?                    2
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -HideComputerName [<SwitchParameter>]
        Omits the computer name of each object from the output display. By default, the name of the computer that generated the object appears in the display.

        This parameter affects only the output display. It does not change the object.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -InputObject <psobject>
        Specifies input to the command. Enter a Variable that contains the objects or type a command or expression that gets the objects.

        When using InputObject, use the $input automatic Variable in the value of the ScriptBlock parameter to represent the input objects.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     true (ByValue)
        Accept wildcard characters? false

    -JobName <string>
        Specifies a friendly name for the background job. By default, jobs are named “Job<n>”, where <n> is an ordinal number. This parameter is valid only with the AsJob parameter.

        If you use the JobName parameter in a command, the command is run as a job, and Invoke-Command returns a job object, even if you do not include the AsJob parameter in the command.

        For more information about Windows PowerShell background jobs, see about_jobs.

        Required?                    false
        Position?                    named
        Default value                Job<n>
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Port <int>
        Specifies the network port on the remote computer used for this command. The default is port 80 (the HTTP port).

        Before using an alternate port, you must configure the WinRM listener on the remote computer to listen at that port. To configure the listener, type the following two commands at the Windows PowerShell prompt:

        Remove-Item -path WSMan:\Localhost\listener\listener* -recurse
        New-Item -path WSMan:\Localhost\listener -Transport http -Address * -port <port-number>

        Do not use the Port parameter unless you must. The Port set in the command applies to all computers or sessions on which the command runs. An alternate port setting might prevent the command from running on all computers.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -ScriptBlock <scriptblock>
        Specifies the commands to run. Enclose the commands in curly braces ( { } ) to create a script block. This parameter is required.

        By default, any Variables in the command are evaluated on the remote computer. To include local Variables in the command, use the ArgumentList parameter.

        Required?                    true
        Position?                    1
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Session <PSSession[]>
        Runs the command in the specified Windows PowerShell sessions (PSSessions). Enter a Variable that contains the PSSessions or a command that creates or gets the PSSessions, such as a New-PSSession or Get-PSSession command.

        When you create a PSSession, Windows PowerShell establishes a persistent connection to the remote computer. Use a PSSession to run a series of related commands that share data. To run a single command or a series of unrelated commands, use the ComputerName parameter.

        To create a PSSession, use the New-PSSession cmdlet. For more information, see about_pssessions.

        Required?                    false
        Position?                    1
        Default value
        Accept pipeline input?     true (ByPropertyName)
        Accept wildcard characters? false

    -SessionOption <PSSessionOption>
        Sets advanced options for the session. Enter a SessionOption object that you create by using the New-PSSessionOption cmdlet.

        The default values for the options are determined by the value of the $PSSessionOption preference Variable, if it is set. Otherwise, the session uses the system defaults.

        For a description of the session options, including the default values, see the help topic for the New-PSSessionOption cmdlet. For information about the $PSSessionOption preference Variable, see about_preference_variables.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -ThrottleLimit <int>
        Specifies the maximum number of concurrent connections that can be established to run this command. If you omit this parameter or enter a value of 0, the default value, 32, is used.

        The throttle limit applies only to the current command, not to the session or to the computer.

        Required?                    false
        Position?                    named
        Default value                32
        Accept pipeline input?     false
        Accept wildcard characters? false

    -UseSSL [<SwitchParameter>]
        Uses the Secure Sockets Layer (SSL) protocol to establish a connection to the remote computer. By default, SSL is not used.

        WS-Management encrypts all Windows PowerShell content transmitted over the network. UseSSL is an additional protection that sends the data across an HTTPS, instead of HTTP.

        If you use this parameter, but SSL is not available on the port used for the command, the command fails.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    <CommonParameters>
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer and OutVariable. For more information, type,
        “Get-Help about_CommonParameters“.

INPUTS
    System.Management.Automation.ScriptBlock
        You can pipe a command in a script block to Invoke-Command. Use the $input automatic Variable to represent the input objects in the command.

OUTPUTS
    System.Management.Automation.PSRemotingJob or the output of the invoked command
        When you use the AsJob parameter, Invoke-Command returns a job object. Otherwise, it returns the output of the invoked command (the value of the ScriptBlock parameter).

NOTES

        — On Windows Vista, and later versions of Windows, to use the ComputerName parameter of Invoke-Command to run a command on the local computer, you must open Windows PowerShell with the “Run as administrator” option.

        — When you run commands on multiple computers, Windows PowerShell connects to the computers in the order in which they appear in the list. However, the command output is displayed in the order that it is received from the remote computers, which might be different.

        — Errors that result from the command that Invoke-Command runs are included in the command results. Errors that would be terminating errors in a local command are treated as non-terminating errors in a remote command. This strategy ensures that terminating errors on one computer do not terminate the command on all computers on which it is run. This practice is used even when a remote command is run on a single computer.

        — If the remote computer is not in a domain that the local computer trusts, the computer might not be able to authenticate the user’s credentials. To add the remote computer to the list of “trusted hosts” in WS-Management, use the following command in the WSMan provider, where <Remote-Computer-Name> is the name of the remote computer:
        Set-Item -path WSMan:\Localhost\Client\TrustedHosts -value <Remote-Computer-Name>.

    ————————– EXAMPLE 1 ————————–

    C:\PS>Invoke-Command -filepath c:\scripts\test.ps1 -computerName Server01

    Disks: C:, D:, E:
    Status: Warning, Normal, Normal

    Description
    ———–
    This command runs the Test.ps1 script on the Server01 computer.

    The command uses the FilePath parameter to specify a script that is located on the local computer. The script runs on the remote computer and the results are returned to the local computer.

    ————————– EXAMPLE 2 ————————–

    C:\PS>Invoke-Command -computername server01 -credential domain01\user01 -ScriptBlock {Get-Culture}

    Description
    ———–
    This command runs a Get-Culture command on the Server01 remote computer.

    It uses the ComputerName parameter to specify the computer name and the Credential parameter to run the command in the security context of “Domain01\User01,” a user with permission to run commands. It uses the ScriptBlock parameter to specify the command to be run on the remote computer.

    In response, Windows PowerShell displays a dialog box that requests the password and an authentication method for the User01 account. It then runs the command on the Server01 computer and returns the result.

    ————————– EXAMPLE 3 ————————–

    C:\PS>$s = New-PSSession -computername server02 -credential domain01\user01

    C:\PS> Invoke-Command -session $s -ScriptBlock {Get-Culture}

    Description
    ———–
    This example runs the same “Get-Culture” command in a session (a persistent connection) on the Server02 remote computer. Typically, you create a session only when you are running a series of commands on the remote computer.

    The first command uses the New-PSSession cmdlet to create a session on the Server02 remote computer. Then, it saves the session in the $s Variable.

    The second command uses the Invoke-Command cmdlet to run the Get-Culture command on Server02. It uses the Session parameter to specify the session saved in the $s Variable.

    In response, Windows PowerShell runs the command in the session on the Server02 computer.

    ————————– EXAMPLE 4 ————————–

    C:\PS>Invoke-Command -computername Server02 -ScriptBlock {$p = Get-Process powershell}

    C:\PS> Invoke-Command -computername Server02 -ScriptBlock {$p.virtualmemorysize}
    C:\PS>

    C:\PS> $s = New-PSSession -computername Server02
    C:\PS> Invoke-Command -session $s -ScriptBlock {$p = Get-Process powershell}
    C:\PS> Invoke-Command -session $s -ScriptBlock {$p.virtualmemorysize}
    17930240

    Description
    ———–
    This example compares the effects of using ComputerName and Session parameters of Invoke-Command. It shows how to use a session to run a series of commands that share the same data.

    The first two commands use the ComputerName parameter of Invoke-Command to run commands on the Server02 remote computer. The first command uses the Get-Process command to get the PowerShell process on the remote computer and to save it in the $p Variable. The second command gets the value of the VirtualMemorySize property of the PowerShell process.

    The first command succeeds. But, the second command fails because when you use the ComputerName parameter, Windows PowerShell creates a connection just to run the command. Then, it closes the connection when the command is complete. The $p Variable was created in one connection, but it does not exist in the connection created for the second command.

    The problem is solved by creating a session (a persistent connection) on the remote computer and by running both of the related commands in the same session.

    The third command uses the New-PSSession cmdlet to create a session on the Server02 computer. Then it saves the session in the $s Variable. The fourth and fifth commands repeat the series of commands used in the first set, but in this case, the Invoke-Command command uses the Session parameter to run both of the commands in the same session.

    In this case, because both commands run in the same session, the commands succeed, and the $p value remains active in the $s session for later use.

    ————————– EXAMPLE 5 ————————–

    C:\PS>$command = { Get-Eventlog -log “windows powershell” | where {$_.message -like “*certificate*”} }

    C:\PS> Invoke-Command -computername S1, S2 -ScriptBlock $command

    Description
    ———–
    This example shows how to enter a command that is saved in a local Variable.

    When the entire command is saved in a local Variable, you can specify the Variable as the value of the ScriptBlock parameter. You do not have to use the “param” keyword or the ArgumentList Variable to submit the value of the local Variable.

    The first command saves a Get-Eventlog command in the $command Variable. The command is formatted as a script block.

    The second command uses the Invoke-Command cmdlet to run the command in $command on the S1 and S2 remote computers.

    ————————– EXAMPLE 6 ————————–

    C:\PS>Invoke-Command -computername server01, server02, TST-0143, localhost -configurationname MySession.PowerShell -ScriptBlock {Get-Eventlog “windows powershell”}

    Description
    ———–
    This example demonstrates how to use the Invoke-Command cmdlet to run a single command on multiple computers.

    The command uses the ComputerName parameter to specify the computers. The computer names are presented in a comma-separated list. The list of computers includes the “localhost” value, which represents the local computer.

    The command uses the ConfigurationName parameter to specify an alternate session configuration for Windows PowerShell and the ScriptBlock parameter to specify the command.

    In this example, the command in the script block gets the events in the Windows PowerShell event log on each remote computer.

    ————————– EXAMPLE 7 ————————–

    C:\PS>$version = Invoke-Command -computername (Get-Content machines.txt) -ScriptBlock {(Get-Host).version}

    Description
    ———–
    This command gets the version of the Windows PowerShell host running on 200 remote computers.

    Because only one command is run, it is not necessary to create persistent connections (sessions) to each of the computers. Instead, the command uses the ComputerName parameter to indicate the computers.

    The command uses the Invoke-Command cmdlet to run a Get-Host command. It uses dot notation to get the Version property of the Windows PowerShell host.

    To specify the computers, it uses the Get-Content cmdlet to get the contents of the Machine.txt file, a file of computer names.

    These commands run synchronously (one at a time). When the commands complete, the output of the commands from all of the computers is saved in the $version Variable. The output includes the name of the computer from which the data originated.

    ————————– EXAMPLE 8 ————————–

    C:\PS>$s = New-PSSession -computername Server01, Server02

    C:\PS> Invoke-Command -session $s -ScriptBlock {Get-Eventlog system} -AsJob

    Id Name    State     HasMoreData Location         Command
    — —-    —–     —–         ———–        ——–             ——-
    1    Job1    Running    True         Server01,Server02 Get-Eventlog system

    C:\PS> $j = Get-Job

    C:\PS> $j | Format-List -property *

    HasMoreData : True
    StatusMessage :
    Location     : Server01,Server02
    Command     : Get-Eventlog system
    JobStateInfo : Running
    Finished     : System.Threading.ManualResetEvent
    InstanceId    : e124bb59-8cb2-498b-a0d2-2e07d4e030ca
    Id            : 1
    Name         : Job1
    ChildJobs     : {Job2, Job3}
    Output        : {}
    Error         : {}
    Progress     : {}
    Verbose     : {}
    Debug         : {}
    Warning     : {}
    StateChanged :

    C:\PS> $results = $j | Receive-Job

    Description
    ———–
    These commands run a background job on two remote computers. Because the Invoke-Command command uses the AsJob parameter, the commands run on the remote computers, but the job actually resides on the local computer and the results are transmitted to the local computer.

    The first command uses the New-PSSession cmdlet to create sessions on the Server01 and Server02 remote computers.

    The second command uses the Invoke-Command cmdlet to run a background job in each of the sessions. The command uses the AsJob parameter to run the command as a background job. This command returns a job object that contains two child job objects, one for each of the jobs run on the two remote computers.

    The third command uses a Get-Job command to save the job object in the $j Variable.

    The fourth command uses a pipeline operator (|) to send the value of the $j Variable to the Format-List cmdlet, which displays all properties of the job object in a list.

    The fifth command gets the results of the jobs. It pipes the job object in $j to the Receive-Job cmdlet and stores the results in the $results Variable.

    ————————– EXAMPLE 9 ————————–

    C:\PS>$MWFO-LOg = Microsoft-Windows-Forwarding/Operational

    C:\PS> Invoke-Command -computername server01 -ScriptBlock {param($log, $num) Get-Eventlog -logname $log -newest $num} -ArgumentList $MWFO-log, 10

    Description
    ———–
    This example shows how to include the values of local Variables in a command run on a remote computer.

    The first command saves the name of the Microsoft-Windows-Forwarding/Operational event log in the $MWFO-Log Variable.

    The second command uses the Invoke-Command cmdlet to run a Get-EventLog command on the Server01 remote computer that gets the 10 newest events from the Microsoft-Windows-Forwarding/Operational event log on Server01.

    This command uses the “param” keyword to create two Variables, $log and $num, that are used as placeholders in the Get-EventLog command. These placeholders have arbitrary names that do not need to match the names of the local Variables that supply their values.

    The values of the ArgumentList parameter demonstrate the two different ways to specify values in the argument list. The value of the $log placeholder is the $MFWO-Log Variable, which is defined in the first command. The value of the $num Variable is 10.

    Before the command is sent to the remote computer, the Variables are replaced with the specified values.

    ————————– EXAMPLE 10 ————————–

    C:\PS>Invoke-Command -computername S1, S2 -ScriptBlock {Get-Process powershell}

    PSComputerName    Handles NPM(K)    PM(K)     WS(K) VM(M) CPU(s)     Id ProcessName
    ————–    ——- ——    —–     —– —– ——     — ———–
    S1                575     15        45100     40988 200     4.68     1392 powershell
    S2                777     14        35100     30988 150     3.68     67 powershell

    C:\PS> Invoke-Command -computername S1, S2 -ScriptBlock {Get-Process powershell} -HideComputerName

    Handles NPM(K)    PM(K)     WS(K) VM(M) CPU(s)     Id ProcessName
    ——- ——    —–     —– —– ——     — ———–
    575     15        45100     40988 200     4.68     1392 powershell
    777     14        35100     30988 150     3.68     67 powershell

    Description
    ———–
    This example shows the effect of using the HideComputerName parameter of Invoke-Command.

    The first two commands use the Invoke-Command cmdlet to run a Get-Process command for the PowerShell process. The output of the first command includes the PsComputerName property, which contains the name of the computer on which the command ran. The output of the second command, which uses the HideComputerName parameter, does not include the PsComputerName column.

    Using the HideComputerName parameter does not change the object. You can still use the Format cmdlets to display the PsComputerName property of any of the affected objects.

    ————————– EXAMPLE 11 ————————–

    C:\PS>Invoke-Command -comp (Get-Content servers.txt) -filepath c:\scripts\sample.ps1 -ArgumentList Process, Service

    Description
    ———–
    This example uses the Invoke-Command cmdlet to run the Sample.ps1 script on all of the computers listed in the Servers.txt file. The command uses the FilePath parameter to specify the script file. This command allows you to run the script on the remote computers, even if the script file is not accessible to the remote computers.

    When you submit the command, the content of the Sample.ps1 file is copied into a script block and the script block is run on each of the remote computers. This procedure is equivalent to using the ScriptBlock parameter to submit the contents of the script.

    ————————– EXAMPLE 12 ————————–

    C:\PS>$LiveCred = Get-Credential

    C:\PS> Invoke-Command -ConfigurationName Microsoft.Exchange `
             -ConnectionUri https://ps.exchangelabs.com/powershell `
             -Credential $LiveCred -Authentication Basic `
             -ScriptBlock {Invoke-Command {Set-Mailbox dan -DisplayName “Dan Park”}

    Description
    ———–
    This example shows how to run a command on a remote computer that is identified by a URI (Internet address). This particular example runs a Set-Mailbox command on a remote Exchange server. The backtick (`) in the command is the Windows PowerShell continuation character.

    The first command uses the Get-Credential cmdlet to store Windows Live ID credentials in the $LiveCred variab the credentials dialog box appears, enter Windows Live ID credentials.

    The second command uses the Invoke-Command cmdlet to run a Set-Mailbox command. The command uses the ConfigurationName parameter to specify that the command should run in a session that uses the Microsoft.Exchange session configuration. The ConnectionURI parameter specifies the URL of the Exchange server endpoint.

    The credential parameter specifies tle. Whenhe Windows Live credentials stored in the $LiveCred Variable. The AuthenticationMechanism parameter specifies the use of basic authentication. The ScriptBlock parameter specifies a script block that contains the command.

    ————————– EXAMPLE 13 ————————–

    C:\PS>$max = New-PSSessionOption -MaximumRedirection 1

    C:\PS> Invoke-Command -ConnectionUri https://ps.exchangelabs.com/powershell `
             -ScriptBlock {Invoke-Command {Get-Mailbox dan} `
             -AllowRedirection -SessionOption $max

    Description
    ———–
    This command shows how to use the AllowRedirection and SessionOption parameters to manage URI redirection in a remote command.

    The first command uses the New-PSSessionOption cmdlet to create a PSSessionOpption object that it saves in the $max Variable. The command uses the MaximumRedirection parameter to set the MaximumConnectionRedirectionCount property of the PSSessionOption object to 1.

    The second command uses the Invoke-Command cmdlet to run a Get-Mailbox command on a remote server running Microsoft Exchange Server. The command uses the AllowRedirection parameter to provide explicit permission to redirect the connection to an alternate endpoint. It also uses the SessionOption parameter to specify the session object in the $max Variable.

    As a result, if the remote computer specified by the ConnectionURI parameter returns a redirection message, Windows PowerShell will redirect the connection, but if the new destination returns another redirection message, the redirection count value of 1 is exceeded, and Invoke-Command returns a non-terminating error.

    ————————– EXAMPLE 14 ————————–

    C:\PS>$so = New-PSSessionOption -SkipCACheck

    PS C:\> Invoke-Command $s { Get-HotFix } -SessionOption $so -credential server01\user01

    Description
    ———–
    This example shows how to create and use a SessionOption parameter.

    The first command uses the New-PSSessionOption cmdlet to create a session option. It saves the resulting SessionOption object in the $so parameter.

    The second command uses the Invoke-Command cmdlet to run a Get-HotFix command remotely. The value of the SessionOption parameter is the SessionOption object in the $so Variable.

    ————————– EXAMPLE 15 ————————–

    C:\PS>Enable-WSManCredSSP -delegate server02

    C:\PS> Connect-WSMan Server02

    C:\PS> Set-Item WSMan:\server02*\service\auth\credSSP -value $true

    C:\PS> $s = New-PSSession server02

    C:\PS> Invoke-Command -session $s -script {Get-Item \\Net03\Scripts\LogFiles.ps1} -authentication credssp -credential domain01\admin01

    Description
    ———–
    This example shows how to access a network share from within a remote session.

    The command requires that CredSSP delegation be enabled in the client settings on the local computer and in the service settings on the remote computer. To run the commands in this example, you must be a member of the Administrators group on the local computer and the remote computer.

    The first command uses the Enable-WSManCredSSP cmdlet to enable CredSSP delegation from the Server01 local computer to the Server02 remote computer. This configures the CredSSP client setting on the local computer.

    The second command uses the Connect-WSMan cmdlet to connect to the Server02 computer. This action adds a node for the Server02 computer to the WSMan: drive on the local computer, allowing you to view and change the WS-Management settings on the Server02 computer.

    The third command uses the Set-Item cmdlet to change the value of the CredSSP item in the Service node of the Server02 computer to True. This action enables CredSSP in the service settings on the remote computer.

    The fourth command uses the New-PSSession cmdlet to create a PSSession on the Server02 computer. It saves the PSSession in the $s Variable.

    The fifth command uses the Invoke-Command cmdlet to run a Get-Item command in the session in $s that gets a script from the Net03\Scripts network share. The command uses the Credential parameter and it uses the Authentication parameter with a value of CredSSP.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=135225
    about_remote
    about_pssessions
    New-PSSession
    Get-PSSession
    Remove-PSSession
    Enter-PSSession
    Exit-PSSession
    WS-Management Provider

Invoke-Expression

NAME
    Invoke-Expression

SYNOPSIS
    Runs commands or expressions on the local computer.

SYNTAX
    Invoke-Expression [-Command] <string> [<CommonParameters>]

DESCRIPTION
    The Invoke-Expression cmdlet evaluates or runs a specified string as a command and returns the results of the expression or command. Without Invoke-Expression, a string submitted at the command line would be returned (echoed) unchanged.

PARAMETERS
    -Command <string>
        Specifies the command or expression to run. Type the command or expression or enter a Variable that contains the command or expression. The Command parameter is required.

        Required?                    true
        Position?                    1
        Default value
        Accept pipeline input?     true (ByValue)
        Accept wildcard characters? false

    <CommonParameters>
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer and OutVariable. For more information, type,
        “Get-Help about_CommonParameters“.

INPUTS
    System.String or PSObject
        You can pipe an object that represents the command to Invoke-Expression. Use the $input automatic Variable to represent the input objects in the command.

OUTPUTS
    PSObject
        Returns the output that is generated by the invoked command (the value of the Command parameter).

NOTES

        — An expression is a statement that can be evaluated and produces a result, such as a Windows PowerShell command.

        — Take reasonable precautions when using the Invoke-Expression cmdlet in scripts. When using Invoke-Expression to run a command that the user enters, verify that the command is safe to run before running it. In general, it is best to design your script with predefined input options, rather than allowing freeform input.

    ————————– EXAMPLE 1 ————————–

    C:\PS>$command = “Get-Process

    C:\PS> $command
    Get-Process

    C:\PS> Invoke-Expression $command

    Handles NPM(K)    PM(K)     WS(K) VM(M) CPU(s)     Id ProcessName
    ——- ——    —–     —– —– ——     — ———–
        296     4     1572     1956    20     0.53 1348 AdtAgent
        270     6     1328        800    34     0.06 2396 alg
         67     2     620        484    20     0.22    716 ati2evxx
     1060     15    12904     11840    74    11.48    892 CcmExec
     1400     33    25280     37544 223    38.44 2564 communicator
    …

    Description
    ———–
    This example demonstrates the use of Invoke-Expression to evaluate an expression. Without Invoke-Expression, the expression is printed, but not evaluated.

    The first command assigns a value of “Get-Process” (a string) to the $command Variable.

    The second command shows the effect of typing the Variable name at the command line. Windows PowerShell echoes the string.

    The third command uses Invoke-Expression to evaluate the string.

    ————————– EXAMPLE 2 ————————–

    C:\PS>Invoke-Expression -Command “C:\ps-test\testscript.ps1”

    C:\PS> “C:\ps-test\testscript.ps1” | Invoke-Expression

    Description
    ———–
    These commands use Invoke-Expression to run a script, TestScript.ps1, on the local computer. The two commands are equivalent. The first uses the Command parameter to specify the command to run. The second uses a pipeline operator (|) to send the command string to Invoke-Expression.

    ————————– EXAMPLE 3 ————————–

    C:\PS>$cmd = ‘Get-Process | where {$_.cpu -gt 1000}’

    C:\PS> iex $command

    Description
    ———–
    This example runs a command string that is saved in the $cmd Variable.

    The command string is enclosed in single quotation marks because it includes a Variable, $_, which represents the current object. If it were enclosed in double quotation marks, the $_ Variable would be replaced by its value before it was saved in the $command string.

    ————————– EXAMPLE 4 ————————–

    C:\PS>$cmdlet_name = “Get-Eventlog”

    C:\PS> $example_number = 1

    C:\PS> $example_code = (Get-Help $cmdlet_name).examples.example[($example_number-1)].code

    C:\PS> Invoke-Expression $example_code

    Description
    ———–
    This command retrieves and runs the first example in the Get-EventLog cmdlet help topic.

    To run an example of a different cmdlet, change the value of the $cmdlet_name Variable to the name of the cmdlet. And, change the $example_number Variable to the example number you want to run. The command will fail if the example number is not valid.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=113343
    Invoke-Command

Invoke-History

NAME
    Invoke-History

SYNOPSIS
    Runs commands from the session history.

SYNTAX
    Invoke-History [[-Id] <string>] [-Confirm] [-WhatIf] [<CommonParameters>]

DESCRIPTION
    The Invoke-History cmdlet runs commands from the session history. You can pass objects representing the commands from Get-History to Invoke-History, or you can identify commands in the current history by using their ID number. To find the identification number of a command, use Get-History.

PARAMETERS
    -Id <string>
        Identifies a command in the history. You can type the ID number of the command or the first few characters of the command.

        If you type characters, Invoke-History matches the most recent commands first. If you omit this parameter, Invoke-History runs the last (most recent) command. The parameter name (“id”) is optional. To find the ID number of a command, use Get-History.

        Required?                    false
        Position?                    1
        Default value
        Accept pipeline input?     true (ByPropertyName)
        Accept wildcard characters? false

    -Confirm [<SwitchParameter>]
        Prompts you for confirmation before executing the command.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -WhatIf [<SwitchParameter>]
        Describes what would happen if you executed the command without actually executing the command.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    <CommonParameters>
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer and OutVariable. For more information, type,
        “Get-Help about_CommonParameters“.

INPUTS
    None
        You cannot pipe input to this cmdlet.

OUTPUTS
    None
        Invoke-History does not generate any output, but output might be generated by the commands that Invoke-History runs.

NOTES

        The session history is a list of the commands entered during the session along with the ID. The session history represents the order of execution, the status, and the start and end times of the command. As you enter each command, Windows PowerShell adds it to the history so that you can reuse it. For more information about the session history, see about_History.

        You can also refer to Invoke-History by its built-in Aliases, “r” and “ihy”. For more information, see about_aliases.

    ————————– EXAMPLE 1 ————————–

    C:\PS>Invoke-History

    Description
    ———–
    This command runs the last (most recent) command in the session history. You can abbreviate this command as “r” (think “repeat” or “rerun”), the Alias for Invoke-History.

    ————————– EXAMPLE 2 ————————–

    C:\PS>Invoke-History -Id 132

    Description
    ———–
    This command runs the command in the session history with ID 132. Because the name of the Id parameter is optional, you can abbreviate this command as “Invoke-History 132″, “ihy 132”, or “r 132”.

    ————————– EXAMPLE 3 ————————–

    C:\PS>Invoke-History get-pr

    Description
    ———–
    This command runs the most recent Get-Process command in the session history. When you type characters for the Id parameter, Invoke-History runs the first command that it finds that matches the pattern, beginning with the most recent commands. This command uses the ID parameter, but it omits the optional parameter name.

    ————————– EXAMPLE 4 ————————–

    C:\PS>Invoke-History (16..24), 27

    Description
    ———–
    This command runs commands 16 through 24 and 27. You can list multiple IDs and ID ranges separated by commas.

    ————————– EXAMPLE 5 ————————–

    C:\PS>Get-History -Id 255 -count 7 | Invoke-History

    Description
    ———–
    This command runs the 7 commands in the history that end with command 255 (typically 249 through 255). It uses the Get-History cmdlet to retrieve the commands. The pipeline operator (|) passes the commands to Invoke-History, which executes them.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=113344
    about_History
    Get-History
    Add-History
    Clear-History

Invoke-Item

NAME
    Invoke-Item

SYNOPSIS
    Performs the default action on the specified item.

SYNTAX
    Invoke-Item [-LiteralPath] <string[]> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Include <string[]>] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

    Invoke-Item [-Path] <string[]> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Include <string[]>] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>]

DESCRIPTION
    The Invoke-Item cmdlet performs the default action on the specified item. For example, it runs an executable file or opens a document file in the application associated with the document file type. The default action depends on the type of item and is determined by the Windows PowerShell provider that provides access to the data.

PARAMETERS
    -Credential <PSCredential>
        Specifies a user account that has permission to perform this action. The default is the current user.

        Type a user name, such as “User01” or “Domain01\User01”, or enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password.

        This parameter is not supported by any providers installed with Windows PowerShell.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     true (ByPropertyName)
        Accept wildcard characters? false

    -Exclude <string[]>
        Omits the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as “*.txt”. Wildcards are permitted.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Filter <string>
        Specifies a filter in the provider’s format or language. The value of this parameter qualifies the Path parameter. The syntax of the filter, including the use of wildcards, depends on the provider. Filters are more efficient than other parameters, because the provider applies them when retrieving the objects rather than having Windows PowerShell filter the objects after they are retrieved.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -Include <string[]>
        Performs the default action only on the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as “*.txt”. Wildcards are permitted.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -LiteralPath <string[]>
        Specifies a path to the item. The value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences.

        Required?                    true
        Position?                    1
        Default value
        Accept pipeline input?     true (ByPropertyName)
        Accept wildcard characters? false

    -Path <string[]>
        Specifies the path to the selected item.

        Required?                    true
        Position?                    1
        Default value
        Accept pipeline input?     true (ByValue, ByPropertyName)
        Accept wildcard characters? false

    -Confirm [<SwitchParameter>]
        Prompts you for confirmation before executing the command.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -WhatIf [<SwitchParameter>]
        Describes what would happen if you executed the command without actually executing the command.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    -UseTransaction [<SwitchParameter>]
        Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_transactions.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?     false
        Accept wildcard characters? false

    <CommonParameters>
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer and OutVariable. For more information, type,
        “Get-Help about_CommonParameters“.

INPUTS
    System.String
        You can pipe a string that contains a path to Invoke-Item.

OUTPUTS
    None
        The command does not generate any output. However, output might be generated by the item that it invokes.

NOTES

        The Invoke-Item cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type “Get-PsSProvider”. For more information, see about_providers.

    ————————– EXAMPLE 1 ————————–

    C:\PS>Invoke-Item C:\Test\aliasApr04.doc

    Description
    ———–
    This command opens the file AliasApr04.doc in Microsoft Office Word. In this case, opening in Word is the default action for .doc files.

    ————————– EXAMPLE 2 ————————–

    C:\PS>Invoke-Item “C:\Documents and Settings\Lister\My Documents\*.xls”

    Description
    ———–
    This command opens all of the Microsoft Office Excel spreadsheets in the C:\Documents and Settings\Lister\My Documents folder. Each spreadsheet is opened in a new instance of Excel. In this case, opening in Excel is the default action for .xls files.

RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=113345
    about_providers
    Clear-Item
    Get-Item
    Move-Item
    Set-Item
    New-Item
    Remove-Item
    Rename-Item
    Copy-Item