In part 1, we looked at an overview of remote access using PowerShell, including the Enter-PSSession command and how you can use it (with authorization) to extend your PowerShell session to a new system.
This form of one-to-one PowerShell access is useful, but hardly scalable for interrogating or managing many systems. In this article we'll look at PowerShell remote access to one-to-many access.
About Script Blocks
Before we get into PowerShell remoting for multiple systems, it's important to understand the PowerShell script block syntax. From the documentation:
... a script block is a collection of statements or expressions that can be used as a single unit.
In PowerShell, commands enclosed within curly braces {} are declared but not immediately executed. Script blocks are the same syntax we use to declare a PowerShell function, where you can identify one or more commands (each on their own line or separated by semicolons) to execute as a group.
Think of a script block as an unnamed function. It's a collection of one or more commands that executes when told to do so.
For example, a script block might get a list of processes and a list of services:
PS C:\Users\Sec504> { Get-Process ; Get-Service } Get-Process ; Get-Service
In this manner the script block is not terribly useful; it does not execute Get-Process or Get-Service, and nothing is done with the script block. However, script blocks can be saved in a variable, then executed later using Invoke-Command:
PS C:\Users\Sec504> $sb = { Get-Process ; Get-Service } PS C:\Users\Sec504> Invoke-Command -ScriptBlock $sb Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName ------- ------ ----- ----- ------ -- -- ----------- 234 14 3824 24540 0.25 4812 1 conhost 102 7 6240 10788 5548 0 conhost 658 49 25284 66848 0.81 6300 1 Cortana ... 604 43 26756 22428 1.66 6340 1 YourPhone Status : Running Name : AarSvc_1cb93 DisplayName : AarSvc_1cb93 Status : Stopped Name : AJRouter DisplayName : AllJoyn Router Service ...
The variable $sb represents the script block in this example. Declaring a variable is not necessary though, since you can also run Invoke-Command -ScriptBlock { Get-Process ; Get-Service } to achieve the same result.
The documentation on script blocks is worth taking a look at, and there's more that can be done with script blocks including defining arguments to pass to the script block. Script blocks are essential for working with PowerShell one-to-many remoting though, as we'll see next.
Don't Make Me Come Over There, and There, and There
In addition to Enter-PSSession, PowerShell supports Invoke-Command with the -ComputerName argument to run commands on a remote system. Using the same WS-Management protocol (and the same authentication and configuration requirements; see part 1), Invoke-Command accepts a script block that is executed on the named system(s):
PS C:\Users\Sec504> Invoke-Command -ScriptBlock { Get-Process } -ComputerName FM-CEO Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName PSComputerName ------- ------ ----- ----- ------ -- -- ----------- -------------- 102 7 6220 10788 0.00 4952 0 conhost FM-CEO 236 13 3856 24652 0.23 5880 1 conhost FM-CEO ...
Within the script block you can still use all of the PowerShell pipeline features:
PS C:\Users\Sec504> Invoke-Command -ScriptBlock { Get-Process | Where-Object -Property Name -EQ 'lsass' | Select-Object -Property Name, ID, PSComputerName } -ComputerName FM-CEO Name : lsass Id : 704 PSComputerName : FM-CEO RunspaceId : 8048efaa-c9b8-4cc6-a05b-9c667b76279f
Notice how the return object includes the PSComputerName and RunspaceId properties. These properties are added by Invoke-Command after the script block is executed. If you don't want one or all of these properties in your output, filter the response after the script block:
PS C:\Users\Sec504> Invoke-Command -ScriptBlock { Get-Process | Where-Object -Property Name -EQ 'lsass' | Select-Object -Property Name, ID } -ComputerName FM-CEO | Select-Object -Property Name, Id, PSComputerName Name Id PSComputerName ---- -- -------------- lsass 704 FM-CEO
This works great, but isn't immediately advantageous over Enter-PSSession when working with a single system. However, you can specify a comma-separated list of multiple systems to run the script block:
PS C:\Users\Sec504> Invoke-Command -ScriptBlock { Get-Process | Where-Object -Property Name -EQ 'lsass' | Select-Object -Property Name, ID } -ComputerName FM-CEO, FM-WEBDEV, FM-GOLF, FM-ALGORITHM Name : lsass Id : 704 PSComputerName : FM-CEO RunspaceId : 199cb838-d1c5-43b1-a155-cd1b78025e7f Name : lsass Id : 680 PSComputerName : FM-WEBDEV RunspaceId : 2d1e05ba-4fdc-4010-9c49-e5e5eeb5b5a8 Name : lsass Id : 680 PSComputerName : FM-GOLF RunspaceId : 146813ae-5059-4b89-9331-317a45c045b1 Name : lsass Id : 684 PSComputerName : FM-ALGORITHM RunspaceId : 6ca5d060-bddf-4dd2-abbc-23bdd03a6efb
This works great, and it's easy to extend this to run more complex PowerShell commands as well: just keep the commands you want to run inside the script block. However, there are a few added considerations to keep in mind.
Inert Objects
When you use a script block and obtain the results back to your host system with Invoke-Command, the result objects are considered inert. That is, you can read them, but you can't act upon them anymore. For example, let's say you want to interrogate the four systems FM-CEO, FM-WEBDEV, FM-GOLF, and FM-ALGORITHM for the notepad process:
PS C:\Users\Sec504> $notepadprocesses = Invoke-Command -ScriptBlock { Get-Process notepad } -ComputerName FM-CEO, FM-WEBDEV, FM-GOLF, FM-ALGORITHM -ErrorAction SilentlyContinue PS C:\Users\Sec504> $notepadprocesses Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName PSComputerName ------- ------ ----- ----- ------ -- -- ----------- -------------- 239 13 2764 21588 0.08 2180 1 notepad FM-WEBDEV 237 13 2768 21392 0.09 6212 1 notepad FM-ALGORITHM
Here I've added -ErrorAction SilentlyContinue to prevent the command from displaying an error when Notepad is not running on one or more of the target systems.
Here we created a variable $notepadprocesses, revealing that two hosts are running Notepad (FM-WEBDEV and FM-ALGORITHM). You might try to stop the processes using the pipeline and Stop-Process:
PS C:\Users\Sec504> $notepadprocesses | Stop-Process Stop-Process : Cannot find a process with the process identifier 2180. At line:1 char:21 + $notepadprocesses | Stop-Process + ~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (2180:Int32) [Stop-Process], ProcessCommandE xception + FullyQualifiedErrorId : NoProcessFoundForGivenId,Microsoft.PowerShell.Commands.StopP rocessCommand Stop-Process : Cannot find a process with the process identifier 6212. At line:1 char:21 + $notepadprocesses | Stop-Process + ~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (6212:Int32) [Stop-Process], ProcessCommandE xception + FullyQualifiedErrorId : NoProcessFoundForGivenId,Microsoft.PowerShell.Commands.StopP rocessCommand
This doesn't work because you are executing Stop-Process on the local system, not on the remote system.
You can interrogate and stop processes on a remote system, but you have to follow one rule: keep it in the script block. The commands in the script block are the only ones that execute on the remote system, but we can use the pipeline there as desired:
PS C:\Users\Sec504> Invoke-Command -ScriptBlock { Get-Process notepad | Stop-Process } -ComputerName FM-CEO, FM-WEBDEV, FM-GOLF, FM-ALGORITHM -ErrorAction SilentlyContinue PS C:\Users\Sec504>
Success!
Optimizing Sessions
When you run Invoke-Command you create a PowerShell remote session. This requires that you establish a connection, authenticate, deliver the commands, execute the commands, collect the results, transfer the resultrs back to the invoking system, and terminate the connection. This is convenient if you intend to only run one script block of commands on the remote system(s), but it's a lot of overhead if you want to run several script blocks one or more times against the same systems.
Fortunately, PowerShell allows us to establish a session with New-PSSession that handles connection establishment, that we can reuse with Invoke-Command -Session:
PS C:\WINDOWS\system32> $mysession = New-PSSession -ComputerName FM-CEO, FM-WEBDEV, FM-GOLF, FM-ALGORITHM PS C:\WINDOWS\system32> Invoke-Command -Session $mysession -ScriptBlock { Get-WinEvent -FilterHashTable @{ LogName = 'System'; Id=7034 } } | Select-Object -Property TimeCreated, PSComputerName, Message TimeCreated PSComputerName Message ----------- -------------- ------- 7/20/2022 2:33:06 AM FM-CEO The Microsoft eDynamics Service service terminated u... 7/20/2022 2:26:50 AM FM-CEO The Microsoft eDynamics Service service terminated u... 7/20/2022 2:23:03 AM FM-CEO The Microsoft eDynamics Service service terminated u... 7/20/2022 2:37:46 AM FM-WEBDEV The Microsoft eDynamics Service service terminated u... 7/20/2022 2:38:03 AM FM-GOLF The Microsoft eDynamics Service service terminated u... 7/20/2022 2:26:59 AM FM-WEBDEV The Microsoft eDynamics Service service terminated u... 7/20/2022 2:27:04 AM FM-GOLF The Microsoft eDynamics Service service terminated u... 7/20/2022 2:22:27 AM FM-GOLF The Microsoft eDynamics Service service terminated u... 7/20/2022 2:22:32 AM FM-WEBDEV The Microsoft eDynamics Service service terminated u... 7/20/2022 2:38:21 AM FM-ALGORITHM The Microsoft eDynamics Service service terminated u... 7/20/2022 2:27:09 AM FM-ALGORITHM The Microsoft eDynamics Service service terminated u... 7/20/2022 2:22:24 AM FM-ALGORITHM The Microsoft eDynamics Service service terminated u...
A session is established for each remote system connection. You can identify them with Get-PSSession:
PS C:\WINDOWS\system32> Get-PSSession Id Name ComputerName ComputerType State -- ---- ------------ ------------ ----- 1 WinRM1 FM-CEO RemoteMachine Opened 2 WinRM2 FM-WEBDEV RemoteMachine Opened 3 WinRM3 FM-GOLF RemoteMachine Opened 4 WinRM4 FM-ALGORITHM RemoteMachine Opened
You can close sessions with Remove-PSSession:
PS C:\WINDOWS\system32> Get-PSSession | Remove-PSSession PS C:\WINDOWS\system32> Get-PSSession PS C:\WINDOWS\system32>
One nice thing about using a session is that you can declare variables in the session, and access them for the duration of the session:
PS C:\WINDOWS\system32> Invoke-Command -Session $mysession -ScriptBlock { $programfiles = Get-ChildItem -Path 'C:\Program Files (x86)' } PS C:\WINDOWS\system32> Invoke-Command -Session $mysession -ScriptBlock { $programfiles.count } 28 20 43 22
Here I'm declaring a variable $programfiles in the first statement, and accessing it in the second statement to get a count of the number of objects in the C:\Program Files (x86) directory on each of the systems. As long as the session is active, the variables declared are accessible in subsequent Invoke-Command script blocks.
Conclusion
The documentation for Invoke-Command is worth reviewing to best leverage this PowerShell feature. Other great options include the ability to run local scripts on the remote system(s) with -FilePath, scale the number of concurrent sessions beyond the default of 32 with -ThrottleLimit, specify alternate credentials with -Credential, run as task as a background job using -AsJob, and much more!
We're nearing the end of the #monthofpowershell, but I hope you can see how this concept can be applied to lots of different threat hunting, incident response, and administration tasks. Tomorrow is our last article for the month, and we'll be taking a detour from our normal focus to look at opportunities to accelerate your operational use of PowerShell.
-Joshua Wright
Return to Getting Started With PowerShell
Joshua Wright is the author of SANS SEC504: Hacker Tools, Techniques, and Incident Handling, a faculty fellow for the SANS Institute, and a senior technical director at Counter Hack.