0
0
PowershellHow-ToBeginner · 4 min read

How to Use Invoke-Command in PowerShell: Syntax and Examples

Use Invoke-Command in PowerShell to run commands locally or on remote computers by specifying the -ScriptBlock and optionally the -ComputerName. It lets you execute scripts or commands on one or many machines easily and securely.
📐

Syntax

The basic syntax of Invoke-Command includes specifying the command or script block to run and optionally the target computer(s).

  • -ScriptBlock: The commands or script to run.
  • -ComputerName: The remote computer(s) where the command runs.
  • -Credential: Optional user credentials for remote access.
  • -Session: Use an existing session for repeated commands.
  • -ArgumentList: Passes arguments to the script block.
powershell
Invoke-Command -ScriptBlock { <commands> } [-ComputerName <string[]>] [-Credential <PSCredential>] [-Session <PSSession>] [-ArgumentList <Object[]>]
💻

Example

This example runs a simple command locally and then remotely on a computer named 'Server01'. It shows how to get the current date and time.

powershell
Invoke-Command -ScriptBlock { Get-Date }

Invoke-Command -ComputerName Server01 -ScriptBlock { Get-Date }
Output
Monday, June 10, 2024 10:15:30 AM Monday, June 10, 2024 10:15:32 AM
⚠️

Common Pitfalls

Common mistakes include:

  • Not enabling PowerShell remoting on the remote machine (Enable-PSRemoting must be run).
  • Using incorrect credentials or missing -Credential when required.
  • Trying to run commands on remote computers without network access or firewall exceptions.
  • Forgetting that Invoke-Command runs in a different session, so variables from your local session are not available remotely.
powershell
## Wrong: Trying to use local variables remotely without passing them
$localVar = "Hello"
Invoke-Command -ComputerName Server01 -ScriptBlock { Write-Output $localVar }

## Right: Pass local variables using the -ArgumentList parameter
$localVar = "Hello"
Invoke-Command -ComputerName Server01 -ScriptBlock { param($msg) Write-Output $msg } -ArgumentList $localVar
Output
## Wrong: No output or error about variable not found ## Right: Hello
📊

Quick Reference

ParameterDescription
-ScriptBlockDefines the commands or script to run.
-ComputerNameSpecifies remote computer(s) to run the command on.
-CredentialProvides user credentials for remote access.
-SessionUses an existing PowerShell session for commands.
-ArgumentListPasses arguments to the script block.

Key Takeaways

Invoke-Command runs commands locally or remotely using a script block.
Always enable PowerShell remoting on remote machines before use.
Use -Credential to provide credentials when accessing remote computers.
Pass local variables to remote sessions with -ArgumentList and param().
Check network and firewall settings to allow remote command execution.