停止脚本和日志错误

时间:2011-11-07 11:40:55

标签: logging powershell error-handling

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

 foreach ($s in Get-Content $config_file)

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

是否可以在脚本中使用-ErrorAction和cusom日志记录功能?

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

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

或者有更好的方法吗?

-G

3 个答案:

答案 0 :(得分:2)

使用-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
# ...

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

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

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

 foreach ($s in Get-Content $config_file)
 ...
相关问题