阻止WhatIfPreference
被子函数继承的正确方法是什么?
我编写了一些函数,使用WhatIf
参数允许它们在安全/测试模式下运行是有意义的。WhatIf
但是,无论参数如何,这些函数都会调用我想要运行的其他 cmdlet(例如,将日志写入文件) 。我假设这WhatIfPreference
将由已SupportsShouldProcess
实现的命令自动继承(就是这种情况),但是任何没有此属性的命令都不会意识到SupportsShouldProcess
/ WhatIfPreference
,因此会破坏链条。
我可以让那些我想始终运行的 cmdlet 调用任何SupportsShouldProcess
用-WhatIf:$False
;实现的 cmdlet 但这意味着将这个值放在很多地方,并且在调用上下文不知道的情况下似乎是错误的SupportsShouldProcess
。
我可以在我的所有 cmdlet 上实现,然后从我真正想要使用的那些中SupportsShouldProcess
调用我想要始终运行的那些;但是再次实现某些东西而不使用它感觉很愚蠢。-WhatIf:$False
SupportsShouldProcess
我敢肯定那里有更好的选择;但到目前为止我还没有找到它。
这种继承的例子:
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)