9

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

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

2 回答 2

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
}
于 2015-09-17T18:49:50.020 回答
1

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 等高级主题的所有内容。通读这些书为我的功能开发工作提供了新的方向。

于 2019-06-23T14:21:57.407 回答