Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass dynamic parameters in Powershell?

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.

like image 397
Dennis G Avatar asked Jun 22 '12 08:06

Dennis G


People also ask

How do I pass multiple parameters to a PowerShell function?

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.

How do I set parameters in PowerShell?

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.

What does $_ do in PowerShell?

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.


1 Answers

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.

like image 117
Joey Avatar answered Oct 12 '22 14:10

Joey