Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
静默/重定向PowerShell错误流:我缺少什么?_Powershell_Cmd - Fatal编程技术网

静默/重定向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

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

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异常复杂的错误处理的全面概述:


谢谢,这让事情更清楚了。“语句终止”和“脚本终止”之间的区别对我来说不太清楚,因为脚本正在继续,所以我假设错误是非终止的。“Set ExecutionPolicy”发出终止错误的原因可能只是一个简单的警告(执行策略毕竟会更改),我仍然不明白,但这完全是另一回事。