InvokeCommandCommand InvokeCommandCommand InvokeCommandCommand Class

Definition

This cmdlet executes a specified script block on one or more remote machines. The expression or command, as they will be interchangeably called, need to be contained in a script block. This is to ensure two things:

  1. The expression that the user has entered is syntactically correct (its compiled)
  2. The scriptblock can be converted to a powershell object before transmitting it to the remote end so that it can be run on constrained runspaces in the no language mode

    In general, the command script block is executed as if the user had typed it at the command line. The output of the command is the output of the cmdlet. However, since invoke-command is a cmdlet, it will unravel its output:

    • if the command outputs an empty array, invoke-command will output $null
    • if the command outputs a single-element array, invoke-command will output that single element.

    Additionally, the command will be run on a remote system.

    This cmdlet can be called in the following different ways:

    Execute a command in a remote machine by specifying the command and machine name invoke-command -Command {get-process} -computername "server1"

    Execute a command in a set of remote machines by specifying the command and the list of machines $servers = 1..10 | ForEach-Object {"Server${_}"} invoke-command -command {get-process} -computername $servers

    Create a new runspace and use it to execute a command on a remote machine $runspace = New-PSSession -computername "Server1" $credential = get-credential "user01" invoke-command -command {get-process} -Session $runspace -credential $credential

    Execute a command in a set of remote machines by specifying the complete uri for the machines $uri = "http://hostedservices.microsoft.com/someservice" invoke-command -command { get-mail } - uri $uri

    Create a collection of runspaces and use it to execute a command on a set of remote machines

    $serveruris = 1..8 | ForEach-Object {"http://Server${_}/"} $runspaces = New-PSSession -URI $serveruris invoke-command -command {get-process} -Session $runspaces

    The cmdlet can also be invoked in the asynchronous mode.

    invoke-command -command {get-process} -computername $servers -asjob

    When the -AsJob switch is used, the cmdlet will emit an PSJob Object. The user can then use the other job cmdlets to work with this object

    Note there are two types of errors:

    1. Remote invocation errors
    2. Local errors.

    Both types of errors will be available when the user invokes a receive operation.

    The PSJob object has its own throttling mechanism. The result object will be stored in a global cache. If a user wants to retrieve data from the result object the user should be able to do so using the Receive-PSJob cmdlet

    The following needs to be noted about exception/error reporting in this cmdlet: The exception objects that are thrown by underlying layers will be written as errors, to avoid stopping the entire cmdlet in case of multi-computername or multi-Session usage (for consistency, this is true even when done using one computername or runspace)

    Only one expression may be executed at a time in any single runspace. Attempts to invoke an expression on a runspace that is already executing an expression shall return an error with ErrorCategory ResourceNotAvailable and notify the user that the runspace is currently busy.

    Some additional notes:

    • invoke-command issues a single scriptblock to the computer or runspace. If a runspace is specified and a command is already running in that runspace, then the second command will fail
    • The files necessary to execute the command (cmdlets, scripts, data files, etc) must be present on the remote system; the cmdlet is not responsible for copying them over
    • The entire input stream is collected and sent to the remote system before execution of the command begins (no input streaming)
    • Input shall be available as $input. Remote Runspaces must reference $input explicitly (input will not automatically be available)
    • Output from the command streams back to the client as it is available
    • Ctrl-C and pause/resume are supported; the client will send a message to the remote powershell instance.
    • By default if no -credential is specified, the host will impersonate the current user on the client when executing the command
    • The standard output of invoke-command is the output of the last element of the remote pipeline, with some extra properties added
    • If -Shell is not specified, then the value of the environment variable DEFAULTREMOTESHELLNAME is used. If this is not set, then "Microsoft.PowerShell" is used.
[System.Management.Automation.Cmdlet("Invoke", "Command", DefaultParameterSetName="InProcess", HelpUri="https://go.microsoft.com/fwlink/?LinkID=135225", RemotingCapability=System.Management.Automation.RemotingCapability.OwnedByCommand)]
public class InvokeCommandCommand : Microsoft.PowerShell.Commands.PSExecutionCmdlet, IDisposable
type InvokeCommandCommand = class
    inherit PSExecutionCmdlet
    interface IDisposable
