【问题标题】:Stop script and log error停止脚本并记录错误
【发布时间】:2011-11-07 11:40:55
【问题描述】:

我有一个 powershell 脚本,需要使用简单的 Get-Content cmdlet 从配置文件中读取:

 foreach ($s in Get-Content $config_file)

如果配置文件不在应有的位置,我想停止脚本并记录错误。

是否可以在脚本中将 -ErrorAction 与自定义日志记录功能一起使用?

foreach($s in Get-Content $config_file -ErrorAction mdie('Could not find config file')

mdie 是一个记录错误并退出脚本的日志功能。

或者有没有更好的方法?

-G

【问题讨论】:

  • 什么是“退出脚本”?回归还是失败?

标签: logging powershell error-handling


【解决方案1】:

使用-ErrorAction Stoptry..catch 模式。在catch 块中,错误对象由变量$_ 表示。

function LogErrorAndExit([string]$message) {
    Write-Host $message -ForegroundColor Red
    exit 1
}

try {
    foreach($s in Get-Content $config_file -ErrorAction Stop) {
        # normal code
        # ...
    }
}
catch {
    # error case code
    LogErrorAndExit $_
}

# normal code
# ...

【讨论】:

  • 谢谢。如果不使用 try-catch 块就没有办法实现这一点吗?
  • 您也可以使用trap 语句。我更喜欢try/catch/finally 的方式,它似乎更简单但更灵活。但是你不能把一个函数指定为错误动作,这个概念是不存在的。
【解决方案2】:

你可以写一些更简单的东西

param($configfile)
$qwe=gc $configfile -erroraction silentlycontinue -errorvariable errorxd
if($qwe -ne $null)
{
  # Here comes what ever do you want to do with the content
}
else
{
  # Here comes the call to the Error Log function
  # You could use the $errorxd variable to see what problem occurs, something like
  # LogError($errorxd)
}

【讨论】:

  • 很好但是.. 如果失败的原因不是“缺少文件或空内容”怎么办? $Error[0]有时可以提供帮助,但如果发生 2+ 个错误怎么办? $Error[0] 不是第一个(通常是最重要的)。
  • @RomanKuzmin 你能给我一个2+错误的例子吗?我在想,但我无法想象那种情况
  • @RomanKuzmin 我编辑了 gc 调用,包括 errorvariable 参数,以将可能问题的描述添加到错误日志中
  • 1) 使用 ErrorVariable 是一个非常好的主意。 2)不,在这种情况下,我不能举一个 2+ 错误的例子。但是谁能保证这是不可能的呢?根据我的经验和错误,实际错误数量有时比预期的要大。我从不认为错误计数是 1。
【解决方案3】:

我会先测试配置文件是否存在:

 if(-not (Test-Path -Path $config_file -PathType Leaf))
 {
    mdie('Could not find config file')
    exit 1
 }

 foreach ($s in Get-Content $config_file)
 ...

【讨论】:

  • 如果它存在但被另一个应用程序锁定怎么办? :)
猜你喜欢
  • 1970-01-01
  • 2018-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-15
相关资源
最近更新 更多