Khalifa96
Khalifa96

Reputation: 47

How do I insert an error action in this script to continue silently?

I am trying to insert an error a action within this script so that any machines that it finds to be offline and cannot query, it will tell me that it is offline first before checking its windows version.

Then stop when finished checking all machines.

$machinesv = Get-Content -Path C:\Users\khalifam\Desktop\WinverMachines.txt

foreach ($Computer in $machinesv ) {
    Invoke-Command -Computername $machinesv -Scriptblock {
        (Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName" -Name ComputerName).ComputerName 
        (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Name ReleaseID).ReleaseID 
    }
} 

Output:

LN-T48-PF11LK59
1809
LN-T48-PF11LK5U
1809
LN-T48-PF11LK6W
1809
[LN-T48-PF11LK6E] Connecting to remote server LN-T48-PF11LK6E failed with the
following error message : The WinRM client cannot process the request because
the server name cannot be resolved. For more information, see the
about_Remote_Troubleshooting Help topic.
    + CategoryInfo          : OpenError: (LN-T48-PF11LK6E:String) [], PSRemotingTransportException
    + FullyQualifiedErrorId : ComputerNotFound,PSSessionStateBroken
LN-T48-PF11LDQ1
1809

Upvotes: 1

Views: 154

Answers (1)

Maximilian Burszley
Maximilian Burszley

Reputation: 19644

If your only goal is to test connectivity before invoking a command, you should be checking status before invoking that command in your loop:

#requires -PSEdition Desktop
foreach ($cn in ...) {
    if (Test-Connection -ComputerName $cn) { ... }
    else { continue }
}

Upvotes: 2

Related Questions