gpt4 book ai didi

powershell - 静默/重定向 PowerShell 错误流 : what am I missing?

转载 作者:行者123 更新时间:2023-12-02 23:33:56 27 4
gpt4 key购买 nike

我有一个 Powershell 脚本来放松机器上的执行策略,本质上是运行:

Set-ExecutionPolicy Unrestricted -Force

由于 ExecutionPolicy 在机器上受到限制,我需要使用 .bat 文件启动 .ps1 脚本,这样可以绕过执行策略:

PowerShell.exe -ExecutionPolicy Bypass -File ./psscripts/myScript.ps1

通过使用这个技巧,我得到了以下错误:

Set-ExecutionPolicy : Windows PowerShell updated your execution policy successfully, but the setting is overridden by
a policy defined at a more specific scope. Due to the override, your shell will retain its current effective
execution policy of Bypass.

该错误试图告诉我当前进程(使用 -Bypass 启动)的策略范围覆盖了我刚刚设置的范围,但我真的不在乎,所以我想简单地隐藏此错误。

我试过使用 -ErrorAction SilentlyContinue:

Set-ExecutionPolicy Unrestricted -Force -ErrorAction SilentlyContinue

但错误仍然显示。所以我尝试像这样将错误流重定向到 &NULL:

Set-ExecutionPolicy Unrestricted -Force 2> $NULL

...但即使这样,错误仍然会在终端上弹出。

我已经成功地使用这样的 try-catch 消除了错误:

try{Set-ExecutionPolicy Unrestricted -Force} catch {}

不过,我还是想明白为什么其他两种方法都行不通?试图将错误流(或 任何 流)重定向到一个变量,该变量结果为空,所以我假设我以某种方式试图从错误的进程重定向流?这与从 .bat 文件启动 Powershell 有关系吗?

有人能帮我吗?

最佳答案

重定向 PowerShell 的 error output stream with 2> 仅适用于非终止 错误

注意:-ErrorAction common parameter也专门针对非终止 错误进行操作 - 不像 看似等价的 ErrorActionPreference preference variable ,然而,令人惊讶的是,这也适用于终止错误 - 请参阅下面的 GitHub 文档问题链接。

Set-ExecutionPolicy 发出一个terminating 错误,这仅是 try / catch可以处理(以及很少使用的 trap 语句)。

另见:

  • PowerShell 的基本错误类型在命令作者何时发出终止错误与非终止错误的指导上下文中的描述:this answer .

  • PowerShell 异常复杂的错误处理全面概述:this GitHub docs issue .

关于powershell - 静默/重定向 PowerShell 错误流 : what am I missing?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60191307/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com