How do I get the number of named parameters in a powershell script?

Visa. ABC.ps1 has this

param(
[bool]$A= $False,
[bool]$B= $False,
[bool]$C= $False
)

$count=$Args.Count
Write-Host "$count"

      

If I call this:. \ ABC.ps1 $ True $ True $ True It should display 3.

This is just a guess, but $ Args.Count is always zero, possibly because Args has no / count named arguments.

+3


source to share


3 answers


The number of named parameters can be obtained from $ psboundparameters

&{param(
[bool]$A= $False,
[bool]$B= $False,
[bool]$C= $False
)
$psboundparameters | ft auto
$psboundparameters.count
} $true $true $true

Key Value
--- -----
A    True
B    True
C    True


3

      



$ arg really only contains unbound parameters.

+6


source


$ args will contain a count that exceeds the number of named parameters (unbound parameters). If you have three named parameters and you pass five arguments, $ args.count will output 2.

Be aware that if the CmdletBinding attribute is present, then the remaining arguments are not allowed and you will receive an error message:

function test
{
    [cmdletbinding()]
    param($a,$b,$c)
    $a,$b,$c    
}

test a b c d

test: A positional parameter cannot be found that accepts argument 'd'.

      



To allow the remaining arguments, you must use the parameter's ValueFromRemainingArguments attribute. Now all unbound arguments will accumulate in $ c:

function test
{
    [cmdletbinding()]
    param($a,$b,[Parameter(ValueFromRemainingArguments=$true)]$c)
    "`$a=$a"
    "`$b=$b"
    "`$c=$c"    
}

test a b c d

$a=a
$b=b
$c=c d

      

+2


source


The named parameter is bound to $psboundparameters.count

, any other additional arguments are bound to $args.count

, the resulting arguments are passed($psboundparameters.count + $args.count).

Check it:

param(
[bool]$A,
[bool]$B,
[bool]$C
)

$count=$Args.Count
Write-Host "$a - $b - $c - $($args[0]) - $count"

$psboundparameters.count

$args.count

      

name it .\abc.ps1 $true $true $true $false

+1


source







All Articles