Powershell Catch 仅打印修改后的错误

Powershell Catch print modified error only

我有包含以下值的 csv 文件:

User,TimeStamp
Pinky,11/4/2015 5:00
Brain,
Leo,never
Don,unspecified

我想确保 TimeStamp 列的此文件具有日期或 $null 值。为此,我使用以下代码:

Function HealthCheckTimeStampColumn
{
    Param ($userInputCsvFileWithPath)

    Write-Host "Checking if TimeStamp column has invalid values..."
    Import-Csv $userInputCsvFileWithPath | %{
        if ($_.TimeStamp)
        {
            Try
            {
                ([datetime]$_.TimeStamp).Ticks | Out-Null
            }
            Catch [system.exception]
            {
                $Error.Clear()
                $invalidValue = $_.TimeStamp
                Write-Error "Invalid Value found `"$_.TimeStamp`"; Value expected Date or `"`""
                Exit
            }
        }
    }
    Write-Host "All values were found valid."
    Write-Host "TimeStamp Healthcheck Column Passed"
    Write-Host ""
}

使用这段代码,我得到了这个错误:

Invalid Value found "Cannot convert value "never" to type "System.DateTime". Error: "The string was not recognized as
a valid DateTime. There is an unknown word starting at index 0.".TimeStamp"; Value expected Date or ""
At C:\Scripts\Tests\TestTime.ps1:247 char:42
+     Import-Csv $userInputCsvFileWithPath | %{
+                                             ~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException

如果我改为尝试这行代码:

Write-Error "Invalid Value found `"$invalidValue`"; Value expected Date or `"`""

我收到这个错误:

Invalid Value found ""; Value expected Date or ""
At C:\Scripts\Tests\TestTime.ps1:247 char:42
+     Import-Csv $userInputCsvFileWithPath | %{
+                                             ~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException

我期望看到的错误是这样的:

Invalid Value found "never"; Value expected Date or ""
At C:\Scripts\Tests\TestTime.ps1:247 char:42
+     Import-Csv $userInputCsvFileWithPath | %{
+                                             ~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException

谁能告诉我我做错了什么?

将 PerSerAl 的观察转化为答案:

$_ 将其在 foreach-object 循环(但在 catch 块之外)中的含义更改为在 catch 块中的含义。在第一种情况下,它是当前对象(行),其时间戳显然具有值 "never"。但是在 catch 块中,它是由于错误而生成的错误记录。所以要修复:

Function HealthCheckTimeStampColumn
{
    Param ($userInputCsvFileWithPath)

    Write-Host "Checking if TimeStamp column has invalid values..."
    Import-Csv $userInputCsvFileWithPath | %{
        $row = $_
        if ($_.TimeStamp)
        {
            Try
            {
                ([datetime]$_.TimeStamp).Ticks | Out-Null
            }
            Catch [system.exception]
            {
                $Error.Clear()
                $invalidValue = $_.TimeStamp
                Write-Error "Invalid Value found `"$row.TimeStamp`"; Value expected Date or `"`""
                Exit
            }
        }
    }
    Write-Host "All values were found valid."
    Write-Host "TimeStamp Healthcheck Column Passed"
    Write-Host ""
}

顺便说一句,如果你想处理整个文件,你需要从 catch 块中删除 exit

你也不需要 try/catch 块。它们适用于意外和不可避免的错误。但是 about_Type_Operators 你会看到 -as-is 处理这种情况的方式相当优雅。

-is : Returns TRUE when the input is an instance of the specified .NET Framework type.

-as : Converts the input to the specified .NET Framework type.

-as 遇到字符串或无法转换为 [datetime] 的内容时,它将 return 为空值。更重要的是它不会出错。我建议您检查所有值的非空值和无效日期时间。将所有这些都捕获到一个变量中。然后检查变量是否有任何值。一次全部打印!然后如果你想退出。我也同意 关于使用 exit 的说法。

Function HealthCheckTimeStampColumn{
    Param ($userInputCsvFileWithPath)
    $badRows = Import-Csv $userInputCsvFileWithPath | 
        Where-Object{-not [string]::IsNullOrEmpty($_.TimeStamp) -and ($_.TimeStamp -as [datetime]) -eq $null}
    if($badRows){
        $badRows | ForEach-Object{
            Write-Host "'$($_.Timestamp)' is not a valid datetime" -ForegroundColor Red
        }
        Write-Error "$($badRows.Count) Invalid Value(s) found"
    } else {
        "All values were found valid.","TimeStamp Healthcheck Column Passed","" | Write-Host
    }
}