我想编写一个powershell ps1脚本,它需要2个参数集( - a -d),每个脚本可以有多达n个属性。如何实现?Powershell参数列表传递像-a <args list> -d <args list>
example : DoTheTask -a <task name 1> <task name 2> ... -d <machine name 1> <machine name 2>...
我想编写一个powershell ps1脚本,它需要2个参数集( - a -d),每个脚本可以有多达n个属性。如何实现?Powershell参数列表传递像-a <args list> -d <args list>
example : DoTheTask -a <task name 1> <task name 2> ... -d <machine name 1> <machine name 2>...
你可以这样做:
param(
[string[]]$a,
[string[]]$d
)
write-host $a
write-host ----
write-host $d
然后就可以调用DoTheTask -a task1,task2 -d machine1,machine2
你可以组织你的任务名称和机器名以这样的方式,他们可以放在一个单独的字符串分隔符。
换句话说,你的-a参数是一个逗号分隔的任务名和你的-d参数是一串逗号分隔的机器名吗?如果是这样,那么你所需要做的就是在脚本开始时将字符串解析为它的组件。
而不是传递字符串,然后分割等,只是通过作为数组。看到我的答案。 – manojlds
如果您传递这些参数传递给脚本本身,你可以充分利用$args
内部变量,虽然键/值映射将因为PowerShell会将每个语句解释为一个参数,所以稍微复杂一点。我建议(和其他人一样)使用另一个分隔符,以便您可以更轻松地进行映射。
不过,如果你想继续做这种方式,您可以使用函数,如下面:
Function Parse-Arguments {
$_args = $script:args # set this to something other than $script:args if you want to use this inside of the script.
$_ret = @{}
foreach ($_arg in $_args) {
if ($_arg.substring(0,1) -eq '-') {
$_key = $_arg; [void]$foreach.moveNext() # set the key (i.e. -a, -b) and moves to the next element in $args, or the tasks to do for that switch
while ($_arg.substring(0,1) -ne '-') { # goes through each task until it hits another switch
$_val = $_arg
switch($_key) {
'-a' {
write-host "doing stuff for $_key"
$ret.add($_key,$_val) # puts the arg entered and tasks to do for that arg.
}
# put more conditionals here
}
}
}
}
}
manojlds:DoTheTask -a task1,task2 -d machine1,machine2这工作正常。有没有一种方法可以在没有(逗号)分隔的情况下给出格式。例如:DoTheTask -a task1 task2 -d machine1 machine2 machine3 –
我自由地尝试一个答案:它是可行的,但相当棘手。看看'$ MyInvocation'变量。使用它的属性'Line','BoundParameters'和/或'UnboundArguments'应该允许你完全按照你喜欢的方式解析参数。 –
我强烈建议您不要尝试修改PowerShell的语法。 – JasonMArcher