尝试/捕获语句似乎不起作用

时间:2020-03-11 18:13:35

标签: function powershell error-handling try-catch

下午!

编辑

经过更多故障排除后,我注意到它似乎不想捕获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
}

1 个答案:

答案 0 :(得分:2)

在您的-ErrorAction Stop语句中添加New-Item

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