CmdID / PowerShell / Cmdlets / Invoke
Invoke-Command
Runs commands on local and remote computers. PowerShell reference
From the PowerShell reference
28 parameters
Alias icm
3 Sigma rules look for it
What it does
Runs commands on local and remote computers. The Invoke-Command cmdlet runs commands on a local or remote computer and returns all output from the commands, including errors. Using a single Invoke-Command command, you can run commands on multiple computers. To run a single command on a remote computer, use the ComputerName parameter. To run a series of related commands that share data, use the New-PSSession cmdlet to create a PSSession (a persistent connection) on the remote computer, and then use the Session parameter of Invoke-Command to run the command in the PSSession. To run a command in a disconnected session, use the InDisconnectedSession parameter. To run a command in a background job, use the AsJob parameter. You can also use Invoke-Command on a local computer to run a scriptblock as a command. PowerShell runs the scriptblock immediately in a child scope of the current scope. Before using Invoke-Command to run commands on a remote computer, read about_Remote. Some code samples use splatting to reduce the line length. For more information, see about_Splatting.
Invoke-Command [-ScriptBlock] <ScriptBlock> [-NoNewScope] [-InputObject <PSObject>] [-ArgumentList <Object[]>] [<CommonParameters>]Invoke-Command [[-Session] <PSSession[]>] [-ThrottleLimit <Int32>] [-AsJob] [-HideComputerName] [-JobName <String>] [-ScriptBlock] <ScriptBlock> [-InputObject <PSObject>] [-ArgumentList <Object[]>] [<CommonParameters>]Invoke-Command [[-Session] <PSSession[]>] [-ThrottleLimit <Int32>] [-AsJob] [-HideComputerName] [-JobName <String>] [-FilePath] <String> [-InputObject <PSObject>] [-ArgumentList <Object[]>] [<CommonParameters>]Invoke-Command [[-ComputerName] <String[]>] [-Credential <PSCredential>] [-Port <Int32>] [-UseSSL] [-ConfigurationName <String>] [-ApplicationName <String>] [-ThrottleLimit <Int32>] [-AsJob] [-InDisconnectedSession] [-SessionName <String[]>] [-HideComputerName] [-JobName <String>] [-FilePath] <String> [-SessionOption <PSSessionOption>] [-Authentication <AuthenticationMechanism>] [-EnableNetworkAccess] [-InputObject <PSObject>] [-ArgumentList <Object[]>] [<CommonParameters>]Invoke-Command [[-ComputerName] <String[]>] [-Credential <PSCredential>] [-Port <Int32>] [-UseSSL] [-ConfigurationName <String>] [-ApplicationName <String>] [-ThrottleLimit <Int32>] [-AsJob] [-InDisconnectedSession] [-SessionName <String[]>] [-HideComputerName] [-JobName <String>] [-ScriptBlock] <ScriptBlock> [-SessionOption <PSSessionOption>] [-Authentication <AuthenticationMechanism>] [-EnableNetworkAccess] [-InputObject <PSObject>] [-ArgumentList <Object[]>] [-CertificateThumbprint <String>] [<CommonParameters>]Invoke-Command [-Credential <PSCredential>] [-ConfigurationName <String>] [-ThrottleLimit <Int32>] [[-ConnectionUri] <Uri[]>] [-AsJob] [-InDisconnectedSession] [-HideComputerName] [-JobName <String>] [-ScriptBlock] <ScriptBlock> [-AllowRedirection] [-SessionOption <PSSessionOption>] [-Authentication <AuthenticationMechanism>] [-EnableNetworkAccess] [-InputObject <PSObject>] [-ArgumentList <Object[]>] [-CertificateThumbprint <String>] [<CommonParameters>]Invoke-Command [-Credential <PSCredential>] [-ConfigurationName <String>] [-ThrottleLimit <Int32>] [[-ConnectionUri] <Uri[]>] [-AsJob] [-InDisconnectedSession] [-HideComputerName] [-JobName <String>] [-FilePath] <String> [-AllowRedirection] [-SessionOption <PSSessionOption>] [-Authentication <AuthenticationMechanism>] [-EnableNetworkAccess] [-InputObject <PSObject>] [-ArgumentList <Object[]>] [<CommonParameters>]Invoke-Command -Credential <PSCredential> [-ConfigurationName <String>] [-ThrottleLimit <Int32>] [-AsJob] [-HideComputerName] [-ScriptBlock] <ScriptBlock> [-InputObject <PSObject>] [-ArgumentList <Object[]>] [-VMId] <Guid[]> [<CommonParameters>]Invoke-Command -Credential <PSCredential> [-ConfigurationName <String>] [-ThrottleLimit <Int32>] [-AsJob] [-HideComputerName] [-ScriptBlock] <ScriptBlock> [-InputObject <PSObject>] [-ArgumentList <Object[]>] -VMName <String[]> [<CommonParameters>]Invoke-Command -Credential <PSCredential> [-ConfigurationName <String>] [-ThrottleLimit <Int32>] [-AsJob] [-HideComputerName] [-FilePath] <String> [-InputObject <PSObject>] [-ArgumentList <Object[]>] [-VMId] <Guid[]> [<CommonParameters>]Invoke-Command -Credential <PSCredential> [-ConfigurationName <String>] [-ThrottleLimit <Int32>] [-AsJob] [-HideComputerName] [-FilePath] <String> [-InputObject <PSObject>] [-ArgumentList <Object[]>] -VMName <String[]> [<CommonParameters>]Invoke-Command [-ConfigurationName <String>] [-ThrottleLimit <Int32>] [-AsJob] [-HideComputerName] [-JobName <String>] [-ScriptBlock] <ScriptBlock> [-RunAsAdministrator] [-InputObject <PSObject>] [-ArgumentList <Object[]>] -ContainerId <String[]> [<CommonParameters>]Invoke-Command [-ConfigurationName <String>] [-ThrottleLimit <Int32>] [-AsJob] [-HideComputerName] [-JobName <String>] [-FilePath] <String> [-RunAsAdministrator] [-InputObject <PSObject>] [-ArgumentList <Object[]>] -ContainerId <String[]> [<CommonParameters>]
Run a script on a server
Invoke-Command -FilePath C:\scripts\test.ps1 -ComputerName Server01IdentifyRun a command on a remote server
Invoke-Command -ComputerName Server01 -Credential Domain01\User01 -ScriptBlock {
Get-Culture
}IdentifyRun a command in a persistent connection
$s = New-PSSession -ComputerName Server02 -Credential Domain01\User01
Invoke-Command -Session $s -ScriptBlock { Get-Culture }IdentifyUse a session to run a series of commands that share data
Invoke-Command -ComputerName Server02 -ScriptBlock { $p = Get-Process powershell }
Invoke-Command -ComputerName Server02 -ScriptBlock { $p.VirtualMemorySize }
$s = New-PSSession -ComputerName Server02
Invoke-Command -Session $s -ScriptBlock { $p = Get-Process powershell }
Invoke-Command -Session $s -ScriptBlock { $p.VirtualMemorySize }IdentifyInvoke a command with a scriptblock stored in a variable
$command = {
Get-EventLog -LogName 'Windows PowerShell' |
Where-Object { $_.Message -like 'certificate' }
}
Invoke-Command -ComputerName S1, S2 -ScriptBlock $commandIdentifyTrips 2 Sigma rules: mediumEventLog Query Requests By Builtin Utilities by Ali Alwashali, Nasreddine Bencherchali (Nextron Systems); mediumPotentially Suspicious EventLog Recon Activity Using Log Query Utilities by Nasreddine Bencherchali (Nextron Systems), X__Junior (Nextron Systems)
Run a single command on several computers
$parameters = @{
ComputerName = 'Server01', 'Server02', 'TST-0143', 'localhost'
ConfigurationName = 'MySession.PowerShell'
ScriptBlock = { Get-EventLog 'Windows PowerShell' }
}
Invoke-Command @parametersIdentifyTrips 2 Sigma rules: mediumEventLog Query Requests By Builtin Utilities by Ali Alwashali, Nasreddine Bencherchali (Nextron Systems); mediumPotentially Suspicious EventLog Recon Activity Using Log Query Utilities by Nasreddine Bencherchali (Nextron Systems), X__Junior (Nextron Systems)
Get the version of the host program on multiple computers
$version = Invoke-Command -ComputerName (Get-Content Machines.txt) -ScriptBlock {
(Get-Host).Version
}IdentifyRun a background job on several remote computers
$s = New-PSSession -ComputerName Server01, Server02
Invoke-Command -Session $s -ScriptBlock { Get-EventLog System } -AsJobIdentifyTrips 1 Sigma rule: mediumEventLog Query Requests By Builtin Utilities by Ali Alwashali, Nasreddine Bencherchali (Nextron Systems)
Include local variables in a command run on a remote computer
$Log = 'Windows PowerShell'
Invoke-Command -ComputerName Server01 -ScriptBlock {
Get-EventLog -LogName $Using:Log -Newest 10
}IdentifyTrips 2 Sigma rules: mediumEventLog Query Requests By Builtin Utilities by Ali Alwashali, Nasreddine Bencherchali (Nextron Systems); mediumPotentially Suspicious EventLog Recon Activity Using Log Query Utilities by Nasreddine Bencherchali (Nextron Systems), X__Junior (Nextron Systems)
Hide the computer name
Invoke-Command -ComputerName S1, S2 -ScriptBlock { Get-Process powershell }IdentifyIts page in the reference: Invoke-Command.
Parameters
Show its 28 parameters
-AllowRedirectionAllows redirection of this connection to an alternate Uniform Resource Identifier (URI).
When you use the ConnectionURI parameter, the remote destination can return an instruction to redirect to a different URI. By default, PowerShell doesn't redirect connections, but you can use this parameter to allow it to redirect the connection.
You can also limit the number of times the connection is redirected by changing the
MaximumConnectionRedirectionCount session option value. Use the MaximumRedirection parameter
of the New-PSSessionOption cmdlet or set the MaximumConnectionRedirectionCount property of the
$PSSessionOption preference variable. The default value is 5.-ApplicationNameSpecifies the application name segment of the connection URI. Use this parameter to specify the application name when you aren't using the ConnectionURI parameter in the command.
The default value is the value of the $PSSessionApplicationName preference variable on the local computer. If this preference variable isn't defined, the default value is WSMAN. This value is appropriate for most uses. For more information, see about_Preference_Variables.
The WinRM service uses the application name to select a listener to service the connection request. The value of this parameter should match the value of the URLPrefix property of a listener on the remote computer.-ArgumentListSupplies the values of parameters for the scriptblock. The parameters in the scriptblock are passed by position from the array value supplied to ArgumentList. This is known as array splatting. For more information about the behavior of ArgumentList, see about_Splatting.
IMPORTANT: Using this parameter with untrusted data is a security risk. Only use trusted data with this parameter. For more information, see Validate All Inputs.-AsJobIndicates that this cmdlet runs the command as a background job on a remote computer. Use this parameter to run commands that take an extensive time to finish.
When you use the AsJob parameter, the command returns an object that represents the job, and then displays the command prompt. You can continue to work in the session while the job finishes. To manage the job, use the *-Job cmdlets. To get the job results, use the Receive-Job cmdlet.
The AsJob parameter resembles using the Invoke-Command cmdlet to run a Start-Job cmdlet remotely. However, with AsJob, the job is created on the local computer, even though the job runs on a remote computer. The results of the remote job are automatically returned to the local computer.
For more information about PowerShell background jobs, see about_Jobs and about_Remote_Jobs.-AuthenticationSpecifies the mechanism that's used to authenticate the user's credentials. CredSSP authentication is available only in Windows Vista, Windows Server 2008, and later versions of the Windows operating system.
The acceptable values for this parameter are as follows:
- Default
- Basic
- Credssp
- Digest
- Kerberos
- Negotiate
- NegotiateWithImplicitCredential
The default value is Default.
For more information about the values of this parameter, see AuthenticationMechanism Enumeration.
CAUTION: Credential Security Support Provider (CredSSP) authentication, in which the user's credentials are passed to a remote computer to be authenticated, is designed for commands that require authentication on more than one resource, such as accessing a remote network share. This mechanism increases the security risk of the remote operation. If the remote computer is compromised, the credentials that are passed to it can be used to control the network session. For more information, see Credential Security Support Provider.-CertificateThumbprintSpecifies the digital public key certificate (X509) of a user account that has permission to connect to the disconnected session. Enter the certificate thumbprint of the certificate.
Certificates are used in client certificate-based authentication. They can be mapped only to local user accounts and they don't work with domain accounts.
To get a certificate thumbprint, use a Get-Item or Get-ChildItem command in the PowerShell Cert: drive.-ComputerNameSpecifies the computers on which the command runs. The default is the local computer.
When you use the ComputerName parameter, PowerShell creates a temporary connection that's used only to run the specified command and is then closed. If you need a persistent connection, use the Session parameter.
To use an IP address in the value of ComputerName, the command must include the Credential parameter. The computer must be configured for the HTTPS transport or the IP address of the remote computer must be included in the local computer's WinRM TrustedHosts list. For instructions to add a computer name to the TrustedHosts list, see How to Add a Computer to the Trusted Host List.
On Windows Vista and later versions of the Windows operating system, to include the local computer in the value of ComputerName, you must run PowerShell using the Run as administrator option.-ConfigurationNameSpecifies the session configuration that is used for the new PSSession.
Enter a configuration name or the fully qualified resource URI for a session configuration. If you specify only the configuration name, the following schema URI is prepended: http://schemas.microsoft.com/PowerShell.
The session configuration for a session is located on the remote computer. If the specified session configuration doesn't exist on the remote computer, the command fails.
The default value is the value of the $PSSessionConfigurationName preference variable on the local computer. If this preference variable isn't set, the default is Microsoft.PowerShell. For more information, see about_Preference_Variables.-ConnectionUriSpecifies a Uniform Resource Identifier (URI) that defines the connection endpoint of the session. The URI must be fully qualified.
The format of this string is as follows:
<Transport>://<ComputerName>:<Port>/<ApplicationName>
The default value is as follows:
http://localhost:5985/WSMAN
If you don't specify a connection URI, you can use the UseSSL and Port parameters to specify the connection URI values.
Valid values for the Transport segment of the URI are HTTP and HTTPS. If you specify a connection URI with a Transport segment, but don't specify a port, the session is created with the standards ports: 80 for HTTP and 443 for HTTPS. To use the default ports for PowerShell remoting, specify port 5985 for HTTP or 5986 for HTTPS.
If the destination computer redirects the connection to a different URI, PowerShell prevents the redirection unless you use the AllowRedirection parameter in the command.-ContainerIdSpecifies an array of container IDs.-CredentialSpecifies a user account that has permission to perform this action. The default is the current user.
Credentials are stored in a PSCredential object and the password is stored as a SecureString.
NOTE: For more information about SecureString data protection, see How secure is SecureString?.-EnableNetworkAccessIndicates that this cmdlet adds an interactive security token to loopback sessions. The interactive token lets you run commands in the loopback session that get data from other computers. For example, you can run a command in the session that copies XML files from a remote computer to the local computer.
A loopback session is a PSSession that originates and ends on the same computer. To create a loopback session, omit the ComputerName parameter or set its value to dot (.), localhost, or the name of the local computer.
By default, loopback sessions are created using a network token, which might not provide sufficient permission to authenticate to remote computers.
The EnableNetworkAccess parameter is effective only in loopback sessions. If you use EnableNetworkAccess when you create a session on a remote computer, the command succeeds, but the parameter is ignored.
You can allow remote access in a loopback session using the CredSSP value of the Authentication parameter, which delegates the session credentials to other computers. …-FilePathSpecifies a local script that this cmdlet runs on one or more remote computers. Enter the path and filename of the script, or pipe a script path to Invoke-Command. The script must exist on the local computer or in a directory that the local computer can access. Use ArgumentList to specify the values of parameters in the script.
When you use this parameter, PowerShell converts the contents of the specified script file to a scriptblock, transmits the scriptblock to the remote computer, and runs it on the remote computer.
IMPORTANT: Using this parameter with untrusted data is a security risk. Only use trusted data with this parameter. For more information, see Validate All Inputs.-HideComputerNameIndicates that this cmdlet omits the computer name of each object from the output display. By default, the name of the computer that generated the object appears in the display.
This parameter affects only the output display. It doesn't change the object.-InDisconnectedSessionIndicates that this cmdlet runs a command or script in a disconnected session.
When you use the InDisconnectedSession parameter, Invoke-Command creates a persistent session on each remote computer, starts the command specified by the ScriptBlock or FilePath parameter, and then disconnects from the session. The commands continue to run in the disconnected sessions. InDisconnectedSession enables you to run commands without maintaining a connection to the remote sessions. And, because the session is disconnected before any results are returned, InDisconnectedSession makes sure that all command results are returned to the reconnected session, instead of being split between sessions.
You can't use InDisconnectedSession with the Session parameter or the AsJob parameter.
Commands that use InDisconnectedSession return a PSSession object that represents the disconnected session. They don't return the command output. To connect to the disconnected session, use the Connect-PSSession or Receive-PSSession cmdlets. To get the results of commands that ran in the session, use the Receive-PSSession cmdlet. …-InputObjectSpecifies input to the command. Enter a variable that contains the objects or type a command or expression that gets the objects.
When using the InputObject parameter, use the $input automatic variable in the value of the ScriptBlock parameter to represent the input objects.-JobNameSpecifies a friendly name for the background job. By default, jobs are named Job<n>, where <n> is an ordinal number.
If you use the JobName parameter in a command, the command is run as a job, and Invoke-Command returns a job object, even if you don't include AsJob in the command.
For more information about PowerShell background jobs, see about_Jobs.-NoNewScopeIndicates that this cmdlet runs the specified command in the current scope. By default,
Invoke-Command runs commands in their own scope.
This parameter is valid only in commands that are run in the current session, that is, commands that omit both the ComputerName and Session parameters.
This parameter was introduced in PowerShell 3.0.-PortSpecifies the network port on the remote computer that is used for this command. To connect to a remote computer, the remote computer must be listening on the port that the connection uses. The default ports are 5985 (WinRM port for HTTP) and 5986 (WinRM port for HTTPS).
Before using an alternate port, configure the WinRM listener on the remote computer to listen at that port. To configure the listener, type the following two commands at the PowerShell prompt:
Remove-Item -Path WSMan:\Localhost\listener\listener* -Recurse
New-Item -Path WSMan:\Localhost\listener -Transport http -Address * -Port <port-number>
Don't use the Port parameter unless you must. The port that is set in the command applies to all computers or sessions on which the command runs. An alternate port setting might prevent the command from running on all computers.-RunAsAdministratorIndicates that this cmdlet invokes a command as an Administrator.-ScriptBlockSpecifies the commands to run. Enclose the commands in braces ({}) to create a scriptblock. When using Invoke-Command to run a command remotely, any variables in the command are evaluated on the remote computer.
NOTE: Parameters for the scriptblock can only be passed in from ArgumentList by position. Switch parameters cannot be passed by position. If you need a parameter that behaves like a SwitchParameter type, use a Boolean type instead.-SessionSpecifies an array of sessions in which this cmdlet runs the command. Enter a variable that contains
PSSession objects or a command that creates or gets the PSSession objects, such as a
New-PSSession or Get-PSSession command.
When you create a PSSession, PowerShell establishes a persistent connection to the remote computer. Use a PSSession to run a series of related commands that share data. To run a single command or a series of unrelated commands, use the ComputerName parameter. For more information, see about_PSSessions.-SessionNameSpecifies a friendly name for a disconnected session. You can use the name to refer to the session in subsequent commands, such as a Get-PSSession command. This parameter is valid only with the InDisconnectedSession parameter.
This parameter was introduced in PowerShell 3.0.-SessionOptionSpecifies advanced options for the session. Enter a SessionOption object, such as one that you create using the New-PSSessionOption cmdlet, or a hash table in which the keys are session option names and the values are session option values.
NOTE: If you specify a hashtable for SessionOption, PowerShell converts the hashtable into a System.Management.Automation.Remoting.PSSessionOption object. The values for keys specified in the hashtable are cast to the matching property of the object. This behaves differently from calling New-PSSessionOption. For example, the System.TimeSpan values for the timeout properties, like IdleTimeout, convert an integer value into ticks instead of milliseconds. For more information on the PSSessionOption object and its properties, see PSSessionOption
The default values for the options are determined by the value of the $PSSessionOption preference variable, if it's set. Otherwise, the default values are established by options set in the session configuration.
The session option values take precedence over default values for sessions set in the
$PSSessionOption preference variable and in the session configuration. However, they don't take …-ThrottleLimitSpecifies 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.-UseSSLIndicates that this cmdlet uses the Secure Sockets Layer (SSL) protocol to establish a connection to the remote computer. By default, SSL isn't used.
WS-Management encrypts all PowerShell content transmitted over the network. The UseSSL parameter is an additional protection that sends the data across an HTTPS, instead of HTTP.
If you use this parameter, but SSL isn't available on the port that's used for the command, the command fails.-VMIdSpecifies an array of IDs of virtual machines.-VMNameSpecifies an array of names of virtual machines.