简体   繁体   English

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

[英]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.

相关问题 如何设置 PowerShell Cmdlet 的默认输出格式? - How do you set the default output format for a PowerShell Cmdlet? 动态地将参数添加到Powershell cmdlet - Dynamically add parameters to Powershell cmdlet 我可以覆盖 Powershell 本机 cmdlet 但从我的覆盖中调用它吗 - Can I override a Powershell native cmdlet but call it from my override 具有“动态”ConfirmImpact 属性设置的 Powershell Cmdlet - Powershell Cmdlet with 'dynamic' ConfirmImpact attribute setting 使用对象参数值动态调用Powershell cmdlet - Invoke powershell cmdlet dynamically with object parameter values 如何查找Powershell cmdlet发出的休息电话? - How to find rest call made by powershell cmdlet? Powershell自定义Cmdlet - 在后台线程中调用WriteObject - Powershell Custom Cmdlet - Call WriteObject in Background Thread 忽略 powershell 中 cmdlet 调用中的证书错误 AD - Ignore Certificate Errors AD in cmdlet call in powershell 如何使用PowerShell使用cmdlet显示文件或文件夹的访问权限 - How can you display access permissions of a file or folder using PowerShell using cmdlet 您可以使用强类型/版本化的powershell cmdlet参数,还是使用类似C#的using指令? - Can you use strongly typed / versioned powershell cmdlet parameters, or a C#-like using directive?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM