Powershell try/catch with test-connection

MattMoo picture MattMoo · Sep 17, 2015 · Viewed 22.4k times · Source

I'm trying to have offline computers recorded in a text file so that I can run them again at a later time. Doesn't seem that it is being recorded or caught in catch.

function Get-ComputerNameChange {

    [CmdletBinding()]
    Param(
    [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)]
    [string[]]$computername,
    [string]$logfile = 'C:\PowerShell\offline.txt'
    )




    PROCESS {

        Foreach($computer in $computername) {
        $continue = $true
        try { Test-Connection -computername $computer -Quiet -Count 1 -ErrorAction stop
        } catch [System.Net.NetworkInformation.PingException]
        {
            $continue = $false

            $computer | Out-File $logfile
        }
        }

        if($continue){
        Get-EventLog -LogName System -ComputerName $computer | Where-Object {$_.EventID -eq 6011} | 
        select machinename, Time, EventID, Message }}}

Answer

briantist picture briantist · Sep 17, 2015

try is for catching exceptions. You're using the -Quiet switch so Test-Connection returns $true or $false, and doesn't throw an exception when the connection fails.

As an alternative you can do:

if (Test-Connection -computername $computer -Quiet -Count 1) {
    # succeeded do stuff
} else {
    # failed, log or whatever
}