I have a script to which I pass server name(s) in $args.
This way I can do stuff to this (these) server(s) using
foreach
:
.\script.ps1 host1 host2 host3
foreach ($i in $args)
Do-Stuff $i
I'd like to add a named optional parameter called vlan. I've tried:
Param(
[string]$vlan
foreach ($i in $args)
Write-Host $i
Write-Host $vlan
It works if you pass a -vlan
parameter but if you don't then the script auto assigns the last server name to $vlan
.
So, how can you pass single or multiple parameters plus an optional named parameter to a PowerShell script?
Ideally, here are valid examples:
.\script.ps1 host1
.\script.ps1 host1 host2 host3
.\script.ps1 host1 host2 -vlan office
The easiest way is probably to use two parameters: One for hosts (can be an array), and one for vlan.
param([String[]] $Hosts, [String] $VLAN)
Instead of
foreach ($i in $args)
you can use
foreach ($hostName in $Hosts)
If there is only one host, the foreach loop will iterate only once. To pass multiple hosts to the script, pass it as an array:
myScript.ps1 -Hosts host1,host2,host3 -VLAN 2
...or something similar.
–
Parameters take input before arguments. What you should do instead is add a parameter that accepts an array, and make it the first position parameter. ex:
param(
[Parameter(Position = 0)]
[string[]]$Hosts,
[string]$VLAN
foreach ($i in $Hosts)
Do-Stuff $i
Then call it like:
.\script.ps1 host1, host2, host3 -VLAN 2
Notice the comma between the values. This collects them in an array
param(
[Parameter(Position=0)][String]$Vlan,
[Parameter(ValueFromRemainingArguments=$true)][String[]]$Hosts
) ...
This would allow multiple hosts to be entered with spaces.
–
I call a scheduled script who must connect to a list of Server this way:
Powershell.exe -File "YourScriptPath" "Par1,Par2,Par3"
Then inside the script:
param($list_of_servers)
Connect-Viserver $list_of_servers.split(",")
The split operator returns an array of string
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
site design / logo © 2019 Stack Exchange Inc; user contributions licensed under cc by-sa 4.0
with attribution required.
rev 2019.9.23.34994