是否将未知数量的值传递给PowerShell脚本参数?
我熟悉如何从命令行接受参数或参数并将其传递给PowerShell:是否将未知数量的值传递给PowerShell脚本参数?,powershell,parameter-passing,Powershell,Parameter Passing,我熟悉如何从命令行接受参数或参数并将其传递给PowerShell: powershell.exe-文件myscript.ps1-计算机服务器1-数据 [CmdletBinding()] Param( [参数(必需=$True)] [字符串]$计算机, [参数(必需=$True)] [字符串]$data ) 这很好,但是如果$computer参数是多个项,并且项数未知,该怎么办?例如: Powershell.exe-文件myscript.ps1-计算机服务器1、服务器2、服务器3-数据 这里
powershell.exe-文件myscript.ps1-计算机服务器1-数据
[CmdletBinding()]
Param(
[参数(必需=$True)]
[字符串]$计算机,
[参数(必需=$True)]
[字符串]$data
)
这很好,但是如果$computer
参数是多个项,并且项数未知,该怎么办?例如:
Powershell.exe-文件myscript.ps1-计算机服务器1、服务器2、服务器3-数据
这里我们不知道将有多少
$computer
项目。总有一个,但可能有2、3、4等。如何最好地实现这样的效果?在参数定义中指定这一点。从[String]
更改为字符串数组[String[]]
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True)]
[string[]]$computer,
[Parameter(Mandatory=$True)]
[string]$data
)
在参数定义中指定此选项。从
[String]
更改为字符串数组[String[]]
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True)]
[string[]]$computer,
[Parameter(Mandatory=$True)]
[string]$data
)
您可以改为使用
[String[]$Computer
使参数[String]$Computer
接受多个字符串(或数组
)
示例:
Function Get-Foo {
[CmdletBinding()]
Param (
[Parameter(Mandatory=$True)]
[String[]]$Computer,
[Parameter(Mandatory=$True)]
[String]$Data
)
"We found $(($Computer | Measure-Object).Count) computers"
}
Get-Foo -Computer a, b, c -Data yes
# We found 3 computers
Get-Foo -Computer a, b, c, d, e, f -Data yes
# We found 6 computers
您可以改为使用
[String[]$Computer
使参数[String]$Computer
接受多个字符串(或数组
)
示例:
Function Get-Foo {
[CmdletBinding()]
Param (
[Parameter(Mandatory=$True)]
[String[]]$Computer,
[Parameter(Mandatory=$True)]
[String]$Data
)
"We found $(($Computer | Measure-Object).Count) computers"
}
Get-Foo -Computer a, b, c -Data yes
# We found 3 computers
Get-Foo -Computer a, b, c, d, e, f -Data yes
# We found 6 computers