Windows: Enable Remote Access

# Set remote hostname variable
$remoteHost="HV01"

# Install psexec
Install-Module -Name psexec
# psexec \\$remoteHost reg add "HKLM\SYSTEM\CurrentControlSet\Services\LanmanWorkstation\Parameters" /v SessTimeout /t REG_DWORD /d 3600 /f

# Run this snippet to enable WinRM
psexec.exe \\$remoteHost -s C:\Windows\system32\winrm.cmd qc -quiet

Output of successful enabling WinRM

PS C:\Windows\system32> psexec.exe \\$remoteHost -s C:\Windows\system32\winrm.cmd qc -quiet

PsExec v2.2 - Execute processes remotely
Copyright (C) 2001-2016 Mark Russinovich
Sysinternals - www.sysinternals.com


WinRM service is already running on this machine.
WinRM is already set up for remote management on this computer.
C:\Windows\system32\winrm.cmd exited on HV01 with error code 0.

# Test to see if WinRM is indeed installed
test-netconnection $remoteHost -port 5985

# Enter PowerShell session on remote host
enter-pssession $remotehost

Scripted function

# This script will check whether the remote host is pingable, then it will set WinRM to be enabled using psexec

# Set remote hostname variable
$remoteHost="HV01"

function pingTest{
Param([string]$node)
try{
Return Test-Connection $node -Count 1 -Quiet -ea Stop;
}
catch{Return $False}
}

function enableRemoteWinRM{
Param([string]$computername)
if (pingTest $computername){
try{
$isWinRMEnabled = Test-WSMan $computername -ea Stop
}
catch{
$isWinRMEnabled=$False
Write-Host "WinRM has not been detected. Enabling now..."
continue;
}
if (!($isWinRMEnabled)){psexec.exe \\$computername -s C:\Windows\system32\winrm.cmd qc -quiet}
else{Write-Host "WinRM has been already enabled. No changes to WinRM have been made."}
}
Else{Write-Host "Unable to determine if WinRM is enabled on $computername`.`n Ping test has failed. Check if this computer is online and whether there's a firewall blocking of ICMP";}
}

enableRemoteWinRM $remoteHost

Leave a Reply

Your email address will not be published. Required fields are marked *