Wednesday, December 23, 2009

Testing for PowerShell Remoting: Test-PsRemoting

Testing for PowerShell Remoting: Test-PsRemoting: "

When you’re writing a script that depends on PowerShell Remoting, it’s often helpful
to know that the remoting channel is open and will support the activities of your
script.
PowerShell has a Test-WSMan command, but that only verifies that a WSMan connection
is possible. There are other scenarios you could be impacted by:
  • Not having permission on the remote machine
  • Misconfiguration of the PowerShell endpoint
  • Corrupted installation
  • (etc)
As you dig deeper, you realize that the only way to really test the viability of the
remoting channel is to just do something on it, and verify that you got the results
you expected to. Since the implementation was so simple, we didn’t write a cmdlet
for it. In retrospect, the concept is more difficult than the implementation, so we
probably should have written it anyways. Here’s an example function that tests the
remoting connection to a specific machine.
function Test-PsRemoting{
  param(
   [Parameter(Mandatory = $true)]
   $computername
  )
  try{
   $errorActionPreference = "Stop"
   $result = Invoke-Command -ComputerName $computername { 1 }
  }
  catch{
   Write-Verbose $_
   return $false
  }
  ##I've never seen this happen, but if you want to be
  ##thorough....
  if($result -ne 1){
   Write-Verbose "Remoting to $computerName returned an unexpected result."
   return $false
  }
  $true
}