如何在 PowerShell 中隐藏 Get-Help 中的参数(不仅仅是选项卡完成)?

How to hide a parameter from Get-Help (not just tab completion) in PowerShell?

我找遍了,没有找到直接的答案'no',也没有找到肯定的答案。

我已经知道的:

我遇到的情况是有一个参数不应被任何第 3 方使用,但会被配套脚本使用

示例:

[CmdletBinding(SupportsShouldProcess)]param(
  [switch]$VisibleSwitch,
  [switch]$HiddenSwitch ### This switch should not be visible to human-beings.
)
#...
if( $HiddenSwitch) {
  #do something
  return
}
#...

我担心从 PowerShell 7.2 开始,没有好的解决方案,但您想要的最接近的可能是以下内容:

  • 定义一个代理参数,其名称表示不能直接使用。

  • 使用 DontShowValueFromRemainingArguments [Parameter()] 属性声明此参数。

  • 手动检查绑定到代理参数的参数以查找“隐藏”参数。

[CmdletBinding(SupportsShouldProcess)]
param(
  [switch] $Switch
  ,
  [Parameter(DontShow, ValueFromRemainingArguments)]
  ${(ignore)}
)

# Examine the quasi-hidden parameter value 
# for containing the switch name of interest.
$HiddenSwitch = ${(ignore)}.Count -eq 1 -and ${(ignore)}[0] -eq '-HiddenSwitch'

# Make sure that no unexpected arguments were passed.
if (-not $HiddenSwitch -and ${(ignore)}.Count -gt 0) { throw "Unexpected arguments specified: ${(ignore)}"}

# Output what switches were passed.
[pscustomobject] @{
  '-Switch' = $Switch
  '-HiddenSwitch' = $HiddenSwitch
}

注:

  • 这不会阻止代理参数出现在语法图中(例如 -?)——它会显示为 [-(ignore) <Object>]——但它不会t 显示真实的参数名称。

    • GitHub issue #7868 在不再显示 obsolete(已弃用)参数的情况下,寻求一种从语法图中隐藏参数的官方方法。
  • 严格来说,您还必须检查 ${(ignore)} 允许显式将 Boolean 传递给开关(例如,-HiddenSwitch:$true),但为了简洁起见,我在上面的代码中省略了它。

  • 同样,需要做更多的工作来支持传递隐藏参数名称的明确前缀(例如,-Hidden)。


如果在语法图中不显示额外的参数是最重要的,一个——也是次优的——替代方法是使用一个名字晦涩的“私有”变量,比如说$__HiddenSwitch,调用者必须设置以模拟 -HiddenSwitch 参数,被调用者(您的 script/function)在检查后将其删除。

请注意,如果被调用者是在 模块 中定义的,则需要额外的努力才能访问调用者的范围。

这是另一种可能的方法,如果从命令行调用该函数,则额外的参数将被忽略。

Function Test-Parm {

  Param (
    [Parameter(Mandatory=$True)]
      [Int] $Value,
    [Parameter(Mandatory=$False)]
      [String] $FromCode

  )

  $Calledby = $($MyInvocation).ScriptName
  

  If ($CalledBy.Length -eq 0) {
    "Called from Command Line"
  }
  Else { "Called from Code" }
  
}

结果:

PSv7>..\Test\Test-HideParam.ps1
Called from Code
PSv7>Test-Parm -Value 3 -FromCode "NO"
Called from Command Line
PSv7>

HTH