如何将两个变量输入到一个命令中

时间:2018-03-14 06:52:39

标签: powershell variables user-input

我被困在这: 用户需要输入两个计算机名称,我不知道如何将它们转换为一个输入(也许我问错了)但这里是代码

elseif ($usersinput -eq 2) 
{
    $pingingtwopcs = Read-Host -Prompt "what are the names of the pc that >you want to ping? (please enter pc names in the next order with comma : >pc1,pc2)"
    foreach ($pcs in $pingingtwopcs)
    {
        Test-Connection -computername $pcs -Count 1
    }
}

请不要提供解决方案,如果有可能请指导我,以便我自己解决。

2 个答案:

答案 0 :(得分:1)

不要使用Read-Host,这是糟糕的设计,不允许自动化。 而是让用户将ComputerName作为字符串和数组提供。

function Write-ComputerName([System.Array]$ComputerName) {
    foreach($oneComputerName in $ComputerName){
        Write-Output $oneComputerName
    }
}

然后用户可以传入一个或多个:

Write-ComputerName 'Bob'
Write-ComputerName @('Bob','Alice')

如果您仍需要根据计算机名称的数量进行自定义逻辑,则可以在函数中使用$ComputerName.Count

答案 1 :(得分:0)

你可以这样做 -

$pingingtwopcs = (Read-Host -Prompt "what are the names of the pc that >you want to ping? (please enter pc names in the next order with comma : >pc1,pc2)").split(',') | ForEach-Object {$_.trim()}

以上行将接受两个值,以comma分隔,一次性转换。由于Read-Host接受String格式的输入,您必须使用Split()方法将它们分开并将其存储在$pingingtwopcs中。 Trim()方法将删除在输入期间输入的任何额外空格。