PowerShell Remoting
You can run commands on one or hundreds of computers with a single PowerShell command. Windows PowerShell supports remote computing by using various technologies, including WMI, RPC, and WS-Management
Verify if we can execute remote commands:
The
Invoke-Commandcmdlet runs commands on a local or remote computer and returns all output from the commands, including errors. Using a singleInvoke-Commandcommand, you can run commands on multiple computers.
Invoke-Command -ScriptBlock {whoami;hostname} -ComputerName dcorp-mgmt$sess = New-PSSession -ComputerName dcorp-mgmt.dollarcorp.moneycorp.localInvoke-command -ScriptBlock{Set-MpPreference -DisableIOAVProtection $true} -Session $sessInvoke-command -ScriptBlock ${function:Invoke-Mimi} -Session $sessRun a script on a server:
Invoke-Command -FilePath c:\scripts\rfs.ps1 -ComputerName Server01Run a single command on several computers
$parameters = @{
ComputerName = 'Server01', 'Server02', 'TST-0143', 'localhost'
ConfigurationName = 'MySession.PowerShell'
ScriptBlock = { Get-WinEvent -LogName PowerShellCore/Operational }
}
Invoke-Command @parametersExplanation of PowerShell Commands
Executing Remote Commands with Invoke-Command
The Invoke-Command cmdlet in PowerShell is a versatile command used to execute scripts and commands on both local and remote systems. Here is how it works:
To run commands on a single remote computer, you use
Invoke-Commandwith the-ComputerNameparameter:Invoke-Command -ScriptBlock {whoami; hostname} -ComputerName dcorp-mgmtThis will execute the
whoamiandhostnamecommands on the remote computer nameddcorp-mgmt.For establishing a persistent connection to a remote computer, you can create a PowerShell session (PSSession):
$sess = New-PSSession -ComputerName dcorp-mgmt.dollarcorp.moneycorp.localThe variable
$sessstores the PSSession for the target computerdcorp-mgmt.dollarcorp.moneycorp.local.You can then run commands in that session using
Invoke-Command:Invoke-command -ScriptBlock {Set-MpPreference -DisableIOAVProtection $true} -Session $sessThis command modifies the antivirus preferences on the remote computer, utilizing the previously established session
$sess.To invoke custom functions or scripts that are defined locally on your computer on a remote session, you wrap the function name within
${function:FunctionName}:Invoke-command -ScriptBlock ${function:Invoke-Mimi} -Session $sessHere,
Invoke-Mimiis presumably a custom or imported function that is being called remotely via$sess.
Running a Script on a Remote Server
To execute a local script on a remote machine using
Invoke-Command, the-FilePathparameter can be used along with the-ComputerName:Invoke-Command -FilePath c:\scripts\rfs.ps1 -ComputerName Server01This runs the script
rfs.ps1that is located atc:\scriptsonServer01.
Running Commands on Multiple
Last updated
Was this helpful?