Public Class InvokeCommandCommand
Inherits PSExecutionCmdlet
Implements IDisposable
Inheritance
Attributes
Implements

Constructors

InvokeCommandCommand() InvokeCommandCommand() InvokeCommandCommand()

Properties

AllowRedirection AllowRedirection AllowRedirection

The AllowRedirection parameter enables the implicit redirection functionality

ApplicationName ApplicationName ApplicationName

This parameters specifies the appname which identifies the connection end point on the remote machine. If this parameter is not specified then the value specified in DEFAULTREMOTEAPPNAME will be used. If thats not specified as well, then "WSMAN" will be used

ArgumentList ArgumentList ArgumentList Inherited from PSExecutionCmdlet
AsJob AsJob AsJob

Specifies if the cmdlet needs to be run asynchronously

Authentication Authentication Authentication

Authentication mechanism to authenticate the user

CertificateThumbprint CertificateThumbprint CertificateThumbprint Inherited from PSRemotingBaseCmdlet
CommandOrigin CommandOrigin CommandOrigin Inherited from InternalCommand
CommandRuntime CommandRuntime CommandRuntime Inherited from Cmdlet
ComputerName ComputerName ComputerName

This parameter represents the address(es) of the remote computer(s). The following formats are supported: (a) Computer name (b) IPv4 address : 132.3.4.5 (c) IPv6 address: 3ffe:8311:ffff:f70f:0:5efe:172.30.162.18

ConfigurationName ConfigurationName ConfigurationName

For WSMan session: If this parameter is not specified then the value specified in the environment variable DEFAULTREMOTESHELLNAME will be used. If this is not set as well, then Microsoft.PowerShell is used.

For VM/Container sessions: If this parameter is not specified then no configuration is used.

ConnectionUri ConnectionUri ConnectionUri

A complete URI(s) specified for the remote computer and shell to connect to and create runspace for

ContainerId ContainerId ContainerId Inherited from PSExecutionCmdlet
Credential Credential Credential

Specifies the credentials of the user to impersonate in the remote machine. If this parameter is not specified then the credentials of the current user process will be assumed.

CurrentPSTransaction CurrentPSTransaction CurrentPSTransaction Inherited from Cmdlet
DisconnectedSessionName DisconnectedSessionName DisconnectedSessionName Inherited from PSExecutionCmdlet
EnableNetworkAccess EnableNetworkAccess EnableNetworkAccess

When set and in loopback scenario (localhost) this enables creation of WSMan host process with the user interactive token, allowing PowerShell script network access, i.e., allows going off box. When this property is true and a PSSession is disconnected, reconnection is allowed only if reconnecting from a PowerShell session on the same box.

Events Events Events Inherited from PSCmdlet
FilePath FilePath FilePath

The script block that the user has specified in the cmdlet. This will be converted to a powershell before its actually sent to the remote end

HideComputerName HideComputerName HideComputerName

Hide/Show computername of the remote objects.

Host Host Host Inherited from PSCmdlet
HostName HostName HostName

Host name for an SSH remote connection

InDisconnectedSession InDisconnectedSession InDisconnectedSession

Specifies that after the command is invoked on a remote computer the remote session should be disconnected.

InputObject InputObject InputObject Inherited from PSExecutionCmdlet
InvokeAndDisconnect InvokeAndDisconnect InvokeAndDisconnect Inherited from PSExecutionCmdlet
InvokeCommand InvokeCommand InvokeCommand Inherited from PSCmdlet
InvokeProvider InvokeProvider InvokeProvider Inherited from PSCmdlet
IsLiteralPath IsLiteralPath IsLiteralPath Inherited from PSExecutionCmdlet
JobManager JobManager JobManager Inherited from PSCmdlet
JobName JobName JobName

Friendly name for the job object if AsJob is used

JobRepository JobRepository JobRepository Inherited from PSCmdlet
KeyFilePath KeyFilePath KeyFilePath

Key Path

MyInvocation MyInvocation MyInvocation Inherited from PSCmdlet
NoNewScope NoNewScope NoNewScope

