【问题标题】:Powershell try/catch with test-connectionPowershell tr​​y/catch 与测试连接
【发布时间】:2015-12-14 18:18:31
【问题描述】:

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

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

【问题讨论】:

    标签: powershell try-catch get-eventlog


    【解决方案1】:

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

    您也可以这样做:

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

    【讨论】:

    • 是的。你知道为什么它只在我的文本文件中输入最后一个计算机名吗?我正在尝试获取内容 "\\test\c$\powershell\computers.txt" |获取计算机名称更改
    • @user3620584 你怎么知道它只是在最后一个管道?
    • 作为测试,我输入了 3 个不存在的计算机名称,它只列出了日志文件中的最后一个。
    • @user3620584 Out-File 每次都会覆盖文件。使用-Append 参数添加到末尾。
    【解决方案2】:

    Try/Catch 块是更好的方法,特别是如果您计划在生产中使用脚本。 OP 的代码有效,我们只需要从 Test-Connection 中删除 -Quiet 参数并捕获指定的错误。我在 PowerShell 5.1 中的 Win10 上测试过,效果很好。

        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?
    

    我过去曾在这些情况下苦苦挣扎。如果您想确保在需要处理错误时捕捉到正确的错误,请检查将保存在 $error 变量中的错误信息。最后一个错误是 $error[0],首先通过管道将它传递给 Get-Member,然后从那里使用点符号进行钻取。

    Don Jones 和 Jeffery Hicks 提供了一套很棒的书籍,涵盖了从基础到 DSC 等高级主题的所有内容。通读这些书籍为我的功能开发工作提供了新的方向。

    【讨论】:

      猜你喜欢
      • 2011-10-10
      • 2020-02-09
      • 1970-01-01
      • 1970-01-01
      • 2022-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-03
      相关资源
      最近更新 更多