【问题标题】:Try/Catch Statements don't seem to be working [duplicate]Try/Catch 语句似乎不起作用[重复]
【发布时间】:2020-06-23 19:16:31
【问题描述】:

下午!

编辑

在进行了更多故障排除后,我注意到它似乎不想从New-Item -ItemType Directory -Path Z:\PMO\PMOBits\test 部分捕获错误。如果我输入 Null 值,它会在我的 Get-Logger 函数和使用 Write-output 中捕获该错误。 为什么它不会捕获文件夹已经存在的错误?

我的 PowerShell 脚本中有一个日志记录功能,并且我正在尝试使用该功能合并一些错误处理。下面是日志功能。

Function Get-Logger { 
    param(
       [Parameter(Mandatory=$true)]
       [String]$message,
       [Parameter(Mandatory=$false)]
       [validatescript({[enum]::getvalues([system.consolecolor]) -contains $_})][string]$Color
    )

    $TimeStamp = Get-Date -Format "MM-dd-yyy hh:mm:ss"

    Write-Host $TimeStamp -NoNewline
    IF ($Color) {
        Write-Host `t $message -ForegroundColor $($color)
    } Else {
        Write-Host `t $message -ForegroundColor Cyan
    }
    $logMessage = "[$TimeStamp]  $message"
    $logMessage | Out-File -Append -LiteralPath $VerboseLogFile
}

我正在使用一些简单的错误处理代码对此进行测试,请参阅下面的测试代码。

Try { New-Item -ItemType Directory -Path Z:\PMO\PMOBits\test } 
    Catch {
        Get-Logger "ERROR: This file already exists"
    }

当我运行脚本时,我看到终端上填充了它已经存在的错误,但它没有像 catch 部分那样显示在我的日志文件中。

我也尝试在不使用下面的函数的情况下捕获错误:

try{...}
catch {
Write-Output $_ | Out-File -Append -LiteralPath $VerboseLogFile
}

【问题讨论】:

    标签: function powershell error-handling try-catch


    【解决方案1】:

    New-Item 语句中添加-ErrorAction Stop

        Try { New-Item -ItemType Directory -Path Z:\PMO\PMOBits\test -ErrorAction Stop } 
        Catch {
            Get-Logger "ERROR: This file already exists"
        }
    

    【讨论】:

    • @Fitzgery,请参阅this answer 了解背景信息; Jawad,这个问题的变种不断出现,我鼓励你在未来投票支持关闭作为重复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-18
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 2010-11-25
    相关资源
    最近更新 更多