Powershell试用/捕获测试连接

Mat*_*Moo 7 powershell try-catch get-eventlog

我正在尝试将离线计算机记录在文本文件中,以便我可以在以后再次运行它们.似乎没有记录或陷入捕获.

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 }}}
Run Code Online (Sandbox Code Playgroud)

bri*_*ist 5

try用于catch处理异常。您正在使用-Quiet开关,因此Test-Connection返回$trueor $false,并且throw在连接失败时不会出现异常。

作为替代方案,您可以执行以下操作:

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