alex2k8
alex2k8

Reputation: 43204

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

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

Upvotes: 34

Views: 33908

Answers (4)

Voytas
Voytas

Reputation: 1

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"
    }
}

Upvotes: 0

Dennis
Dennis

Reputation: 1782

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

But that will include the actual command as well.

Upvotes: 1

Keith Hill
Keith Hill

Reputation: 2389

$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

Upvotes: 42

JasonMArcher
JasonMArcher

Reputation: 15011

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

Upvotes: 34

Related Questions