[英]Can you dynamically set an attribute in a Powershell cmdlet call?
I am not sure if this is possible, but I am wondering if there's an elegant "dynamic" way to use or not an attribute when using a cmdlet in Powershell.我不确定这是否可能,但我想知道在 Powershell 中使用 cmdlet 时是否有一种优雅的“动态”方式来使用或不使用属性。
For instance, in the code below, how can i set the -directory
attribute to be present or not, depending on some conditions?例如,在下面的代码中,如何根据某些条件设置
-directory
属性是否存在?
gci $folder_root -recurse -directory | ForEach{
# do something
}
You can conditionally add parameter arguments to a call through a technique called splatting .您可以通过称为splatting的技术有条件地将参数 arguments 添加到调用中。
All you need to do is construct a dictionary-like object and add any parameters you might want to pass to the call there:您需要做的就是构建一个类似字典的 object 并添加您可能想要传递给调用的任何参数:
# Create empty hashtable to hold conditional arguments
$optionalArguments = @{}
# Conditionally add an argument
if($somethingThatMightBeTrue){
# This is equivalent to having the `-Directory` switch present
$optionalArguments['Directory'] = $true
}
# And invoke the command
Get-ChildItem $folder_root -Recurse @optionalArguments
Notice that any variable that we splat is specified with a @
instead of $
at the call site.请注意,我们splat的任何变量都在调用站点用
@
而不是$
指定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.