根据文档,PS 7引入了管道链接运算符,例如||
和&&
。
https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_pipeline_chain_operators?view=powershell-7
而且您应该能够执行C#式的短路操作,例如:Write-Error 'Bad' && Write-Output 'Second'
以上示例可以正常工作。并且文档说管道链接运算符使用两个字段(不确定如何精确工作):$?
和$LASTEXITCODE
如何将这些应用于自己的功能?
例如:
function yes() {
echo 'called yes'
return $True
}
function no() {
echo 'called no'
return $False
}
我觉得我应该能够运行以下no && yes
并看到以下输出called no
False
但是我看到了
called no
False
called yes
True
那么,如何以可以使用管道链接和短路的方式开发功能?
编辑:我现在能弄清楚构造一个使
&&
短路的自定义函数的唯一方法是使其成为throw
,但这在一般情况下似乎没有太大用处。
最佳答案
&&
和||
仅在命令的成功状态上运行,这反射(reflect)在automatic $?
variable(如您所述)中-与命令输出(返回)无关。
函数和脚本将$?
报告为$true
,除非采取了明确的措施;否则,它们将被禁用。也就是说,即使脚本/函数内部使用的命令失败,当脚本/函数退出时,$?
仍然是$true
。
不幸的是,从PowerShell 7.0开始,没有直接的方法让函数直接将$?
设置为$false
,尽管计划是要添加这样的功能-请参见this GitHub isssue。
在脚本中,将exit
与非零退出代码一起使用是有效的(但是,这会导致$LASTEXITCODE
反射(reflect)退出代码,如果退出代码非零,PowerShell引擎会将$?
设置为$false
-这也是您工作时的工作方式调用外部程序)。
目前,对于函数,只有以下次优解决方法;它是次优的,因为它总是发出错误消息:
function no {
# Make the function an advanced one, so that $PSCmdlet.WriteError()
# can be called.
[CmdletBinding()]
param()
# Call $PSCmdlet.WriteError() with a dummy error, which
# sets $? to $false in the caller's scope.
# By default, this dummy error prints and is recorded in the $Error
# collection; you can use -ErrorAction Ignore on invocation to suppress
# that.
$PSCmdlet.WriteError(
[System.Management.Automation.ErrorRecord]::new(
[exception]::new(), # the underlying exception
'dummy', # the error ID
'NotSpecified', # the error category
$null) # the object the error relates to
)
}
现在,函数
no
将$?
设置为false,从而触发||
分支; -EA Ignore
(-ErrorAction Ignore
)用于消除虚拟错误。PS> no -EA Ignore || 'no!'
no!
关于powershell - PS7.1-如何将管道链接与自定义功能一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62469152/