Peter Gyger
Peter Gyger

Reputation: 5

Param with more values

Early days with CMD and Batch I use the shift command.

How I do that with PowerShell? Here my sample:

# test.ps1
# start ps script with parameters
param(
    [string]$varmon)

if ($varmon) {
    foreach ($var in $varmon) {
        Write-Host $var
    }
}

PS CLI: .\test.ps1 one two three

I get only "one". How can I start the script with more parameters than one?

Upvotes: 0

Views: 124

Answers (1)

G42
G42

Reputation: 10019

You could use the automatic variable $args:

# test.ps1
# start ps script with parameters
foreach ($var in $args){
    write-host $var
}

Arrays allow you to enter a variable number of arguments - at the end of the day $args is just an automatic array that's created for unassigned variables.

Array parameters are comma delimited, not space - example below.

test.ps1

# test.ps1
# start ps script with parameters
param(
    [int[]]$numbers,
    [string[]]$names
)

if($numbers){
    Write-host "`nYou have entered the following numbers:"
    foreach ($num in $numbers){
        write-host "Number     : $num"
        Write-host "Square root: $([system.math]::sqrt($num))"
    }
}

if($names){
    Write-host "`nYou have entered the following names:"    
    foreach($name in $names){
        Write-host $name
    }
}

Example 1: Without using the parameter names, you will need to keep the arrays in order. So $numbers first, and $names second

PS CLI: .\test.ps1 4,9,16 john,jim,jane


Example 1: With parameter names, you can change the order.

PS CLI: .\test.ps1 -names john,jim,jane -numbers 4,9,16

Upvotes: 2

Related Questions