14

I want to call an existing commandlet with a dynamic number of parameters.

So instead of doing this (taking write-host as an example), I would like to do it the smart way.

# these are the dynamic parameters which maybe get passed into my function or script
# they would be $null be default of course
$forecolor = 'Green'
$newline = $true

# now build the "dynamic" write-host...
if ($forecolor) {
    if ($newline) {
        write-host -fore $forecolor "Hello world"
    }
    else {
        write-host -fore $forecolor "Hello world" -nonewline
    }
}
else {
    if ($newline) {
        write-host "Hello world"
    }
    else {
        write-host "Hello world" -nonewline
    }
}

This of course is very ugly. Help me make it prettier!

I already tried just setting $forecolor = '-fore Green' which only outputs "-fore Green Hello world". I could think of passing a list of arguments to a function and for each argument in the list add the according parameter - I just don't know how to hold the parameters.

2

1 Answer 1

21

You can just pass your variables as arguments to Write-Host:

Write-Host -Fore $forecolor -NoNewLine:(!$newline) 'Hello World'

For a truly dynamic way you can use a hashtable:

$params = @{ NoNewLine = $true; ForegroundColor = 'Green' }

and then use the splat operator

Write-Host @params Hello World

You can add parameters and their values to the hashtable as you like before calling Write-Host that way.

Sign up to request clarification or add additional context in comments.

3 Comments

Awesome! Here's an article about splatting: technet.microsoft.com/en-us/magazine/gg675931.aspx never heard of that wizardry before. Thanks.
I have been working for years with PowerShell and have never heard about this. Now finally, I did: Great feature!
Your last example already implies this, but just for clarity, you can mix and match as well: Write-Host @params Hello World -BackgroundColor White

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.