簡體   English   中英

Powershell試用/捕獲測試連接

[英]Powershell try/catch with test-connection

我正在嘗試將離線計算機記錄在文本文件中,以便我可以在以后再次運行它們。 似乎沒有記錄或陷入捕獲。

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是為了catch異常。 您正在使用-Quiet開關,因此Test-Connection返回$true$false ,並且在連接失敗時不會throw異常。

做就是了:

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

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等高級主題的所有內容。 閱讀這些書籍給了我功能開發工作的新方向。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM