powershell - PS7.1-如何将管道链接与自定义功能一起使用?

标签 powershell powershell-7.0

根据文档,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/

相关文章:

visual-studio - Visual Studio 2012 可以使用 cmdlet 实现自动化吗?

powershell - 如何使用Powershell更改RDL中的共享数据集路径

Powershell从多个文件创建对象

xml - 列出SSIS包中所有 "Execute SQL Task"的SqlStatementSource

powershell - Powershell循环每个文件名仅运行一次文件,即使文件名存在多个扩展名也是如此

powershell - 内存使用 powershell 7.03 Foreach-object 并行

xml - Powershell:按元素索引将XML节点值选择为变量

powershell - 为什么 pwsh.exe 结合 Start-Process 不直接接受脚本 block ?

powershell - Blob属性-除了通过ForEach循环之外,还有其他更好的方法可以从此集合中进行选择吗?