【发布时间】: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