【问题标题】:Exit code is not bubbled up退出代码没有冒泡
【发布时间】:2015-02-25 14:45:44
【问题描述】:

外部.ps1:

& "$env:WINDIR\syswow64\WindowsPowerShell\v1.0\powershell.exe" -NonInteractive -NoProfile -ExecutionPolicy Bypass -Command "& '.\Inner.ps1'; Write-Host "BLOCK: $LastExitCode"; exit $LastExitCode"
Write-Host "OUTSIDE: $LastExitCode"

Inner.ps1:

exit 3

执行Outer.ps1 输出:

BLOCK: 1
OUTSIDE: 1

什么,为什么? Inner.ps1 明显退出,退出代码为 3。有什么问题?

注意:如果我将Inner.ps1 更改为返回0,我会收到以下输出:

BLOCK: 0
OUTSIDE: 0

不知何故,除了 0 之外的所有其他代码都默认为 1,为什么?

【问题讨论】:

  • & '.\Inner.ps1' 中删除单引号会发生什么?我不认为 inner 被称为。当我删除单引号时它正在工作
  • 同样的结果,但是,如果 Inner.ps1 的名称中有空格,它就不再起作用了。
  • 是的.. 正在 ISE 中进行测试,我只有在手动运行 Inner 时才让它工作,所以我破坏了测试。回到绘图板

标签: powershell powershell-4.0


【解决方案1】:

你有报价问题:

& "$env:WINDIR\syswow64\WindowsPowerShell\v1.0\powershell.exe" -NonInteractive -NoProfile -ExecutionPolicy Bypass -Command '& ''.\Inner.ps1''; Write-Host "BLOCK: $LastExitCode"; exit $LastExitCode'
Write-Host "OUTSIDE: $LastExitCode"

【讨论】:

  • 我知道有些地方看起来不对劲,但我可以让它正常工作。每天学习一些东西。
  • 为其他读者澄清:$LastExitCode 甚至在调用脚本之前就被替换了!您必须在此处使用单引号,以停止变量替换!
  • 更多说明:在单引号中,您可以通过将单引号加倍来使用单引号 (''.\Inner.ps1'')。另外:原始命令中Write-Host 的引用问题不是问题,因为 PowerShell 会自动连接字符串。
猜你喜欢
  • 2012-04-19
  • 2015-07-03
  • 2013-04-30
  • 1970-01-01
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
  • 2018-05-25
  • 2020-09-24
相关资源
最近更新 更多