您可以在 Powershell cmdlet 调用中动态设置属性吗?

Can you dynamically set an attribute in a Powershell cmdlet call?

我不确定这是否可行,但我想知道在 Powershell 中使用 cmdlet 时是否有优雅的“动态”方式来使用或不使用属性。

例如,在下面的代码中,我如何根据某些条件将 -directory 属性设置为存在或不存在?

gci $folder_root -recurse -directory | ForEach{ 
  # do something
}

您可以通过称为 splatting.

的技术有条件地将参数参数添加到调用中

您需要做的就是构造一个类似字典的对象并添加您可能想要传递给调用的任何参数:

# 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

请注意,我们 splat 的任何变量在调用站点都是用 @ 而不是 $ 指定的。