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 | %{"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} ¨Crunspace $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 | %{"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.
public ref class InvokeCommandCommand : Microsoft::PowerShell::Commands::PSExecutionCmdlet, IDisposable
public class InvokeCommandCommand : Microsoft.PowerShell.Commands.PSExecutionCmdlet, IDisposable
[System.Management.Automation.Cmdlet("Invoke", "Command", DefaultParameterSetName="InProcess", HelpUri="https://go.microsoft.com/fwlink/?LinkID=2096789", RemotingCapability=System.Management.Automation.RemotingCapability.OwnedByCommand)]
public class InvokeCommandCommand : Microsoft.PowerShell.Commands.PSExecutionCmdlet, IDisposable
[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()

Fields

ComputerInstanceIdParameterSet

Computername with session instance ID parameter set

(Inherited from PSRemotingCmdlet)
ComputerNameParameterSet

Computername parameter set

(Inherited from PSRemotingCmdlet)
ContainerIdParameterSet

Container ID parameter set

(Inherited from PSRemotingCmdlet)
DefaultPowerShellRemoteShellAppName

default application name for the connection uri

(Inherited from PSRemotingCmdlet)
DefaultPowerShellRemoteShellName

Default shellname

(Inherited from PSRemotingCmdlet)
FilePathComputerNameParameterSet

FilePathComputername parameter set

(Inherited from PSExecutionCmdlet)
FilePathContainerIdParameterSet

Container ID file path parameter set.

(Inherited from PSExecutionCmdlet)
FilePathSessionParameterSet

FilePathRunspace parameter set

(Inherited from PSExecutionCmdlet)
FilePathSSHHostHashParameterSet

SSH Host file path parameter set with HashTable connection parameter

(Inherited from PSExecutionCmdlet)
FilePathSSHHostParameterSet

SSH Host file path parameter set.

(Inherited from PSExecutionCmdlet)
FilePathUriParameterSet

FilePathUri parameter set

(Inherited from PSExecutionCmdlet)
FilePathVMIdParameterSet

VM guid file path parameter set.

(Inherited from PSExecutionCmdlet)
FilePathVMNameParameterSet

VM name file path parameter set.

(Inherited from PSExecutionCmdlet)
LiteralFilePathComputerNameParameterSet

LiteralFilePathComputername parameter set

(Inherited from PSExecutionCmdlet)
SessionParameterSet

runspace parameter set

(Inherited from PSRemotingCmdlet)
SSHHostHashParameterSet

SSH host parmeter set supporting hash connection parameters

(Inherited from PSRemotingCmdlet)
SSHHostParameterSet

SSH host parameter set

(Inherited from PSRemotingCmdlet)
UriParameterSet

Uri parameter set

(Inherited from PSRemotingBaseCmdlet)
UseWindowsPowerShellParameterSet (Inherited from PSRemotingCmdlet)
VMIdParameterSet

VM guid parameter set

(Inherited from PSRemotingCmdlet)
VMNameParameterSet

VM name parameter set

(Inherited from PSRemotingCmdlet)

Properties

AllowRedirection

The AllowRediraction parameter enables the implicit redirection functionality

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

Arguments that are passed to this scriptblock

(Inherited from PSExecutionCmdlet)
AsJob

Specifies if the cmdlet needs to be run asynchronously

Authentication

Authentication mechanism to authenticate the user

CertificateThumbprint

Specifies the certificate thumbprint to be used to impersonate the user on the remote machine.

(Inherited from PSRemotingBaseCmdlet)
CommandOrigin

This property tells you if you were being invoked inside the runspace or if it was an external request.

(Inherited from InternalCommand)
CommandRuntime

Holds the command runtime object for this command. This object controls what actually happens when a write is called.

(Inherited from Cmdlet)
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

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

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

ContainerId

ID of target container.

(Inherited from PSExecutionCmdlet)
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

Gets an object that surfaces the current PowerShell transaction. When this object is disposed, PowerShell resets the active transaction

(Inherited from Cmdlet)
DisconnectedSessionName

Session names optionally provided for Disconnected parameter.

(Inherited from PSExecutionCmdlet)
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

Gets the event manager for the current runspace.

(Inherited from PSCmdlet)
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

Hide/Show computername of the remote objects.

Host

Gets the host interaction APIs.

(Inherited from PSCmdlet)
HostName

Host name for an SSH remote connection

HostName

Host name for an SSH remote connection.

(Inherited from PSRemotingBaseCmdlet)
InDisconnectedSession

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

InputObject

Input object which gets assigned to $input when executed on the remote machine. This is the only parameter in this cmdlet which will bind with a ValueFromPipeline=true

(Inherited from PSExecutionCmdlet)
InvokeAndDisconnect

Indicates that if a job/command is invoked remotely the connection should be severed right have invocation of job/command.

(Inherited from PSExecutionCmdlet)
InvokeCommand

Provides access to utility routines for executing scripts and creating script blocks.

(Inherited from PSCmdlet)
InvokeProvider

Gets the instance of the provider interface APIs for the current runspace.

(Inherited from PSCmdlet)
IsLiteralPath

True if FilePath should be processed as a literal path

(Inherited from PSExecutionCmdlet)
JobManager

Manager for JobSourceAdapters registered.

(Inherited from PSCmdlet)
JobName

Friendly name for the job object if AsJob is used

JobRepository

Repostiory for jobs

(Inherited from PSCmdlet)
KeyFilePath

Key Path

KeyFilePath

SSH Key File Path

(Inherited from PSRemotingBaseCmdlet)
MyInvocation

Contains information about the identity of this cmdlet and how it was invoked.

(Inherited from PSCmdlet)
NoNewScope

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

PagingParameters

If the cmdlet declares paging support (via SupportsPaging), then PagingParameters property contains arguments of the paging parameters. Otherwise PagingParameters property is null.

(Inherited from PSCmdlet)
ParameterSetName

The name of the parameter set in effect.

(Inherited from PSCmdlet)
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

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

ResolvedComputerNames

Computer names after they have been resolved (null, empty string, "." resolves to localhost)

(Inherited from PSRemotingBaseCmdlet)
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.

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

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

SessionName

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

SessionOption

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

SessionState

Gets the instance of session state for the current runspace.

(Inherited from PSCmdlet)
SSHConnection

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

SSHConnection

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

(Inherited from PSRemotingBaseCmdlet)
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.

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.

(Inherited from PSRemotingBaseCmdlet)
Stopping

Is this command stopping?

(Inherited from Cmdlet)
Subsystem (Inherited from PSRemotingBaseCmdlet)
ThrottleLimit

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

UserName

User Name

UserName

SSH User Name

(Inherited from PSRemotingBaseCmdlet)
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.

VMId

Guid of target virtual machine.

(Inherited from PSExecutionCmdlet)
VMName

Name of target virtual machine.

(Inherited from PSExecutionCmdlet)

Methods

BeginProcessing()

Creates the helper classes for the specified parameter set

CloseAllInputStreams()

Closes the input streams on all the pipelines

(Inherited from PSExecutionCmdlet)
CreateHelpersForSpecifiedComputerNames()

Creates helper objects with the command for the specified remote computer names

(Inherited from PSExecutionCmdlet)
CreateHelpersForSpecifiedContainerSession()

Creates helper objects with the command for the specified container IDs or names.

(Inherited from PSExecutionCmdlet)
CreateHelpersForSpecifiedRunspaces()

Creates helper objects with the specified command for the specified remote runspaceinfo objects

(Inherited from PSExecutionCmdlet)
CreateHelpersForSpecifiedSSHComputerNames()

Creates helper objects for SSH remoting computer names remoting.

(Inherited from PSExecutionCmdlet)
CreateHelpersForSpecifiedSSHHashComputerNames()

Creates helper objects for SSH remoting from HashTable parameters.

(Inherited from PSExecutionCmdlet)
CreateHelpersForSpecifiedUris()

Creates helper objects with the command for the specified remote connection uris

(Inherited from PSExecutionCmdlet)
CreateHelpersForSpecifiedVMSession()

Creates helper objects with the command for the specified VM GUIDs or VM names.

(Inherited from PSExecutionCmdlet)
CurrentProviderLocation(String) (Inherited from PSCmdlet)
Dispose()

Dispose the cmdlet

EndProcessing()

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

GetResolvedProviderPathFromPSPath(String, ProviderInfo) (Inherited from PSCmdlet)
GetResourceString(String, String)

Gets the resource string corresponding to baseName and resourceId from the current assembly. You should override this if you require a different behavior.

(Inherited from Cmdlet)
GetScriptBlockFromFile(String, Boolean)

Reads content of file and converts it to a scriptblock

(Inherited from PSExecutionCmdlet)
GetUnresolvedProviderPathFromPSPath(String) (Inherited from PSCmdlet)
GetVariableValue(String) (Inherited from PSCmdlet)
GetVariableValue(String, Object) (Inherited from PSCmdlet)
Invoke()

Invoke this cmdlet object returning a collection of results.

(Inherited from Cmdlet)
Invoke<T>()

Returns a strongly-typed enumerator for the results of this cmdlet.

(Inherited from Cmdlet)
ParseSshHostName(String, String, String, Int32) (Inherited from PSRemotingBaseCmdlet)
ProcessRecord()

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

ResolveAppName(String)

Determines the appname to be used based on the following order: 1. AppName parameter specified 2. DEFAULTREMOTEAPPNAME variable set 3. WSMan

(Inherited from PSRemotingCmdlet)
ResolveComputerName(String)

Resolves a computer name. If its null or empty its assumed to be localhost

(Inherited from PSRemotingCmdlet)
ResolveComputerNames(String[], String[])

Resolve all the machine names provided. Basically, if a machine name is '.' assume localhost

(Inherited from PSRemotingCmdlet)
ResolveShell(String)

Determines the shellname to use based on the following order: 1. ShellName parameter specified 2. DEFAULTREMOTESHELLNAME variable set 3. PowerShell

(Inherited from PSRemotingCmdlet)
ShouldContinue(String, String)

Confirm an operation or grouping of operations with the user. This differs from ShouldProcess in that it is not affected by preference settings or command-line parameters, it always does the query. This variant only offers Yes/No, not YesToAll/NoToAll.

(Inherited from Cmdlet)
ShouldContinue(String, String, Boolean, Boolean)

Confirm an operation or grouping of operations with the user. This differs from ShouldProcess in that it is not affected by preference settings or command-line parameters, it always does the query. This variant offers Yes, No, YesToAll and NoToAll.

(Inherited from Cmdlet)
ShouldContinue(String, String, Boolean, Boolean, Boolean)

Confirm an operation or grouping of operations with the user. This differs from ShouldProcess in that it is not affected by preference settings or command-line parameters, it always does the query. This variant offers Yes, No, YesToAll and NoToAll.

(Inherited from Cmdlet)
ShouldProcess(String)

Confirm the operation with the user. Cmdlets which make changes (e.g. delete files, stop services etc.) should call ShouldProcess to give the user the opportunity to confirm that the operation should actually be performed.

(Inherited from Cmdlet)
ShouldProcess(String, String)

Confirm the operation with the user. Cmdlets which make changes (e.g. delete files, stop services etc.) should call ShouldProcess to give the user the opportunity to confirm that the operation should actually be performed.

This variant allows the caller to specify text for both the target resource and the action.

(Inherited from Cmdlet)
ShouldProcess(String, String, String)

Confirm the operation with the user. Cmdlets which make changes (e.g. delete files, stop services etc.) should call ShouldProcess to give the user the opportunity to confirm that the operation should actually be performed.

This variant allows the caller to specify the complete text describing the operation, rather than just the name and action.

(Inherited from Cmdlet)
ShouldProcess(String, String, String, ShouldProcessReason)

Confirm the operation with the user. Cmdlets which make changes (e.g. delete files, stop services etc.) should call ShouldProcess to give the user the opportunity to confirm that the operation should actually be performed.

This variant allows the caller to specify the complete text describing the operation, rather than just the name and action.

(Inherited from Cmdlet)
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)

Terminate the command and report an error

(Inherited from Cmdlet)
TransactionAvailable()

Returns true if a transaction is available and active.

(Inherited from Cmdlet)
ValidateComputerName(String[])

Validates computer names to check if none of them happen to be a Uri. If so this throws an error

(Inherited from PSRemotingBaseCmdlet)
ValidateRemoteRunspacesSpecified()

Validate the PSSession objects specified and write appropriate error records.

(Inherited from PSRemotingBaseCmdlet)
WriteCommandDetail(String)

Write text into pipeline execution log.

(Inherited from Cmdlet)
WriteDebug(String)

Display debug information

(Inherited from Cmdlet)
WriteError(ErrorRecord)

Internal variant: Writes the specified error to the error pipe.

(Inherited from Cmdlet)
WriteInformation(InformationRecord)

Route information to the user or host.

(Inherited from Cmdlet)
WriteInformation(Object, String[])

Route information to the user or host.

(Inherited from Cmdlet)
WriteObject(Object)

Writes the object to the output pipe.

(Inherited from Cmdlet)
WriteObject(Object, Boolean)

Writes one or more objects to the output pipe. If the object is a collection and the enumerateCollection flag is true, the objects in the collection will be written individually.

(Inherited from Cmdlet)
WriteProgress(ProgressRecord)

Display progress information

(Inherited from Cmdlet)
WriteVerbose(String)

Display verbose information

(Inherited from Cmdlet)
WriteWarning(String)

Display warning information

(Inherited from Cmdlet)

Applies to