Using remote PowerShell commands is a great way to manage servers.
I have been spending more time using Windows 2012 Server Core which makes using
remote tools essential. Instead of connecting using Remote Desktop, I try to do
everything using PowerShell remotely. In this post, I will show off some
extremely basic remote PowerShell commands, Enter-PSSession and
Invoke-Command.
Let’s start with a simple command:
Enter-PSSession -ComputerName 'Target'This amazing command uses your current PowerShell prompt to run PowerShell
commands interactively on the remote computer, “Target”. When you
are done type exit. With this command you now have the complete
might of a fully operational PowerShell!
You can run single or multiple commands using
Invoke-Command. Unlike Enter-PSSession, this command is not interactive
and will still stream results back to your current prompt. This is great for
one line commands like restarting IIS on the remote server “Target”:
Invoke-Command -ComputerName 'Target' -ScriptBlock { iisreset }Remote commands are allowed by default on Windows Server 2012 and beyond.
On older operating systems you can run Enabled-PSRemoting -Force from
an Administrator PowerShell prompt on the target machine to enable remoting. You can
then test the connection by running the following from another computer:
Invoke-Command -ComputerName 'Target' -ScriptBlock { echo 'hello' }There are many other commands which natively support remote operations.
These commands will often have a ComputerName parameter. You can see a list
of commands with the ComputerName parameter by using:
Get-Command -ParameterName 'ComputerName'Among my favourites is Get-EventLog. It is a great way to look at messages
from a remote server without ever leaving the terminal. This example
retrieves, formats and displays the last 5 error messages from the remote
server “Target”:
Get-EventLog -ComputerName 'Target' -LogName 'Application' -Newest 5 -EntryType 'Error' `
| Format-List TimeWritten, Message `
| moreI hope you liked this mini intro to PowerShell remoting. Now go run some commands!