0
0
PowerShellscripting~5 mins

Invoke-Command in PowerShell

Choose your learning style9 modes available
Introduction

Invoke-Command lets you run commands on one or many computers from your own computer. It helps you control other machines easily without logging into each one.

You want to check the disk space on several computers at once.
You need to restart a service on remote servers quickly.
You want to gather system information from multiple machines.
You need to run a script on a remote computer without opening a remote session.
You want to automate tasks across many computers in your network.
Syntax
PowerShell
Invoke-Command -ComputerName <string[]> -ScriptBlock { <commands> } [-Credential <PSCredential>] [-ArgumentList <object[]>]

-ComputerName specifies the target computers.

-ScriptBlock contains the commands to run remotely.

Examples
Runs Get-Process on the computer named Server01.
PowerShell
Invoke-Command -ComputerName Server01 -ScriptBlock { Get-Process }
Runs Get-Service on two computers: Server01 and Server02.
PowerShell
Invoke-Command -ComputerName Server01, Server02 -ScriptBlock { Get-Service }
Passes 'Alice' as a parameter to the script block and prints a greeting on Server01.
PowerShell
Invoke-Command -ComputerName Server01 -ScriptBlock { param($name) Write-Output "Hello, $name" } -ArgumentList 'Alice'
Sample Program

This runs the Get-Date command on your own computer (localhost) and shows the current date and time.

PowerShell
Invoke-Command -ComputerName localhost -ScriptBlock { Get-Date }
OutputSuccess
Important Notes

You can run commands on your own computer by using localhost as the computer name.

Make sure remote computers allow remote commands (PowerShell Remoting must be enabled).

Use -Credential to provide a username and password if needed.

Summary

Invoke-Command runs commands on remote or local computers easily.

It helps automate tasks across many machines without manual login.

Use -ComputerName and -ScriptBlock to specify where and what to run.