简体   繁体   中英

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 }}}

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

Just do:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM