仅Powershell Catch打印修改错误



我有一个具有以下值的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:ScriptsTestsTestTime.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:ScriptsTestsTestTime.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:ScriptsTestsTestTime.ps1:247 char:42
+     Import-Csv $userInputCsvFileWithPath | %{
+                                             ~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException

有人能告诉我我做错了什么吗?

您也不需要try/catch块。它们对意外和不可避免的错误很好。然而,查看_Type_Operators,您会看到-as-is可以非常优雅地处理这种情况。

-is:当输入是指定.NET Framework类型的实例时,返回TRUE。

-as:将输入转换为指定的.NET Framework类型。

-as遇到一个字符串或不可转换为[datetime]的东西时,它将返回一个null。更重要的是,它不会出错。我建议您检查所有值的非null和无效日期时间。捕获变量中的所有这些。然后检查变量是否有任何值。一次打印所有内容!然后退出,如果你愿意的话。我也支持用户2460798的回答中关于出口的使用。

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

将PerSerAl的观察转化为答案:

$_的含义从它在foreach对象循环中(但在catch块之外)变为它在catchblock中。在第一种情况下,它是当前对象(行),其时间戳的值显然为"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

最新更新