我有一个很大的项目,里面有很多功能。只有两个问题:
区块报价
$ErrorActionPreference = "Stop"
Function F1
{
try
{
# do something
}
catch
{
# 1. cascade Error to Main?
# throw $Error[0].InnerException
# or
# local Error-Logging?
write-MyErrorLogging -message $Error[0].InnerException
}
}
Function F2
{
try
{
# do something
}
catch
{
# 1. cascade Error to Main?
# throw $Error[0].InnerException
# or
# local Error-Logging?
write-MyErrorLogging -message $Error[0].InnerException
}
}
Function F_XXXXXX
{
try
{
cls
write-host "The install data is copied.."
$share = "\\my_wrong_path\sql_sources\"
Copy-Item $share -Destination $installDrive -Force -Recurse
}
catch
{
$Error[0] #here is nothing!
$null -eq $Error[0] # here true
$_.Exception # only here the error-message: wrong path!
}
}区块报价
# here Main
try
{
F1
F2
F_XXXXXX
}
catch
{
write-MyErrorLogging -message $Error[0].InnerException
}区块引号
发布于 2022-05-08 16:33:36
中得到可靠的反映
- If you do need access to _previous_ errors via the [automatic `$Error` variable](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Automatic_Variables#error), **use** **`$global:Error`** **inside modules** - see the bottom section for details.$ErrorActionPreference = "Stop"语句将代码中的所有错误变为)泡起调用堆栈,直到它被try / catch statement捕获,或者在没有try / catch statement的情况下终止整个调用堆栈(即脚本及其调用方)。- If you do need to perform additional actions, use `try` / `catch`, and place the actions inside the `catch` block (as well as potential cleanup actions in a `finally` block), followed by _re-throwing_ the error simply by calling `throw` _without an argument_.因此,您可以在脚本的顶层范围中使用单个try / catch语句:
# Turn all errors in this and descendant scopes into
# script-terminating (fatal) ones.
$ErrorActionPreference = 'Stop'
# ... other function definitions, without try / catch
# Top-level code that calls the other functions and catches
# any errors.
try
{
F1
F2
F_XXXXXX
}
catch
{
write-MyErrorLogging -message $_.InnerException
}奇怪的是,至少可以达到PowerShell 7.2.3 (本文编写时的当前):
模块中发生的
$Error变量中。。
但是,存在一个看似未使用的、模块-本地复制的$Error variable. 的,其中E 248E 149阴影E 250E 151全局variable.>
解决方法是从模块内部使用$global:Error use 。
这种行为暗示了一个错误,因为模块本地副本似乎从未被碰过,也没有明显的用途。
https://stackoverflow.com/questions/72162310
复制相似问题