powershell - 分隔输入到字符串中的值
问题描述
所以我正在尝试创建一个 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 继续...:
解决方案
您需要将您的强制参数声明为一个数组,然后 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 }
}
推荐阅读
- javascript - 将状态项设置回初始状态而不发生变化
- angular - 如果路线守卫不允许您访问,则显示警报
- node.js - SurveyJS 结果
- css - div侧面的条,仅限Firefox
- sql-server - 根据日期查找两种产品之间的差异
- java - out.println(); 不工作的Java SocketServer
- python - 运行时检查功能
- java - 如何在 Java 中填充 JSON 模式的字段
- java - 当 StringBuffer 容量不足时是否创建了一个新的 StringBuffer 对象,或者它仍然是旧的?
- jquery - jQuery - 如何定位“第一”行“没有”属性