Introduction to PowerShell Remoting
Overview of PowerShell Remoting
PowerShell is a great scripting and automation tool — and it also enables administrators to execute commands and scripts on remote computers remotely, as if they were sitting in front of them. Indeed, early in the history of PowerShell, Microsoft added support for cmdlets to run on remote systems with the -ComputerName parameter.
Benefits and Use Cases for Remote Sessions
You can use the remote capabilities of PowerShell to manage multiple systems from a single workstation without physical access or remote desktop tools. For example, you can:
- Manage configuration settings on multiple servers.
- Monitor remote endpoints.
- Automate software updates and patch installations on an entire fleet of machines.
- Transfer files or synchronize data between remote systems.
- Manage virtual machines on platforms like Azure or VMware directly from PowerShell.
- Troubleshoot systems remotely to diagnose and resolve issues
- Manage backups on remote systems.
The benefits of this approach include:
- Reduced IT workload through automation of repetitive administrative tasks
- Fewer errors
- Easy scalability across hundreds or even thousands of machines
- Cross-platform functionality in Windows, Linux and macOS environments
Enabling PowerShell Remoting
Steps to Enable PowerShell Remoting
To run PowerShell remotely, you first need to make sure that ports5985 (HTTP) and 5986 (HTTPS) are open on the local firewall for WinRM communications.Thescreenshot below shows how to do this on a Windows Server 2022 machine using the Windows Defender firewall wizard:
Next, configure the computer to receive remote commands on the remote computer by running the Enable PSremoting. You can use the -Force to suppress all prompts during the execution of Enable-PSRemoting. This is necessary for automated scripts. An example is shown below:
Security Considerations and Configurations
To maintain strong security during remote management of computers, especially servers, follow these best practices:
- Always use HTTPS instead of HTTP to encrypt communications.
- Grant remote PowerShell abilities only to users who absolutely need it. By default, only members of the Administrators group can use PowerShell remoting.
- Implement Just Enough Administration (JEA) to limit user actions during a remote session.
- Regularly review event logs from PowerShell remoting sessions and investigate any suspicious activity.
Enabling Remoting in Workgroup vs. Domain Environments
Domain environments make the task of configuring PowerShell Remote easier. You can use Group Policy to enable WinRM and configure firewall rules across as many machines in your domain as necessary. Domain environments benefit from Kerberos authentication, which provides secure and seamless connectivity without additional configuration.
If your remote computers are in a workgroup environment, Kerberos is not available, so you must configure the TrustedHosts list on each machine to specify which computers can connect remotely. This is done using the following PowerShell command:
Set-Item WSMan:\localhost\Client\TrustedHosts -Value "RemoteComputerName"
You can use a wildcard (*) to allow connections from any computer, but use this option with due caution because of its impact on security.
Running Remote Commands
Using the Invoke Command cmdlet for Remote Execution
The Invoke-Command can manage up to 32 simultaneous connections by default, and you can extend that limit using the -ThrottleLimit parameter. This makes it an ideal command when you want to:
- Run commands or scripts on remote machines.
- Execute code on multiple computers simultaneously.
- Return output from remote executions, including errors.
The format for this command is as follows:
Invoke-Command -ComputerName <computers> -ScriptBlock { <commands> }
The ComputerName variable specifies target computers, while the ScriptBlock contains the commands you want to execute remotely.
Here is how to retrieve the Windows time service from a single remote computer:
Invoke-Command -ComputerName "Server01" -ScriptBlock { Get-Service -Name "W32Time"}
And here how to use Invoke-Command to get the time on two remote computers:
# Define the remote computers
$computers = "Server1", "Server2"
# Use Invoke-Command to run Get-Service on the remote computers
Invoke-Command -ComputerName $computers -ScriptBlock {
Get-Service -Name "W32Time"
}
Running Single vs. Multiple Remote Commands
In the examples above, we executed a single command (getting the time). Single command execution is ideal for quick, one-off tasks where establishing a persistent connection is unnecessary. But there are times when you want to run multiple commands. Multiple command execution is useful when running a sequence of commands that benefit from shared context or data, reducing overhead from repeatedly opening and closing connections.
The following script runs multiple commands on multiple remote computers:
Invoke-Command -ComputerName "Server1", "Server2" -ScriptBlock {
$os = Get-WmiObject -Class Win32_OperatingSystem
$hostname = $env:COMPUTERNAME
Write-Output "$hostname is running $($os.Caption)"
}
Example Commands for Common Remote Tasks
Restarting Servers
A common task that administrators must do is reboot a series of servers. This can easily be done using Invoke-Command in a PowerShell remote session:
Invoke-Command -ComputerName "Server1", "Server2" -ScriptBlock {
Restart-Computer -Force
}
For instance, suppose the spooler service is no longer running on a remote print server. You can start it remotely using the following command:
Invoke-Command -ComputerName "Server1" -ScriptBlock {
Start-Service -Name "Spooler"
}
Starting and Managing Remote Sessions
Initiating Interactive Sessions with Enter-PSSession
The Enter-PSSession cmdlet will start an interactive session with a remote computer, allowing you to execute commands as if you were working directly on the local computer. Once you’ve connected, any command you type runs directly on the remote system. Practical use cases include performing tasks such as checking system status, managing services or updating configurations directly on a remote server.
Below is an example of the cmdlet:
Enter-PSSession -ComputerName <RemoteComputerName> [-Credential
Note that only one interactive session can be active at a time. The session remains open until you explicitly close it by running Exit-PSSession.
Managing Multiple Sessions with New-PSSession
When running multiple commands frequently, it’s efficient to use persistent sessions. This is done using the New-PSSession cmdlet and then using the Session parameter of Invoke-Command. This approach maintains an open session, allowing multiple commands to be executed without the overhead of repeatedly establishing remote connections each time.
Below is an example:
# Create persistent sessions
$sessions = New-PSSession -ComputerName "Server1", "Server2"
# First command
Invoke-Command -Session $sessions -ScriptBlock {
Get-EventLog -LogName "System" -Newest 5
}
# Second command
Invoke-Command -Session $sessions -ScriptBlock {
Get-Process
}
# Close sessions
Remove-PSSession -Session $sessions
Best Practices for Session Persistence and Management
Here are some of the recommended best practices when using persistent sessions:
- Use persistent sessions for efficiency, as they reduce connection setup time and improve performance.
- Limit the number of concurrent sessions to avoid overwhelming the remote system.
- Always close sessions when tasks are complete to free up resources on both local and remote systems.
- Assign meaningful names to sessions to make them easier to manage, especially in scripts involving multiple remote systems.
- Regularly check for open sessions to prevent resource exhaustion.
Advanced Remoting Techniques
Creating and Configuring Customized Sessions
Administrators can create custom configurations that define the capabilities and restrictions for remote PowerShell sessions. These configurations can enhance security and productivity by enforcing the principle of least privilege and providing only necessary tools for specific tasks.
For example, you can create custom configurations to:
- Restrict access to sensitive cmdlets and data.
- Enforce policies tailored to specific roles or departments.
- Limit users to the subset of cmdlets relevant to their roles.
- Prevent execution of potentially harmful commands.
- Control which modules can be imported.
To create a custom session configuration:
- Use the New-PSSessionConfigurationFile cmdlet to create a configuration file.
- Register the configuration using Register-PSSessionConfiguration.
- Apply security settings to control who can use the configuration.
Using Remote Command Imports with Import-PSSession
Importing commands from a remote session into your current session using Import-PSSession enables you to use remote functionality locally. This is particularly useful for accessing modules or commands that are available only on remote machines. Here is an example:
$session = New-PSSession -ComputerName Server01
Import-PSSession -Session $session -Module ServerAdminTools -Prefix Remote
Configuring and Using the WSMan Provider
The WSMan (Web Services Management) provider in PowerShell allows you to manage and configure remote systems over the WS-Management protocol. This protocol allows administrators to configure, query, and troubleshoot remote computers and services that support WS-Management.
Key benefits of using WSMan include:
- Remote configuration and querying of WS-Management-enabled devices
- Access to a specialized PowerShell drive for managing local and remote system configurations
- Broad support for troubleshooting and administering remote computers and services
To access the WSMan provider on a remote machine, use the Connect-WSMan cmdlet to establish a connection to the remote computer’s WinRM service, as follows:
Connect-WSMan -ComputerName "Server01"
Troubleshooting PowerShell Remoting
Common Issues and Resolutions
Here are tips for resolving common issues with PowerShell remoting:
- Review the event log. For errors related to WinRM, navigate to Applications and Services Logs > Microsoft > Windows > Windows Remote Management.
- Check whether the firewall is blocking the necessary WinRM ports:
Test-NetConnection -ComputerName <RemoteComputerName> -Port 5985
If necessary, create a firewall rule to allow remote traffic:
New-NetFirewallRule -Name "Allow WinRM" -DisplayName "Allow WinRM" -Protocol TCP -LocalPort 5985,5986 -Action Allow
- Check whether the WinRM service is operational on the remote machine:
Test-WSMan -ComputerName "RemoteComputer"
If it is not, enable WinRM on the remote machine:
Enable-PSRemoting -Force
- Ensure that the SSL certificates on both the local and remote systems are valid and trusted.
Resources for Remote Troubleshooting
PowerShell can be intimidating at first, but there are many resources available to help you learn how to better leverage it and troubleshoot problems that occur. For example:
- Microsoft has lots of official documentation that provides detailed guidance on configuring and troubleshooting WinRM and PowerShell remoting.
- There are a variety of forums that provide community-driven solutions and discussions about common remoting issues. They include Stack Overflow, PowerShell.org and Reddit.
- If you suspect a bug or need help with a new feature, the PowerShell GitHub page can provide updates or fixes.
Conclusion
PowerShell remoting can definitely make your job as IT administrator easier. By enabling you to perform tasks across numerous machines simultaneously, it reduces the time and effort required for large-scale management operations. Running commands directly on remote systems minimizes network overhead and processing load on the querying host. And thanks to built-in security features such as Kerberos authentication and encrypted communications, PowerShell offers a more secure alternative to other traditional remote management methods.
If you want to learn more about PowerShell, Microsoft provides detailed information on configuration, usage, and best practices. There are also many online tutorials and guides, such as those found on websites like HowToGeek and ILovePowerShell, that provide step-by-step instructions for setting up and using PowerShell remoting. You can also find many great books to guide you.
FAQ
What is remote PowerShell used for?
PowerShell remoting allows users to execute PowerShell commands and scripts on remote Windows systems, which automates management and monitoring and facilitates troubleshooting. It is similar to SSH in other operating systems.
How do I run a PowerShell command remotely?
To run a PowerShell command remotely, you must ensure that PowerShell remoting is enabled on the remote computer and that WinRM is allowed through the firewall (if it is enabled).
You can then use the Invoke-Command cmdlet to execute a command on the remote computer. You may be prompted to provide the credentials of an admin account with PowerShell permissions.
How to enable remote PowerShell?
To enable remote PowerShell, open an elevated PowerShell session on the remote computer and run the following command to start the WinRM service:
Enable-PSRemoting -Force
How to start a remote PowerShell session?
Enable PowerShell remoting on the remote computer using the Enable-PSRemoting -Force cmdlet. Then start an interactive session using the Enter-PSSession cmdlet, as shown here:
Enter-PSSession -ComputerName RemoteComputerName -Credential (Get-Credential)
Can PowerShell be used remotely?
Yes. Administrators can run PowerShell cmdlets and scripts on remote machines across a network. This capability enables them to centrally manage, troubleshoot, configure and maintain systems. PowerShell remoting must be enabled on the machines and the admin must have appropriate permissions.
How do I enable remoting in PowerShell?
To enable PowerShell remoting on a computer, take the following steps:
- Run the Enable-PSRemoting -Force cmdlet on the remote computer.
- Configure Windows Firewall for WinRM.
- If the remote computer is in a workgroup, configure trusted hosts.
- Make sure your user account has the necessary administrative privileges.
What is PowerShell remoting?
PowerShell remoting enables administrators to run PowerShell commands and scripts on remote computers over a network. It enables them to manage configurations and perform other vital administrative tasks on distant machines without direct physical access.
Is it safe to enable PowerShell remoting?
Running PowerShell scripts remotely does introduces security risks. Administrators can mitigate these risks by implementing secure communication protocols like HTTPS or SSH, utilizing strong authentication methods such as Kerberos or certificates, and leveraging features like Just Enough Administration (JEA) to restrict user permissions and command access.
How to connect to PowerShell remotely?
Before connecting to a remote computer using PowerShell, you must ensure that PowerShell remoting is enabled on it. Open PowerShell with administrative privileges on the remote machine and run the following command:
Enable-PSRemoting -Force
If your computers are part of a workgroup rather than a domain, you also need to configure the TrustedHosts setting on both computers.
You can then initiate an interactive remote session using Enter-PSSession as shown here:
Enter-PSSession -ComputerName RemoteComputerName -Credential (Get-Credential)
Replace RemoteComputerName with the hostname or IP address of the remote system. When prompted, enter the username and password for the remote system. Once connected, the prompt will change to indicate the remote session.