简体   繁体   中英

How to get count of named parameters in a powershell script?

Viz. ABC.ps1 has this

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

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

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

This is just a guess, but $Args.Count is always zero, possibly because it Args doesn't hold/count named arguments.

The number of named parameters can be gotten 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 will indeed contain only the unbound parameters.

$args will hold the count of values that exceeds the named parameters count (unbound parameters). If you have three named parameters and you send five arguments, $args.count will output 2.

Keep in mind that if the CmdletBinding attribute is present, no remaining arguments are allowed and you'll get an error:

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 remaining arguments you will have use the ValueFromRemainingArguments parameter 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

Named Param are bind in $psboundparameters.count any other additional arguments are bind in $args.count the total arguments passed is ($psboundparameters.count + $args.count).

Test it:

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

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

$psboundparameters.count

$args.count

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM