将多个值传递给单个 PowerShell 脚本参数 [英] Passing multiple values to a single PowerShell script parameter

查看:30
本文介绍了将多个值传递给单个 PowerShell 脚本参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本,我将 $args 中的服务器名称传递给该脚本.

I have a script to which I pass server name(s) in $args.

这样我就可以使用 foreach 对这个(这些)服务器做一些事情:

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
}

我想添加一个名为 vlan 的命名可选参数.我试过了:

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

如果你传递一个 -vlan 参数,它会起作用,但如果你不传递,那么脚本会自动将最后一个服务器名称分配给 $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.

那么,如何将单个或多个参数以及可选的命名参数传递给 PowerShell 脚本?

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

推荐答案

最简单的方法大概是使用两个参数:一个用于hosts(可以是数组),一个用于vlan.

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)

代替

foreach ($i in $args)

你可以使用

foreach ($hostName in $Hosts)

如果只有一台主机,foreach 循环只会迭代一次.要将多个主机传递给脚本,请将其作为数组传递:

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

...或类似的东西.

这篇关于将多个值传递给单个 PowerShell 脚本参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