如何"get" 异常上下文进行错误处理?

how to "get" an exception context for error handling?

我有一个 运行 很棒的脚本,但我正在考虑通过添加更多我过去收到的异常处理来增强它,以防未来用户遇到困难并需要明确提示可能的解决方案来修复如果问题稍后发生。

我基本上想做的是,一旦我尝试 运行 脚本,我就得到了一个执行策略异常,即未经授权访问 运行 脚本。

我不想将异常吐到日志文件中,然后我可以在其中获取某些字符串的内容以打印可能的解决方案。

相反,我想立即从控制台获取异常字符串的一部分,然后提示可能的解决方案。

有这样的选项吗?

您可以在 Powershell 中使用 Try Catch 方法。结合一个开关,您可以选择要显示的消息。

try{
    sdasdasdad
}catch [System.Exception]{
    switch ($_.Exception.GetType().FullName){
        "System.Management.Automation.CommandNotFoundException"{
            "No Command Found. Please try a diffrent command."
        }
        default { 
            $_.Exception.message
        }
    }
}

我将在此处的示例中使用 File.WriteAllLines 方法。如果您的目标是使用单个 catch 语句,则可以在异常消息上使用 switch:

$ErrorActionPreference = 'Stop'
try
{
    [System.IO.File]::WriteAllLines('C:\Temp\test.txt', 'Test message')
}
catch
{
    switch -Regex ($PSItem.Exception.Message)
    {
        'null'
        {
            'null path passed!'
        }

        'invalid'
        {
            'bad path passed!'
        }

        default
        {
            'didn''t catch this case!'
        }
    }
}

不过,这种方式不太易于维护。更好的方法是捕获不同的异常:

$ErrorActionPreference = 'Stop'
try
{
    [System.IO.File]::WriteAllLines('C:\Temp\test.txt', 'Test message')
}
catch [System.ArgumentNullException]
{
    'null path passed!'
}
catch [System.IO.DirectoryNotFoundException]
{
    'bad path passed!'
}
catch
{
    'didn''t handle this case!'
}

对于你的例外情况运行一个脚本:

try
{
    & 'C:\myscript.ps1'
}
catch [System.Management.Automation.PSSecurityException]
{
     "Execution policy bad! $PSItem"
}
catch
{
    "This exception was thrown by something in the script and not caught: $PSItem"
}