【问题标题】:Separating values entered into a string分隔输入到字符串中的值
【发布时间】:2024-01-14 03:28:01
【问题描述】:

所以我正在尝试创建一个 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 继续...:

【问题讨论】:

  • 欢迎来到 *!请发布您的代码,而不是您的代码的屏幕截图 :)
  • 重申之前的“发布文本”消息 [grin] ... 为什么在提问时不上传代码/错误图像? - 元堆栈溢出 — meta.*.com/questions/285551/…
  • 我做到了,在第二个屏幕截图中,当我执行命令时它没有显示任何输出。
  • @Lee 的措辞有点模棱两可:他的意思是你不应该一般使用图像,只能使用文本;图片,如果需要的话,应该只补充文本信息。
  • @agardi - 正如其他人所指出的那样......“文本图像”cmets 是关于不发布文本图像,除非没有其他方法可以完成这项工作。我的链接显示了该想法背后的为什么。 [咧嘴]

标签: powershell parameters parameter-passing


【解决方案1】:

你需要将你的强制参数声明为一个数组,然后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 }
}

【讨论】:

  • @agardi - 请参阅我的更新 - 您必须遍历名称数组的元素。另外,由于我的回答是基于您问题的 original 形式 - 它表现出 not using an array 的问题,我建议您编辑您的问题以显示 原始代码,以便问题和答案匹配。
最近更新 更多