Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

For instance, in the code below, how can i set the -directory attribute to be present or not, depending on some conditions?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can conditionally add parameter arguments to a call through a technique called splatting.

All you need to do is construct a dictionary-like object and add any parameters you might want to pass to the call there:

# 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading