Admin Power Level: Intermediate Chapter 10: Run Commands on Other Computers
Invoke-Command: run a command remotely
Invoke-Command sends a script block to one or more computers, runs it there, and returns the results as objects. The work happens on the remote computer, not yours.
Lesson 1 of 2 in Chapter 10: Run Commands on Other Computers. Previous step in this path: Iteration: for, while, and foreach. 3 learning objectives, 9 examples, and a knowledge check.
Start: what you will learn
Invoke-Command sends a script block to one or more computers, runs it there, and returns the results as objects. The work happens on the remote computer, not yours.
Learning objectives
- Explain what Invoke-Command does
- Run a command on a named computer
- Explain why returned objects can differ from local objects
Concept in simple words
What it is: Invoke-Command is a command that sends a script block, which is a small block of code in braces, to one or more remote computers, runs it there, and brings the results back to you. The script block is the work order. The remote computer does the work. Your computer only sends the order and shows the answer.
Why it works
Why it exists: Imagine you look after ten computers, and you need to check the same service on every one of them. Walking to each computer, signing in, and typing the same check ten times is slow, and it is easy to miss one. Remoting solves that problem. You type the check once, PowerShell sends it to every computer you name, and you collect all the answers in one place.
Think of it like this
Think of it like this: Invoke-Command is like sending the same short note to several friends and asking each one to check something at home and report back. You write the note once, each friend does the work where they are, and you collect all the answers in one place. The note is the script block. Each friend is a remote computer. The report back is the returned result.
What WinRM does behind the command: Remoting uses WinRM, which is the Windows Remote Management service. WinRM carries your command from your computer to the remote computer, and it carries the results back again. Think of WinRM as the delivery road between the two computers. If the road is closed, or if the remote computer does not accept your identity, no command can travel, and that is a setup problem, not a problem with the command itself.
Safety first, stated plainly: Use remoting only on computers you own or manage, and only with permission. That means your own computers and your own lab computers. Never run commands on a computer you do not own or manage, and never use remoting to look at, change, or take anything from someone else computer. Permission is not a detail here. It is the whole point of the login check that follows.
Before you start, check three things: First, do you have the exact computer name, spelled correctly. Second, do you have an account that is allowed to run commands on that computer. Third, is remoting turned on on that computer. If any one of these three is missing, the command will fail, and the fix is in the setup, not in typing the command louder or faster.
How remoting is turned on: On the remote computer, in an elevated PowerShell window, an admin runs Enable-PSRemoting -Force. That command starts the WinRM service, sets it to start automatically, creates a listener that waits for remote requests, and opens the firewall rule that lets WinRM traffic in. You only do this on a computer you own or manage, and you only do it when you have permission to change that computer. Do not turn remoting on on a shared or borrowed computer just to practise.
How it works, step by step
Step one, test the road: Run Test-WSMan -ComputerName srv1, where Test-WSMan tests whether WinRM answers on srv1. A successful answer means WinRM is listening and reachable. A failure means you must stop and fix the setup first. A failed test can point to a wrong name, a computer that is off or unreachable, WinRM not running, or a firewall blocking the traffic. Fix the cause, then test again, before you run a real command.
Step two, know the ports in plain words: WinRM normally uses port 5985 for HTTP traffic and port 5986 for HTTPS traffic. You do not need to memorise these numbers for every task, but they help you read a firewall problem. If a firewall blocks port 5985, WinRM traffic cannot get through, even when the service is running. A check such as Test-NetConnection -ComputerName srv1 -Port 5985 tests whether that road is open, and it is a read only check, so it changes nothing.
The anatomy of the command: Invoke-Command -ComputerName srv1 -ScriptBlock { Get-Service -Name Spooler } has three clear parts. Invoke-Command is the cmdlet that does the sending. -ComputerName srv1 names the target computer, and you can list several computers there, separated by commas. -ScriptBlock { Get-Service -Name Spooler } holds the code to run on the remote computer, inside braces. Everything inside the braces runs remotely. Everything outside the braces is your local command that sends it.
The boundary matters: The braces draw a line between your computer and the remote computer. Code inside the braces sees the remote computer, its services, its files, and its settings. Code outside the braces sees only your computer. That is why a variable you set on your computer does not magically exist inside the braces. The remote computer never saw it, because it was never sent.
Let us walk through the single computer example, part by part: Invoke-Command -ComputerName srv1 -ScriptBlock { Get-Service -Name Spooler } starts on your computer, but Get-Service runs on srv1, not on yours. Get-Service reads the service list on srv1. -Name Spooler narrows that list to the print spooler service. Only the result travels back to you. In the output, look for the Status column first, because it tells you whether the service is Running or Stopped, and then look for the Name column, because it confirms you are looking at Spooler and not at a different service.
Let us walk through the two computer example, part by part: Invoke-Command -ComputerName srv1, srv2 -ScriptBlock { Get-Service -Name Spooler | Select-Object Name, Status } lists two targets after -ComputerName, separated by a comma, so the same block runs on both. Inside the block, Get-Service -Name Spooler reads the Spooler service on each remote computer, and Select-Object Name, Status keeps only those two properties. The results also carry a PSComputerName property, which tells you which computer each result came from, so always check that column when you run one command on several computers. Do not assume the answers arrive in the same order you listed the computers. Read PSComputerName, and you will never mix up the answers.
What comes back is a snapshot, not a live object: The returned objects are deserialised, which means PowerShell turns the live remote object into a travelling copy, sends the copy, and rebuilds it on your computer. The rebuilt copy keeps its properties, the facts about it, such as Name and Status, but it loses most of its methods, the actions it could do. That is because an action would need to run on the remote computer, and the copy on your computer has no live link back to it. Only simple methods such as ToString remain, and you should treat the returned object as a report, not as a remote control.
The snapshot trap, in plain words: If you pipe a returned service object into Stop-Service on your own computer, that Stop-Service runs locally, on your computer, not on the remote computer. It reads the Name from the snapshot and acts on a service with that name where it is running, which is your computer. That is a dangerous mistake. If you want to stop a service remotely, put the stopping command inside the script block, so the action runs where the service lives. Always ask, where is this part of the pipeline running, before you run a command that changes something.
Local variables do not travel on their own: Suppose you set $serviceName = Spooler on your computer, and then you write a script block that uses $serviceName inside the braces. The remote computer will not know that value, because local variables do not travel automatically. The remote computer has its own session, with its own variables, and your local variable was never sent. The result is an empty or missing value, not an error that clearly says you forgot to send it, so this mistake is easy to miss.
How to send a local value, method one, the using scope: Write $using:serviceName inside the script block, where $using: tells PowerShell that this variable comes from your local session. PowerShell copies the current value of the local variable when it sends the command, and the remote computer uses that copied value. Change the local variable after you send the command, and the already sent copy does not change, because the copy was made at send time. This is the simplest way to send one local value into a remote command.
How to send a local value, method two, an argument list: Use -ArgumentList to pass values, and a param block inside the script block to receive them. For example, -ArgumentList Spooler passes the word Spooler as an argument, and param($name) inside the block stores it in $name for the code in the block to use. This method is clearer when you pass several values, because each value has a named place, and the order of the arguments must match the order of the param names.
One command, one fresh connection: When you use -ComputerName, PowerShell makes a temporary connection for that command, runs the block, returns the results, and then lets the connection go. A variable you set inside one such command does not survive into the next Invoke-Command call, because the next call starts fresh. That is fine for single checks, but it is the wrong tool when several commands need to share data.
When several commands must share data, use a persistent session: Create a session once with $s = New-PSSession -ComputerName srv1, which stores the session object in $s. Then run Invoke-Command -Session $s -ScriptBlock { $check = Get-Service -Name Spooler } to set $check inside that session, and run Invoke-Command -Session $s -ScriptBlock { $check.Status } to read the same $check in the same session. The second command works because both commands ran in the same persistent session, not in two fresh connections. When you are done, close the session with Remove-PSSession -Session $s, so you do not leave a connection open for no reason.
Credentials, in plain words: If your current account is not enough on the remote computer, add -Credential (Get-Credential) to the command. Get-Credential opens a prompt that asks for a user name and password, and PowerShell uses those credentials for the remote connection. Type the password only into that prompt. Never write a password as plain text inside a script or a script block, and never share a password with another person to make a remote command work. If you are unsure which account to use, stop and ask the person who manages the computer, instead of guessing.
Filter where the data lives: You can filter inside the script block, or after the results come back. Filtering inside the block, for example by selecting only Name and Status on the remote computer, sends less data back over the network, and it is faster when the remote list is long. Filtering after the results come back happens on your computer, and it is fine for a small result, but it means the full result had to travel first. As a habit, filter remotely when you only need a small part of a large remote list.
Reading an error, step by step: A connection error usually points to WinRM, the firewall, the computer name, or the computer being unreachable. A permission error usually points to the account, because WinRM answered, but your account was not allowed to run the command. Do not treat both errors the same way. A connection error asks you to check the road. A permission error asks you to check the account and the permission. Guessing the wrong fix wastes time and can open a setting that should stay closed.
A warning about trusted hosts: In a workgroup, where computers are not in a shared domain, you may need to add a remote computer to a trusted hosts list before the connection is accepted. If you ever do this, name only the exact computers you own or manage, one by one. Never use a wildcard star that trusts every computer, because that removes the safety check for every computer at once. A shortcut that trusts everyone is not a fix. It is a hole.
When to use it
When to use it, and when not to: Use Invoke-Command when you need to run one command, or the same short check, on one or many computers, and when you do not need to explore step by step. Do not use it when you need to try things, look at a result, and then decide the next step, because an interactive session fits that exploring style much better. Do not use it on a computer where you have not checked WinRM and permissions first, and do not use it for a changing command until you have first run a read only check and confirmed the target computer.
Worked examples
Read each example in order. Each one explains its parts, then shows what to look for in the output.
Syntax
Invoke-Command -ComputerName <Computer> -ScriptBlock { <command> }Example 1
Checks that WinRM answers on srv1. Fix remoting setup here, before you run real commands.
Test-WSMan -ComputerName srv1Illustrative output: ProductVersion: OS: 0.0.0 SP: 0.0 Stack: 3.0
Example 2
Runs on srv1, returns the service object to your console. Get-Service runs remotely, inside the braces, and only the result travels back.
Invoke-Command -ComputerName srv1 -ScriptBlock { Get-Service -Name Spooler }Illustrative output: Status Name ------ ---- Running Spooler
Example 3
-ComputerName srv1, srv2 lists two target computers, separated by a comma, so the same block runs on both. Inside the block, Get-Service -Name Spooler reads the Spooler service on each remote computer, and Select-Object Name, Status keeps only those two properties. The results also carry a PSComputerName property, which tells you which computer each result came from, so check that column to tell the two answers apart.
Invoke-Command -ComputerName srv1, srv2 -ScriptBlock { Get-Service -Name Spooler | Select-Object Name, Status }Illustrative output: Name Status PSComputerName ---- ------ -------------- Spooler Running srv1 Spooler Running srv2
Example 4
The first line sets $serviceName on your computer. The second line sends the command, and $using:serviceName copies that local value into the remote block, so the remote computer can use it. Without $using:, the remote computer would not know the value.
$serviceName = 'Spooler'
Invoke-Command -ComputerName srv1 -ScriptBlock { Get-Service -Name $using:serviceName }Illustrative output: Status Name PSComputerName ------ ---- -------------- Running Spooler srv1
Example 5
-ArgumentList passes the word Spooler into the block. Inside the block, param($name) receives it as $name, and Get-Service -Name $name uses it. This is the clearest method when you pass several values, because each argument has a named place.
Invoke-Command -ComputerName srv1 -ArgumentList 'Spooler' -ScriptBlock { param($name) Get-Service -Name $name }Illustrative output: Status Name PSComputerName ------ ---- -------------- Running Spooler srv1
Example 6
The first line creates a persistent session and stores it in $s. The second line sets $check inside that session. The third line reads the same $check, which works only because both commands used the same session. The last line closes the session when you are done.
$s = New-PSSession -ComputerName srv1
Invoke-Command -Session $s -ScriptBlock { $check = Get-Service -Name Spooler }
Invoke-Command -Session $s -ScriptBlock { $check.Status }
Remove-PSSession -Session $sIllustrative output: Running
Example 7
-Credential (Get-Credential) opens a prompt for a user name and password, and uses those credentials for the remote connection. Type the password only into that prompt, never as plain text in a script.
Invoke-Command -ComputerName srv1 -Credential (Get-Credential) -ScriptBlock { Get-Service -Name Spooler }Illustrative output: Status Name PSComputerName ------ ---- -------------- Running Spooler srv1
Example 8
The filtering inside the braces runs on srv1, so only running services travel back. Where-Object keeps services whose Status equals Running, and Select-Object keeps only Name and Status. Filtering remotely sends less data than bringing the full list home and filtering afterwards.
Invoke-Command -ComputerName srv1 -ScriptBlock { Get-Service | Where-Object { $_.Status -eq 'Running' } | Select-Object Name, Status }Illustrative output: Name Status PSComputerName ---- ------ -------------- Spooler Running srv1
Example 9
Here the pipe after Invoke-Command runs on your computer, after the result has come back. Select-Object keeps Name, Status, and PSComputerName from the returned snapshot. Compare this with the previous example, where the filtering ran remotely, inside the braces.
Invoke-Command -ComputerName srv1 -ScriptBlock { Get-Service -Name Spooler } | Select-Object Name, Status, PSComputerNameIllustrative output: Name Status PSComputerName ---- ------ -------------- Spooler Running srv1
Nothing on this page executes PowerShell code. The outputs above are illustrative only.
Diagram
Choose a stage above to see what it does.
Common mistakes and troubleshooting
Read these before you try the examples, so you can spot the same problems in your own work.
- Assuming a returned object still has its methods. Deserialised objects keep properties, not live methods.
- Running remoting commands without checking permissions and WinRM setup first, then blaming the command.
- Putting a local variable directly inside the script block and expecting the remote computer to know its value, when it does not, because local variables do not travel automatically, so pass the value in explicitly or define it inside the block.
- Expecting a variable set in one Invoke-Command call with -ComputerName to exist in the next call. Each such call starts fresh, so use a persistent session with -Session when commands must share data.
- Piping a returned service object into a changing cmdlet on your own computer, such as Stop-Service, and acting on your own computer by mistake. Put the changing action inside the script block, so it runs where the service lives.
- Forgetting to check PSComputerName when the same command runs on several computers, and then mixing up which answer came from which computer.
- Thinking a successful Test-WSMan answer proves you have permission to run a command. Test-WSMan only proves WinRM answers. A permission error can still follow, and it points to the account, not to the road.
- Adding a wildcard star to a trusted hosts list, which trusts every computer at once. Name only the exact computers you own or manage, one by one.
- Writing a password as plain text in a script or a script block. Use Get-Credential, type the password only into its prompt, and never share it.
Knowledge check
Knowledge check
Where does the script block in Invoke-Command run?
Pick one answer. Feedback appears right away, and you can try again.
Remember this and next step
Remember this: Invoke-Command runs your code where the data lives, on the remote computer, and returns the results to you, so one command can do the work on many computers at once. The braces mark the boundary. Inside the braces is remote. Outside the braces is local. Returned objects are snapshots with properties, not live controls. Local values only travel when you send them with $using: or with -ArgumentList, and a variable only survives between commands when you use a persistent session. Check the target, check PSComputerName, and work only on computers you own or manage, with permission.