静默/重定向PowerShell错误流:我缺少什么?
我有一个Powershell脚本来放松机器上的执行策略,基本上运行:静默/重定向PowerShell错误流:我缺少什么?,powershell,cmd,Powershell,Cmd,我有一个Powershell脚本来放松机器上的执行策略,基本上运行: Set ExecutionPolicy Unrestricted-Force 由于ExecutionPolicy在计算机上受到限制,因此我需要使用.bat文件启动.ps1脚本,该文件绕过执行策略,如下所示: PowerShell.exe -ExecutionPolicy Bypass -File ./psscripts/myScript.ps1 Set-ExecutionPolicy Unrestricted -Force
Set ExecutionPolicy Unrestricted-Force
由于ExecutionPolicy在计算机上受到限制,因此我需要使用.bat文件启动.ps1脚本,该文件绕过执行策略,如下所示:
PowerShell.exe -ExecutionPolicy Bypass -File ./psscripts/myScript.ps1
Set-ExecutionPolicy Unrestricted -Force 2> $NULL
try{Set-ExecutionPolicy Unrestricted -Force} catch {}
通过使用此技巧,我得到以下错误:
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,如下所示:
PowerShell.exe -ExecutionPolicy Bypass -File ./psscripts/myScript.ps1
Set-ExecutionPolicy Unrestricted -Force 2> $NULL
try{Set-ExecutionPolicy Unrestricted -Force} catch {}
…但即使这样,终端上仍然会弹出错误
我已成功地使用如下的try-catch使错误静音:
PowerShell.exe -ExecutionPolicy Bypass -File ./psscripts/myScript.ps1
Set-ExecutionPolicy Unrestricted -Force 2> $NULL
try{Set-ExecutionPolicy Unrestricted -Force} catch {}
然而,我仍然想理解为什么其他两种方法不起作用?
尝试将错误流(或任何流)重定向到一个变量时,变量结果为空,因此我假设我试图从错误的进程重定向流?
这与从.bat文件启动Powershell有关吗
这里有人能帮我吗?使用
2>
重定向PowerShell只适用于非终止错误
注意:也只对非终止错误进行操作-与表面上的等效错误不同,但令人惊讶的是,它也适用于终止错误-请参阅下面GitHub文档问题的链接
设置执行策略
发出终止错误,该错误只能处理(以及很少使用的语句)
另见:
- 在命令编写者关于何时发出终止错误与非终止错误的指南上下文中,对PowerShell基本错误类型的描述
- PowerShell异常复杂的错误处理的全面概述: