Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell try/catch with test-connection

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 }}}
like image 504
MattMoo Avatar asked Sep 17 '15 18:09

MattMoo


2 Answers

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
}
like image 121
briantist Avatar answered Oct 10 '22 12:10

briantist


The Try/Catch block is the better way to go, especially if you plan to use a script in production. The OP's code works, we just need to remove the -Quiet parameter from Test-Connection and trap the error specified. I tested on Win10 in PowerShell 5.1 and it works well.

    try {
        Write-Verbose "Testing that $computer is online"
        Test-Connection -ComputerName $computer -Count 1 -ErrorAction Stop | Out-Null
        # any other code steps follow
    catch [System.Net.NetworkInformation.PingException] {
        Write-Warning "The computer $(($computer).ToUpper()) could not be contacted"
    } # try/catch computer online?

I've struggled through these situations in the past. If you want to be sure you catch the right error when you need to process for it, inspect the error information that will be held in the $error variable. The last error is $error[0], start by piping it to Get-Member and drill in with dot notation from there.

Don Jones and Jeffery Hicks have a great set of books available that cover everything from the basics to advanced topics like DSC. Reading through these books has given me new direction in my function development efforts.

like image 31
ChrisS Avatar answered Oct 10 '22 14:10

ChrisS