arraylist没有';不允许在powershell中只输入一个主机名进行ping

arraylist没有';不允许在powershell中只输入一个主机名进行ping,powershell,administrator,Powershell,Administrator,我有一个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,

我有一个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-repeation 2,脚本将ping两台主机2次,然后停止。那太好了。但是,如果我只有一个主机(exam.www.google.ch)来ping,问题就会出现。它表示,
无法处理参数“Hosts”的参数转换。无法将“System.String”类型的值“www.google.ch”转换为“System.Collections.ArrayList”类型。


我能做些什么,这样即使我只ping一个主机,脚本也能工作?这里的问题是,我在参数中定义了一个Arraylist,这就是为什么它不允许我只输入一个主机进行ping。

删除
Arraylist
System.String
$Hosts
参数的强制转换,并在代码中使用
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 ]

thx人。它起作用了。你能给我解释一下为什么它以前不起作用吗?[ArrayList]、[system.string]和不包含所有参数的param之间的区别,如您所说??当您强制为参数指定一个类型时,它会验证它,而不接受其他类型,这是出于设计