测试 Enter-PSSession 是否成功

sun*_*eas 5 windows powershell

有没有办法测试 Enter-PSSession 是否成功或 Enable-Remoting 是否已为 true?我不需要能够进入机器本身,只是一种找出返回码的方法。基本上,只需检查是否可以远程连接到计算机,或者计算机是否仍然需要启用远程连接。

Mat*_*sen 5

Enter-PSSession仅供互动使用。

要测试是否启用远程处理,请使用New-PSSession

$testSession = New-PSSession -Computer $targetComputer
if(-not($testSession))
{
    Write-Warning "$targetComputer inaccessible!"
}
else
{
    Write-Host "Great! $targetComputer is accessible!"
    Remove-PSSession $testSession
}
Run Code Online (Sandbox Code Playgroud)

如果成功,New-PSSession将返回新的 PSSession 对象 - 如果失败,则不会返回任何内容,并且$testSession$null因此-not($testSession) -eq $true