When executing a scriptblock in the current session, tell the cmdlet not to create a new scope.

PagingParameters PagingParameters PagingParameters Inherited from PSCmdlet
ParameterSetName ParameterSetName ParameterSetName Inherited from PSCmdlet
Port Port Port

Port specifies the alternate port to be used in case the default ports are not used for the transport mechanism (port 80 for http and port 443 for useSSL)

RemoteDebug RemoteDebug RemoteDebug

When selected this parameter causes a debugger Step-Into action for each running remote session.

ResolvedComputerNames ResolvedComputerNames ResolvedComputerNames Inherited from PSRemotingBaseCmdlet
RunAsAdministrator RunAsAdministrator RunAsAdministrator

When set, PowerShell process inside container will be launched with high privileged account. Otherwise (default case), PowerShell process inside container will be launched with low privileged account.

SSHConnection SSHConnection SSHConnection

Hashtable array containing SSH connection parameters for each remote target ComputerName (Alias: HostName) (required) UserName (optional) KeyFilePath (Alias: IdentityFilePath) (optional)

SSHTransport SSHTransport SSHTransport

This parameter specifies that SSH is used to establish the remote connection and act as the remoting transport. By default WinRM is used as the remoting transport. Using the SSH transport requires that SSH is installed and PowerShell remoting is enabled on both client and remote machines.

ScriptBlock ScriptBlock ScriptBlock

The script block that the user has specified in the cmdlet. This will be converted to a powershell before its actually sent to the remote end

Session Session Session

The PSSession object describing the remote runspace using which the specified cmdlet operation will be performed

SessionName SessionName SessionName

Specifies the name of the returned session when the InDisconnectedSession switch is used.

SessionOption SessionOption SessionOption

Extended Session Options for controlling the session creation. Use "New-WSManSessionOption" cmdlet to supply value for this parameter.

SessionState SessionState SessionState Inherited from PSCmdlet
Stopping Stopping Stopping Inherited from Cmdlet
ThrottleLimit ThrottleLimit ThrottleLimit

Allows the user of the cmdlet to specify a throttling value for throttling the number of remote operations that can be executed simultaneously

UseSSL UseSSL UseSSL

This parameter suggests that the transport scheme to be used for remote connections is useSSL instead of the default http.Since there are only two possible transport schemes that are possible at this point, a SwitchParameter is being used to switch between the two.

UserName UserName UserName

User Name

VMGuid VMGuid VMGuid Inherited from PSExecutionCmdlet
VMId VMId VMId Inherited from PSExecutionCmdlet
VMName VMName VMName Inherited from PSExecutionCmdlet

Methods

BeginProcessing() BeginProcessing() BeginProcessing()

Creates the helper classes for the specified parameter set

CloseAllInputStreams() CloseAllInputStreams() CloseAllInputStreams() Inherited from PSExecutionCmdlet
CreateHelpersForSpecifiedComputerNames() CreateHelpersForSpecifiedComputerNames() CreateHelpersForSpecifiedComputerNames() Inherited from PSExecutionCmdlet
CreateHelpersForSpecifiedContainerSession() CreateHelpersForSpecifiedContainerSession() CreateHelpersForSpecifiedContainerSession() Inherited from PSExecutionCmdlet
CreateHelpersForSpecifiedRunspaces() CreateHelpersForSpecifiedRunspaces() CreateHelpersForSpecifiedRunspaces() Inherited from PSExecutionCmdlet
CreateHelpersForSpecifiedSSHComputerNames() CreateHelpersForSpecifiedSSHComputerNames() CreateHelpersForSpecifiedSSHComputerNames() Inherited from PSExecutionCmdlet
CreateHelpersForSpecifiedSSHHashComputerNames() CreateHelpersForSpecifiedSSHHashComputerNames() CreateHelpersForSpecifiedSSHHashComputerNames() Inherited from PSExecutionCmdlet
CreateHelpersForSpecifiedUris() CreateHelpersForSpecifiedUris() CreateHelpersForSpecifiedUris() Inherited from PSExecutionCmdlet
CreateHelpersForSpecifiedVMSession() CreateHelpersForSpecifiedVMSession() CreateHelpersForSpecifiedVMSession() Inherited from PSExecutionCmdlet
CurrentProviderLocation(String) CurrentProviderLocation(String) CurrentProviderLocation(String) Inherited from PSCmdlet
Dispose() Dispose() Dispose()

