【问题标题】:Stop WhatIf inheritance in cmdlets which don't use SupportsShouldProcess在不使用 SupportsShouldProcess 的 cmdlet 中停止 WhatIf 继承
【发布时间】:2021-07-06 07:15:04
【问题描述】:

阻止WhatIfPreference 被子函数继承的正确方法是什么?

我编写了一些函数,使用WhatIf 参数允许它们在安全/测试模式下运行是有意义的。但是,无论WhatIf 参数如何,这些函数都会调用我想要运行的其他 cmdlet(例如,将日志写入文件)。我假设WhatIfPreference 将被实现SupportsShouldProcess 的命令自动继承(就是这种情况),但是任何没有此属性的命令都不会知道SupportsShouldProcess/@987654329 @,所以会破坏链条。

我可以让那些我想始终运行的 cmdlet 调用任何实现 SupportsShouldProcess-WhatIf:$False 的 cmdlet;但这意味着将这个值放在很多地方,并且鉴于调用上下文不知道SupportsShouldProcess,这似乎是错误的。

我可以在我的所有 cmdlet 上实现 SupportsShouldProcess,然后从我真正想要使用 SupportsShouldProcess 的那些中调用我想要始终使用 -WhatIf:$False 运行的那些;但是再次实现某些东西而不使用它感觉很愚蠢。

我敢肯定那里有更好的选择;但我目前还没有找到。

这种继承的例子:

Function Nest1 {
    [CmdletBinding(SupportsShouldProcess)]
    Param ()
    "Nest1 $WhatIfPreference"
    Nest2
}

Function Nest2 {
    [CmdletBinding()]
    Param ()
    "Nest2 $WhatIfPreference"
    Nest3
    Nest3 -WhatIf:$false
}

Function Nest3 {
    [CmdletBinding(SupportsShouldProcess)]
    Param ()
    "Nest3 $WhatIfPreference"
}

使用和不使用 -WhatIf 参数调用这些函数会产生以下行为:

Nest1
# Output:
#  Nest1 False
#  Nest2 False
#  Nest3 False
#  Nest3 False

Nest1 -WhatIf
# Output:
#  Nest1 True
#  Nest2 True
#  Nest3 True
#  Nest3 False

我想要的是这样的:

Nest1 -WhatIf
# Output:
#  Nest1 True
#  Nest2 False     # as it doesn't implement SupportsShouldProcess
#  Nest3 False     # as its caller doesn't implement SupportsShouldProcess
#  Nest3 False     # multiple reasons (caller and -WhatIf:$False)

【问题讨论】:

  • $WhatIfPreference variable 始终存在,默认为 $false 并且(与其他变量一样)不会自发改变。 (在给定范围内)。 SupportsShouldProcess argument(或不存在)不会改变 $WhatIfPreference 的值...
  • 另一方面,$WhatIfPreference 变量将其值保持在给定范围内,直到更改(如果通过赋值语句或在支持它的调用者中使用 -WhatIf 显式更改,则无关紧要) …
  • 谢谢@JosefZ;这就说得通了;我只是希望当SupportsShouldProcess 没有实现时,该值将在该函数的范围内设置回false(因此默认情况下是任何子进程的范围);或者至少有一种方法可以很容易地导致这种行为。

标签: powershell powershell-core powershell-5.1


【解决方案1】:

我当前的解决方案是将$WhatIfPreference = $false 设置为任何不实现SupportsShouldProcess 的cmdlet 的第一行,这样他们就不会将此值传递给他们调用的任何cmdlet,即使这些cmdlet 实现@ 987654323@。感觉很hacky,但比其他选项更干净。由于变量范围,幸运的是对该变量的更改不会影响调用者;因此在下面的示例中,两个 Nest1 输出都显示此值为真,即使第二个是在 Nest2 调用之后。

Function Nest1 {
    [CmdletBinding(SupportsShouldProcess)]
    Param ()
    "Nest1 $WhatIfPreference"
    Nest2
    "Nest1 $WhatIfPreference"
}

Function Nest2 {
    [CmdletBinding()]
    Param ()
    $WhatIfPreference = $false
    "Nest2 $WhatIfPreference"
    Nest3
}

Function Nest3 {
    [CmdletBinding(SupportsShouldProcess)]
    Param ()
    "Nest3 $WhatIfPreference"
}

【讨论】:

    猜你喜欢
    • 2021-10-10
    • 2018-07-03
    • 1970-01-01
    • 2023-02-07
    • 1970-01-01
    • 1970-01-01
    • 2010-12-07
    • 2011-11-03
    • 1970-01-01
    相关资源
    最近更新 更多