首页 > 解决方案 > 分隔输入到字符串中的值

问题描述

所以我正在尝试创建一个 Powershell 菜单,当用户选择一个选项时,它会询问它试图搜索的一个或多个值(例如 Ping 多台计算机)。我目前很难让它发挥作用。我会张贴图片来说明我的意思

当我输入一个名称进行搜索时,命令执行良好,如下所示:

使用输入的一个值

当我尝试使用多个值时,它不起作用:

不使用多个值

这是我拥有的代码的快照:

代码示例

当然,任何帮助都非常感谢。

更新- 11/13

这是我目前拥有的:

function gadc {
   Param(
       [Parameter(Mandatory=$true)]
       [string[]] $cname # Note: [string[]] (array), not [string]
       )
   $cname = "mw$cname"
   Get-ADComputer $cname

}

这是控制台中的输出

cmdlet gadc at command pipeline position 1
Supply values for the following parameters:
cname[0]: imanuel
cname[1]: troyw
cname[2]: hassan
cname[3]: 
Get-ADComputer : Cannot convert 'System.String[]' to the type 
'Microsoft.ActiveDirectory.Management.ADComputer' required by parameter 'Identity'. Specified 
method is not supported.
At line:32 char:19
+    Get-ADComputer $cname
+                   ~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-ADComputer], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.ActiveDirectory.Management.Commands.G 
   etADComputer
 
Press Enter to continue...: 

**And here is the other way with the same result:**

cmdlet gadc at command pipeline position 1
Supply values for the following parameters:
cname[0]: imanuel, troyw

Get-ADComputer : Cannot convert 'System.String[]' to the type 
'Microsoft.ActiveDirectory.Management.ADComputer' required by parameter 'Identity'. Specified 
method is not supported.
At line:32 char:19
+    Get-ADComputer $cname
+                   ~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-ADComputer], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.ActiveDirectory.Management.Commands.G 
   etADComputer

按 Enter 继续...:

标签: powershellparametersparameter-passing

解决方案


您需要将您的强制参数声明为一个数组,然后 PowerShell 的自动提示将允许您一个一个地输入多个-只需在提交最后一个值后自行按下以继续:Enter

function gadc {
  param(
    [Parameter(Mandatory)]
    [string[]] $cname  # Note: [string[]] (array), not [string]
  )
  # Get-ADComputer only accepts one computer name at a time 
  # (via the positionally implied -Identity parameter), so you must loop
  # over the names.
  # The following should work too, but is slightly slower:
  #   $cname | Get-ADComputer 
  foreach ($c in $cname) { Get-ADComputer $c }
}

推荐阅读