Dispose the cmdlet

EndProcessing() EndProcessing() EndProcessing()

InvokeAsync would have been called in ProcessRecord. Wait here for all the results to become available.

GetResolvedProviderPathFromPSPath(String, ProviderInfo) GetResolvedProviderPathFromPSPath(String, ProviderInfo) GetResolvedProviderPathFromPSPath(String, ProviderInfo) Inherited from PSCmdlet
GetResourceString(String, String) GetResourceString(String, String) GetResourceString(String, String) Inherited from Cmdlet
GetScriptBlockFromFile(String, Boolean) GetScriptBlockFromFile(String, Boolean) GetScriptBlockFromFile(String, Boolean) Inherited from PSExecutionCmdlet
GetUnresolvedProviderPathFromPSPath(String) GetUnresolvedProviderPathFromPSPath(String) GetUnresolvedProviderPathFromPSPath(String) Inherited from PSCmdlet
GetVariableValue(String) GetVariableValue(String) GetVariableValue(String) Inherited from PSCmdlet
GetVariableValue(String, Object) GetVariableValue(String, Object) GetVariableValue(String, Object) Inherited from PSCmdlet
Invoke() Invoke() Invoke() Inherited from Cmdlet
Invoke<T>() Invoke<T>() Invoke<T>() Inherited from Cmdlet
ProcessRecord() ProcessRecord() ProcessRecord()

The expression will be executed in the remote computer if a remote runspace parameter or computer name or uri is specified.

ResolveAppName(String) ResolveAppName(String) ResolveAppName(String) Inherited from PSRemotingCmdlet
ResolveComputerName(String) ResolveComputerName(String) ResolveComputerName(String) Inherited from PSRemotingCmdlet
ResolveComputerNames(String[], String[]) ResolveComputerNames(String[], String[]) ResolveComputerNames(String[], String[]) Inherited from PSRemotingCmdlet
ResolveShell(String) ResolveShell(String) ResolveShell(String) Inherited from PSRemotingCmdlet
ShouldContinue(String, String) ShouldContinue(String, String) ShouldContinue(String, String) Inherited from Cmdlet
ShouldContinue(String, String, Boolean, Boolean) ShouldContinue(String, String, Boolean, Boolean) ShouldContinue(String, String, Boolean, Boolean) Inherited from Cmdlet
ShouldContinue(String, String, Boolean, Boolean, Boolean) ShouldContinue(String, String, Boolean, Boolean, Boolean) ShouldContinue(String, String, Boolean, Boolean, Boolean) Inherited from Cmdlet
ShouldProcess(String) ShouldProcess(String) ShouldProcess(String) Inherited from Cmdlet
ShouldProcess(String, String) ShouldProcess(String, String) ShouldProcess(String, String) Inherited from Cmdlet
ShouldProcess(String, String, String) ShouldProcess(String, String, String) ShouldProcess(String, String, String) Inherited from Cmdlet
ShouldProcess(String, String, String, ShouldProcessReason) ShouldProcess(String, String, String, ShouldProcessReason) ShouldProcess(String, String, String, ShouldProcessReason) Inherited from Cmdlet
StopProcessing() StopProcessing() StopProcessing()

This method is called when the user sends a stop signal to the cmdlet. The cmdlet will not exit until it has completed executing the command on all the runspaces. However, when a stop signal is sent, execution needs to be stopped on the pipelines corresponding to these runspaces

