A session is required to execute PowerShell commands or scripts on a remote computer. A PowerShell session is also known as PowerShell remoting, and it is just like an SSH session to an operating system. There are several ways to create a PowerShell session. I'll list one of the easiest methods here. These steps work on Windows 10, Windows 11, and also on Windows Server.
Step 1. Enabling PowerShell Remoting
Open the PowerShell with administrative privileges on the remote computer and execute the following command:
Enable-PSRemoting -Force
This command starts the WinRM service and creates a firewall rule to allow incoming connections. The -force option prevents PowerShell from prompting you for confirmation at each step.
Step 2. Configure TrustedHosts
On both computers, configure the TrustedHosts setting, so they know each other. Execute the following command on both computers to do so:
winrm set winrm/config/client '@{TrustedHosts=""}'
Step 3. Restart WinRM Service
Run the following command to restart the WinRM service now:
Restart-Service WinRM
Step 4. Test the Connection
To test your configuration, execute the following command on the local computer:
Test-WsMan <RemoteCOMPUTERName>
For the configuration to be successful, this command should execute without errors and show the information of the WinRM service of the remote computer.
Create a PowerShell Session and Execute Commands
After configuring both computers, you can create a session using the following commands (Execute these commands with elevated privileges):
$cred=Get-Credential $sess = New-PSSession -Credential $cred -ComputerName <remotemachinename> Enter-PSSession $sess <Run commands in remote session> Exit-PSSession Remove-PSSession $sess
An example for commands to be run in the session can be creating a directory.