PowerShell Logo Small

Invoke-Command



This is the built-in help made by Microsoft for the command 'Invoke-Command', in PowerShell version 2 - as retrieved from Windows version 'Microsoft® Windows Vista™ Ultimate ' PowerShell help files on 2016-06-23.

For PowerShell version 3 and up, where you have Update-Help, this command was run just before creating the web pages from the help files.

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>] [-Cr
edential <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 | Negotia
te | NegotiateWithImplicitCredential | Credssp | Digest | Kerberos}] [-ConfigurationName <string>] [-Credential <PSCredential>] [-HideComputerNam
e] [-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>] [-Argument
List <Object[]>] [-InputObject <psobject>] [<CommonParameters>]
Invoke-Command [-FilePath] <string> [[-ConnectionURI] <Uri[]>] [-AllowRedirection] [-AsJob] [-Authentication {Default | Basic | Negotiate | Negot
iateWithImplicitCredential | Credssp | Digest | Kerberos}] [-ConfigurationName <string>] [-Credential <PSCredential>] [-HideComputerName] [-JobNa
me <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[]>] [-Inp
utObject <psobject>] [<CommonParameters>]



Search powershellhelp.space

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 I
nvoke-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 PSSes
sion (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 s
cript 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.



<

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



REMARKS

<

Examples


-------------------------- 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 "Domai
n01\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 run
s 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 variabl
e.

The second command uses the Invoke-Command cmdlet to run the Get-Culture command on Server02. It uses the Session parameter to specify the sessio
n 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 o
f 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 t
he 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 connectio
n 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 doe
s 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 s
ame 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 f
ourth and fifth commands repeat the series of commands used in the first set, but in this case, the Invoke-Command command uses the Session param
eter 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 us
e.








-------------------------- 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 "wi
ndows 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 com
puters 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 paramet
er 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 u
ses 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 th
e $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 th
e 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 rem
ote 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 va
riable.








-------------------------- 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 fr
om 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 pl
aceholders 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 placeho
lder 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 inc
ludes 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 a
ny 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 c
omputers. 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-M
ailbox 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 s
pecifies 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 th
e 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 SessionO
ption 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 retu
rns 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 paramete
r.

The second command uses the Invoke-Command cmdlet to run a Get-Hotfix command remotely. The value of the SessionOption parameter is the SessionOp
tion 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 co
mputer. 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 comput
er. 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 WS
Man: 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 act
ion 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.