Frage

im currently finishing my PS script to get the time from a list of servers and export them to a .txt file. Thing is that servers with connection problems gives just a PS error. I want that servers with connection issues get logged also and by just a message i.e "Server server name not reachable". Thanks a lot for your help!

cls
$server = Get-Content srvtime_list.txt
Foreach ($item in $server)
{
 net time \\$item | find /I "Local time" >> srvtime_result.txt
}
War es hilfreich?

Lösung

I'd probably rewrite your code a bit:

Get-Content srvtime_list.txt |
  ForEach-Object {
    $server = $_
    try {
      $ErrorActionPreference = 'Stop'
      (net time \\$_ 2>$null) -match 'time'
    } catch { "Server $server not reachable" }
  } |
  Out-File -Encoding UTF8 srvtime_result.txt

Andere Tipps

There are other/better ways to get the time (as others suggested) but to answer your question:

  1. You can suppress errors by redirecting the error stream to null.
  2. Check the $LASTEXITCODE variable, any result other than 0 means the command did not completed successfully.

    Get-Content srvtime_list.txt | Foreach-Object{
    
       net time \\$_ 2>$null | find /I "Current time" >> srvtime_result.txt
    
       if($LASTEXITCODE -eq 0)
       {
           $result >> srvtime_result.txt
       }
       else
       {
        "Server '$_' not reachable" >> srvtime_result.txt
       }        
    

    }

I'd do something like this:

Get-Content srvtime_list.txt | %{
   $a = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $_ -erroraction 'silentlycontinue'
   if ($a) { "$_ $($a.ConvertToDateTime($a.LocalDateTime))"  } else { "Server $_ not reachable" }
} | Set-Content srvtime_result.txt

Use the Test-Connection cmdlet to verify that the remote system is reachable.

cls
$server = Get-Content srvtime_list.txt
Foreach ($item in $server)
{
 if (test-connection $item) {
     net time \\$item | find /I "Local time" >> srvtime_result.txt
    } else {
   "$item not reachable" | out-file errors.txt -append
}
}

But you can do this in pure Powershell, without resorting to net time - use WMI. This is untested as I don't have Windows handy at the moment, but it's at least 90% there.

cls
$server = Get-Content srvtime_list.txt
$ServerTimes = @();
Foreach ($item in $server)
{
 if (test-connection $item) {
     $ServerTimes += Get-WMIObject -computername $name win32_operatingsystem|select systemname,localdatetime 
    } else {
   "$item not reachable" | out-file errors.txt -append
}
}
$ServerTimes |Out-File srvtime_result.txt
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top