How to get all arguments passed to function (vs. optional only $args)
Asked Answered
K

4

34

$args returns only optional arguments. How can I get all function parameters?

Khelat answered 23/4, 2009 at 12:22 Comment(1)
What exactly are you trying to do?Baroda
B
34

$args returns any undeclared parameters, not optional parameters. So just don't declare parameters.

In PowerShell v2, you can use $PSBoundParameters to get all parameters in a structured way.

Baroda answered 23/4, 2009 at 18:0 Comment(2)
Would this behave in the same way as $@ in bash?Florenceflorencia
(Technically $@ without quotes is an error; you mean "$@".)Alrzc
T
41

$PSBoundParameters gets you all the parameters that were "bound" along with the bound values in a hashtable, it doesn't get you the optional/extra arguments. That is what $args is for. AFAICT the only way to get what you want is to combine the two:

$allArgs = $PsBoundParameters.Values + $args
Toluene answered 3/5, 2009 at 22:1 Comment(0)
B
34

$args returns any undeclared parameters, not optional parameters. So just don't declare parameters.

In PowerShell v2, you can use $PSBoundParameters to get all parameters in a structured way.

Baroda answered 23/4, 2009 at 18:0 Comment(2)
Would this behave in the same way as $@ in bash?Florenceflorencia
(Technically $@ without quotes is an error; you mean "$@".)Alrzc
H
1

$MyInvocation.Line is also a good one to know.

But that will include the actual command as well.

Hothead answered 29/8, 2023 at 20:47 Comment(0)
P
0

useful way to dynamically inspect and display the parameters of a function

Write-Host "Parameters and Default Values:"
foreach ($param in $MyInvocation.MyCommand.Parameters.keys) {
    Write-Host "${param}: $(Get-Variable -Name $param -ValueOnly -ErrorAction SilentlyContinue)"
}

and params with values only

Write-Host "Parameters and Default Values:"
foreach ($param in $MyInvocation.MyCommand.Parameters.keys) {
    $value = Get-Variable -Name $param -ValueOnly -ErrorAction SilentlyContinue
    if (-not $null -eq [string]$value) {
        Write-Host "${param}: $value"
    }
}
Pyrogallol answered 17/10, 2023 at 20:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.