如何将 powershell hyper-v 错误保存到文件

How to save powershell hyper-v errors to file

我正在制作一个脚本来在 hyper-v 中打开和关闭虚拟机。 有时 Stop-VM 命令失败,我需要保存错误或以某种方式在日志文件中反映它

我尝试将命令放在 trycath 中,但没有成功。

命令:

Stop-VM $VMapagar

有时命令会报这个错误并且不关机

Stop-VM: Could not stop.

我希望能够在 log.txt 中以某种方式反映失败 谢谢!

使用 Try..Catch 告诉 PS 将错误视为终止错误来捕获错误,然后根据需要进行处理:

# Rest of your script
Try {
    # Run your command, but tell PS to stop if it find an error
    # You can explore the effects of the other possible values for -ErrorAction in PS documentation.
    Stop-VM $VMpagar -ErrorAction Stop
    # If it's got this far, then there can't have been an error so write a success message to console
    Write-Host "OK"
}
Catch {
    # This code will process if there was an error in the "Try" block
    # By default, within the "Catch" block, the "$_" variable contains the error message
    Write-Host "Error: $_"
    # Write the error to a log file - "`n" tells PS to write a newline before the subsequent text
    Add-Content -Path 'c:\temp\log.txt' -Value "`n$_"
    # You could stop the script here using "Throw" or "Exit" commands if you want the whole script to stop on ANY error
}
# Your script will continue from this point if you haven't stopped it
  • shows how to capture a terminating error, by using the common -ErrorAction (-ea) parameter with value 'Stop' in order to promote non-terminating errors (the most common kind) to terminating ones, which allows them to be trapped with a try/ catch / finally statement.

    • 请注意,此方法限制您捕获第一个非终止错误(而单个 cmdlet 调用可能会发出 多个 个),因为它 - 感谢 -ErrorAction Stop - 然后 立即终止语句 并转移控制权 catch 块(其中 automatic $_ variable reflects the triggering error in the form of an [ErrorRecord] 实例)。

    • 另请注意,默认情况下 会在 catch 块后继续执行 - 除非您明确使用 throw to re-throw the terminating error (or use a statement such as exit 退出脚本) .

  • 捕获 - 可能 多个 - 非终止 错误你有两个选择:

    • 使用 redirection 运算符 > 将它们 直接重定向到文件 带有错误流的编号,2:

      • Stop-Vm $vms 2>errs.txt
      • 这会将任何错误悄悄地发送到文件errs.txt;也就是说,您不会在控制台中看到它们。如果没有错误发生,将创建一个空文件。
      • 注意:此技术是直接重定向外部程序错误(stderr 输出)的唯一选择;但是,使用重定向 2>&1 您可以捕获成功输出 (stdout) 和错误 (stderr) 组合 ,并稍后将它们按源流拆分 - 请参阅 [= 的底部部分41=].
    • 使用 common -ErrorVariable (-ev) parameter 收集 变量中的任何非终止错误 - 请注意必须指定目标变量 而没有 $:

      • Stop-Vm $vms -ErrorVariable errs
      • 默认情况下,错误仍然以及输出,因此默认打印到控制台(主机),但您可以添加-ErrorAction SilentlyContinue来防止这种情况。 警告不要使用-ErrorAction Ignore,因为这会明确抑制错误并防止收集错误。
      • 然后您可以检查 $errs 数组(列表),如果没有错误发生则为空,否则包含一个或多个 [ErrorRecord] 实例,并根据需要将收集到的错误发送到文件;例如。:
        • if ($errs) { $errs > errs.txt }

另请参阅:

  • This answer 了解有关 PowerShell 的两种基本错误类型的信息。
  • GitHub docs issue #1583 全面了解 PowerShell 异常复杂的错误处理。