ThrowTerminatingError(ErrorRecord) ThrowTerminatingError(ErrorRecord) ThrowTerminatingError(ErrorRecord) Inherited from Cmdlet
TransactionAvailable() TransactionAvailable() TransactionAvailable() Inherited from Cmdlet
ValidateComputerName(String[]) ValidateComputerName(String[]) ValidateComputerName(String[]) Inherited from PSRemotingBaseCmdlet
ValidateRemoteRunspacesSpecified() ValidateRemoteRunspacesSpecified() ValidateRemoteRunspacesSpecified() Inherited from PSRemotingBaseCmdlet
WriteCommandDetail(String) WriteCommandDetail(String) WriteCommandDetail(String) Inherited from Cmdlet
WriteDebug(String) WriteDebug(String) WriteDebug(String) Inherited from Cmdlet
WriteError(ErrorRecord) WriteError(ErrorRecord) WriteError(ErrorRecord) Inherited from Cmdlet
WriteInformation(InformationRecord) WriteInformation(InformationRecord) WriteInformation(InformationRecord) Inherited from Cmdlet
WriteInformation(Object, String[]) WriteInformation(Object, String[]) WriteInformation(Object, String[]) Inherited from Cmdlet
WriteObject(Object) WriteObject(Object) WriteObject(Object) Inherited from Cmdlet
WriteObject(Object, Boolean) WriteObject(Object, Boolean) WriteObject(Object, Boolean) Inherited from Cmdlet
WriteProgress(ProgressRecord) WriteProgress(ProgressRecord) WriteProgress(ProgressRecord) Inherited from Cmdlet
WriteVerbose(String) WriteVerbose(String) WriteVerbose(String) Inherited from Cmdlet
WriteWarning(String) WriteWarning(String) WriteWarning(String) Inherited from Cmdlet

Fields

ComputerInstanceIdParameterSet ComputerInstanceIdParameterSet ComputerInstanceIdParameterSet Inherited from PSRemotingCmdlet
ComputerNameParameterSet ComputerNameParameterSet ComputerNameParameterSet Inherited from PSRemotingCmdlet
ContainerIdParameterSet ContainerIdParameterSet ContainerIdParameterSet Inherited from PSRemotingCmdlet
DefaultPowerShellRemoteShellAppName DefaultPowerShellRemoteShellAppName DefaultPowerShellRemoteShellAppName Inherited from PSRemotingCmdlet
DefaultPowerShellRemoteShellName DefaultPowerShellRemoteShellName DefaultPowerShellRemoteShellName Inherited from PSRemotingCmdlet
FilePathComputerNameParameterSet FilePathComputerNameParameterSet FilePathComputerNameParameterSet Inherited from PSExecutionCmdlet
FilePathContainerIdParameterSet FilePathContainerIdParameterSet FilePathContainerIdParameterSet Inherited from PSExecutionCmdlet
FilePathSSHHostHashParameterSet FilePathSSHHostHashParameterSet FilePathSSHHostHashParameterSet Inherited from PSExecutionCmdlet
FilePathSSHHostParameterSet FilePathSSHHostParameterSet FilePathSSHHostParameterSet Inherited from PSExecutionCmdlet
FilePathSessionParameterSet FilePathSessionParameterSet FilePathSessionParameterSet Inherited from PSExecutionCmdlet
FilePathUriParameterSet FilePathUriParameterSet FilePathUriParameterSet Inherited from PSExecutionCmdlet
FilePathVMIdParameterSet FilePathVMIdParameterSet FilePathVMIdParameterSet Inherited from PSExecutionCmdlet
FilePathVMNameParameterSet FilePathVMNameParameterSet FilePathVMNameParameterSet Inherited from PSExecutionCmdlet
LiteralFilePathComputerNameParameterSet LiteralFilePathComputerNameParameterSet LiteralFilePathComputerNameParameterSet Inherited from PSExecutionCmdlet
SSHHostHashParameterSet SSHHostHashParameterSet SSHHostHashParameterSet Inherited from PSRemotingCmdlet
SSHHostParameterSet SSHHostParameterSet SSHHostParameterSet Inherited from PSRemotingCmdlet
SessionParameterSet SessionParameterSet SessionParameterSet Inherited from PSRemotingCmdlet
UriParameterSet UriParameterSet UriParameterSet Inherited from PSRemotingBaseCmdlet
VMIdParameterSet VMIdParameterSet VMIdParameterSet Inherited from PSExecutionCmdlet
VMNameParameterSet VMNameParameterSet VMNameParameterSet Inherited from PSExecutionCmdlet

Applies to