In this post we are going to look at running commands on a remote server using PSRemoting sent using the WS-Managment technology WinRM protocol.
Firstly you need to make sure WinRM is enabled:
WinRM is enabled by default on Windows Server 2012 R2 but disabled on all client operating systems earlier than Windows Server 2012.
WinRM is a Microsoft implementation of WS-Management Protocol. Read more
It allows for better inventory of systems running Windows compared to WMI and is relatively easy to setup. It can be done through a GPO in your Active Directory.
If PSRemoting is not enabled via GPO or isn’t set to default enabled you can run thee commands below-
Enable-PSRemoting –force # Set WinRM to automatic Set-Service WinRM -StartMode Automatic # Check startmode and run service Get-WmiObject -Class win32_service | Where-Object {$_.name -like "WinRM"} # Trust all hosts Set-Item WSMan:localhost\client\trustedhosts -value * # Verify trusted hosts config Get-Item WSMan:\localhost\Client\TrustedHosts
PSRemoting brief:
- Invoke-Command if you’re only going to run one command against a system
- Enter-PSSession if you want to create a session with a computer
- Use PowerShell sessions when you’re going to run multiple commands on multiple systems
Start remote PowerShell interactive session on remote computer:
Enter-PSSession -ComputerName COMPUTER -Credential “myDomain\adminusername“
Start remote PowerShell interactive session using your current account (most PSRemote commands can be run as just the default user)
Enter-PSSession -ComputerName COMPUTER
To run a script located on a remote computer –
Invoke-Command -ComputerName COMPUTER -ScriptBlock {Invoke-Expression “C:\scripts\leavedomain.ps1” } -credential “myDomain\adminusername“
Run single commands –
Invoke-Command -ComputerName COMPUTER -ScriptBlock {Invoke-Expression “shutdown -r” } -credential “myDomain\adminusername“
Test WinRM connection:
Test-WsMan COMPUTER
Remote connection to Exchange server console:
$UserCredential = Get-Credential$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://ServerHostName/PowerShell/ -Authentication Kerberos -Credential $UserCredentialImport-PSSession $Session
New-PSSession –ComputerName server1.domain.com –Credentials “myDomain\adminusername“
Get-PSSession
Enter-PsSession –id 3
Exit-PsSession
Invoke-Command -Session (Get-PSSession) -ScriptBlock {ComputerHostname}
Get-PSSession | Disconnect-PSSession
Thanks for reading – feel free to follow and stay updated 🙂 View sysadminguides’s profile on Facebook View GuidesSysadmin’s profile on Twitter View 115372466162675927272’s profile on Google+
This was great to readd
LikeLike