Is there a way to test if Enter-PSSession is successful or if Enable-Remoting is already true? I don't need to be able to get into the machine itself, just a way to find out the return code. Basically, just checking to see if remoting into a machine can be done or if the machine still needs remoting to be enabled.
4 Answers
Enter-PSSession
is exclusively for interactive use.
To test whether remoting is enabled, use New-PSSession
:
$testSession = New-PSSession -Computer $targetComputer
if(-not($testSession))
{
Write-Warning "$targetComputer inaccessible!"
}
else
{
Write-Host "Great! $targetComputer is accessible!"
Remove-PSSession $testSession
}
If successful, New-PSSession
will return the new PSSession object - if it failed it won't return anything, and $testSession
is $null
(thus making -not($testSession) -eq $true
)
-
Does not catch some cases, e.g., user cancels password prompt. Apr 28, 2017 at 9:27
-
@FlorianWinter Agree, you cannot give feedback to the user based on this.– TerryJun 17, 2021 at 9:30
You can also use
Test-WSMan computername
or with autentication:
Test-WSMan myserver -Credential peter -Authentication Negotiate
and then check the return object.
If that works PSSession should also work.
-
Test-WSMan session succeeds in cases where New-PSSession would raise an error instead. The only clue for me is that the ProductVersion property shows the Windows version to be zero.
Test-WSMan HOSTNAME | Select -Expand ProductVersion
producesOS: 0.0.0 SP: 0.0 Stack: 3.0
. Aug 18, 2014 at 9:39 -
Testing with
-Authentication Negotiate
will reveal Kerberos issues - such as duplicate registered SPNs (setspn -x
). WinRM uses Kerberos by default, so you have to explicity request Negotiate. This was a very helpful suggestion. Mar 2, 2015 at 6:46
function CanRemote {
$session = New-PSSession $ComputerName -ErrorAction SilentlyContinue
if ($session -is [System.Management.Automation.Runspaces.PSSession])
{Write-Host "Remote test succeeded: $ComputerName."}
else
{Write-Host "Remote test failed: $ComputerName."}
}
-
Does not catch some cases, e.g., user cancels password prompt. Apr 28, 2017 at 9:29
If you are using Try block, then just add -ErrorAction Stop
Try{
$session = New-PSSession $ComputerName -ErrorAction Stop
}
Catch {
We got error..
}