Remote Command Execution with PowerShell

Posted by:

|

On:

|

PowerShell can become a lot more fun when you can effortlessly remote into nearly every system to manage them. There are a handful of ways this can be done. First, you can have an interactive session open with another device. If you want to perform repeatable work, you can make a script that is run remotely on one or more machines. It’s even possible to connect to non-Windows systems through PowerShell to manage settings or transfer files!

Enter-PsSession Remote Control

Using Enter-PsSession will bring you into a PowerShell session on the remote machine, provided the Windows Remote Management Service is on. It’s simply as if you opened PowerShell on the remote machine, so it’s not the best option for when two systems need interact with each other. However, it’s nice to use for a quick application install or network troubleshooting. When you type quit or close the window, your session will end, deleting any temporary data.

PowerShell
Enter-PsSession $computerName

There is a near-identical cmdlet for Azure environments, as well.

PowerShell
Enter-AzVM -Name $computerName -ResourceGroupName $ResourceGroupName 

Invoke-Command

Invoke-Command allows for you to run a script or script block on a remote machine. This is useful if there are more complex tasks that need to be handled, such as executing a runbook or an application install that needs to have specific files added before running. Ensure your execution policy allows for the scripts provided before running this on your fleet.

PowerShell
Invoke-Command -ComputerName $computerName -FilePath C:\scripts\myscript.ps1
Invoke-Command -ComputerName -ScriptBlock {
    winget install app
    Copy-Item \\share\settings.conf -Destination C:\app\settings
}

Other Command-Line Tools

It’s possible to use the SCP command to transfer files between devices, or the SSH command to remotely manage networking equipment or servers. This is not limited to Windows systems, you can remote into anything configure with the matching protocol, but depending on the environment you may need to tweak firewall rules or permissions.

Remote Enable RDP

Sometimes, you just want to do something graphically. If you’re unable to connect using the Remote Desktop Protocol, you can make a quick registry edit using PowerShell.

To make this change:

PowerShell
Set-ItemProperty -Path 'HKLM:\\System\CurrentControlSet\\Control\\Terminal Server' -name \"fDenyTSConnections\" -value 0

PowerShell Remoting is simple, since you’re just establishing connections with various devices. However, being comfortable in this will let you quickly check or modify settings without the hassle and scheduling it might require to screenshare or visit the device.