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.
To pass multiple parameters you must use the command line syntax that includes the names of the parameters. For example, here is a sample PowerShell script that runs the Get-Service function with two parameters. The parameters are the name of the service(s) and the name of the Computer.
To create a parameter set, you must specify the ParameterSetName keyword of the Parameter attribute for every parameter in the parameter set. For parameters that belong to multiple parameter sets, add a Parameter attribute for each parameter set.
The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With