Training
Get a free hour of SANS training

Experience SANS training through course previews.

Learn More
Learning Paths
Can't find what you are looking for?

Let us help.

Contact us
Resources
Join the SANS Community

Become a member for instant access to our free resources.

Sign Up
For Organizations
Interested in developing a training plan to fit your organization’s needs?

We're here to help.

Contact Us
Talk with an expert

Month of PowerShell - PowerShell Remoting, Part 2

We'll finish up our look at PowerShell remoting by examining several options to run PowerShell commands on multiple remote systems.

Authored byJoshua Wright
Joshua Wright

#monthofpowershell

In part 1, we looked at an overview of remote access using PowerShell, including the [code]Enter-PSSession[/code] 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:

In PowerShell, commands enclosed within curly braces [code]{}[/code] 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.

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 [code]Get-Process[/code] or [code]Get-Service[/code], and nothing is done with the script block. However, script blocks can be saved in a variable, then executed later using [code]Invoke-Command[/code]:

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 [code]$sb[/code] represents the script block in this example. Declaring a variable is not necessary though, since you can also run [code]Invoke-Command -ScriptBlock { Get-Process ; Get-Service }[/code] 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 [code]Enter-PSSession[/code], PowerShell supports [code]Invoke-Command[/code] with the [code]-ComputerName[/code] argument to run commands on a remote system. Using the same WS-Management protocol (and the same authentication and configuration requirements; see part 1), [code]Invoke-Command[/code] 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 [code]PSComputerName[/code] and [code]RunspaceId[/code] properties. These properties are added by [code]Invoke-Command[/code] 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 [code]Enter-PSSession[/code] 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 [code]Invoke-Command[/code], 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 [code]notepad[/code] 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 we created a variable [code]$notepadprocesses[/code], revealing that two hosts are running Notepad (FM-WEBDEV and FM-ALGORITHM). You might try to stop the processes using the pipeline and [code]Stop-Process[/code]:

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 [code]Stop-Process[/code] 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 [code]Invoke-Command[/code] 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 [code]New-PSSession[/code] that handles connection establishment, that we can reuse with [code]Invoke-Command -Session[/code]:

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 [code]Get-PSSession[/code]:

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 [code]Remove-PSSession[/code]:

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 [code]$programfiles[/code] in the first statement, and accessing it in the second statement to get a count of the number of objects in the [code]C:\Program Files (x86)[/code] directory on each of the systems. As long as the session is active, the variables declared are accessible in subsequent [code]Invoke-Command[/code] 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 [code]-FilePath[/code], scale the number of concurrent sessions beyond the default of 32 with [code]-ThrottleLimit[/code], specify alternate credentials with [code]-Credential[/code], run as task as a background job using [code]-AsJob[/code], 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.

Month of PowerShell - PowerShell Remoting, Part 2 | SANS Institute