arraylist 不允许只输入一个主机名以在 powershell 中执行 ping

arraylist doesn't let enter only one host name to ping in powershell

我有一个 ping 脚本,它有以下输入参数

  param(
#Arralist zum Aufnehmen der Hosts.
#[parameter(Mandatory = $true, Position = 0)][System.Collections.ArrayList]$Hosts = @(),
[parameter(Mandatory = $true, Position = 0)][System.String]$Hosts,
#Anzahl Wiederholung pro Host, Standard 10 Jahre
[parameter(Mandatory = $false,Position = 1)][double]$Repetition = 315360000,
#solange wird nichts unternommen, standard 0
[parameter(Mandatory = $false,Position = 1)][double]$Pause = 5,
#Speicherort des Logfile, standard C:\Temp
[parameter(Mandatory = $false,Position = 2)][string]$LogPath = 'C:\Temp\Ping Tool'
)

如果我使用脚本名称和所需参数调用脚本,例如 script.ps1 -hosts www.google.ch, www.youtube.com -repetition 2 脚本将 ping 两个主办 2 次,然后停止。这样就好了。但是问题出现了,如果我只有一个主机(考试。www.google.ch)来ping。它说 The argument transformation for the parameter "Hosts" can't be processed. The value "www.google.ch" of type "System.String" can't be converted to the type "System.Collections.ArrayList".

我该怎么做才能使脚本即使只对一台主机执行 ping 操作也能正常工作?这里的问题是我在参数中定义了一个 Arraylist,这就是为什么它不允许我只输入一个主机来 ping。

移除$Hosts参数的ArrayListSystem.String的转换,并在您的代码中使用foreach迭代每个项目,它会单独处理。 ..

参见示例:

function Test-Input {
param(
$hosts
)
Write-Host The Input is: [ $hosts.GetType().FullName ]

    foreach ($item in $hosts) {
    Write-Host Item: [ $item ]
    }
}

查看结果:

PS > Test-Input -hosts www.google.ch
The Input is: [ System.String ]
Item: [ www.google.ch ]

PS > Test-Input -hosts www.google.ch,www.google.com
The Input is: [ System.Object[] ]
Item: [ www.google.ch ]
Item: [ www.google.com ]