title: Powershell invoke command and getting result or error back
body: <p>I have a powershell script as seen below.</p>
  <pre><code>$credential = Get-Credential
  $server_list = @('server1','server2')
  $script = &quot;[System.Net.Dns]::GetHostName()&quot;
  foreach ($server_name in $server_list) {
      
      $result = invoke-command -ComputerName $server_name -ScriptBlock { [System.Net.Dns]::GetHostName() }
      write-output &quot;Remote command execution result is $result&quot;
  }
  </code></pre>
  <p>What is the problem ?</p>
  <p>In the example below, if the server is unreachable or access denied errors are encountered for whatever reason, the value of result is not populated. The value of $result is only populated for a successful execution.</p>
  <p>Sometimes, I get the error below.</p>
  <p><code>Connecting to remote server server1 failed with the following error message: WinRM cannot process the request. The following error occured whilst using kerberos authentication: cannot find the computer server1. Verify that the computer exists on the network and that the name provided is spelled correctly.</code></p>
  <p>Now, what I want to achieve is as following, for every server, get the hostname using <code>[System.Net.Dns]::GetHostName()</code> or any other means, the current time and the powershell version and any error message. Store this up in a custom object etc and return it as part of the script block. This way, when  I receive the value of result per server, I can load the results in a database and analyse which servers encountered errors etc.</p>
  <p>I looked at <a href="https://stackoverflow.com/questions/8549184/how-to-capture-the-return-value-of-a-scriptblock-invoked-with-powershells-invok">How to capture the Return Value of a ScriptBlock invoked with Powershell&#39;s Invoke-Command</a> which was a good reference, but what they were doing there is a ping, in my case a ping doesnt really answer the questions of if the credential being used is valid etc.</p>