Sunday, 29 March 2015

Execute Remote PowerShell Commands

We can run powershell commands on remote computer using the powershell cmdlet Invoke-Command.

Syntax of Invoke-Command:
Invoke-Command -ComputerName COMPUTER -ScriptBlock { COMMAND } -credential USERNAME
COMPUTER - The name of the computer to connect.
COMMAND - The powershell command to run in remote computer
USERNAME - The user account to run the command as on the remote computer. You will be prompted to enter a password for the username.

The below sample execute the command on the remote computer MCOM12, find the remote host name and display as output.
Invoke-Command -ComputerName MCOM12 -ScriptBlock { 'This command running on {0}.' -f (hostname) } -credential Morgan

Remote PowerShell Session

If you want to run series of PowerShell commands on a remote computer, you can start a remote PowerShell session for the particular remote computer using the Enter-PSSession cmdlet and then you can run multiple commands, instead of running a single command:
Enter-PSSession -ComputerName COMPUTER -Credential USER
The below sample command creates new session for the remote computer MCOM12.
Enter-PSSession -ComputerName MCOM12 -Credential Administrator
Execute Remote PowerShell Commands


No comments:

Post a Comment