我在一个函数中传递了一个ntp-server数组来循环访问它。这就是发生的事情:
$srvA = @(
'0.at.pool.ntp.org',
'1.at.pool.ntp.org',
'2.at.pool.ntp.org',
'3.at.pool.ntp.org'
)
Function Get-NtpTime {
param($srvList)
$srvList
$nSrv = $srvList.Length
foreach ( $Server in $srvList ) {
$nSrv--
Write-Host $Server $nSrv
}
}
Get-NtpTime $srvA
0.at.pool.ntp.org 1.at.pool.ntp.org 2.at.pool.ntp.org 3.at.pool.ntp.org
0.at.pool.ntp.org 1.at.pool.ntp.org 2.at.pool.ntp.org 3.at.pool.ntp.org 70如您所见,$srvList似乎是一个弹簧,而不是一个字符串数组
$Server不是单个服务器,而是所有服务器,长度是70而不是4。
数组的定义似乎是不正确的,但是为什么以及如何定义呢?(我尝试了1行数组的版本-没有区别)
发布于 2014-09-03 05:06:13
您应该以数组形式键入$srvList参数。
function Get-NtpTime
{
param(
[string[]]
$srvList
)
# ...snip...
}发布于 2014-09-08 04:47:35
基于重启ISE修复了该问题的your comment,听起来$srvA在会话期间的某一时刻被声明为字符串变量。一旦使用特定类型声明,PowerShell将强制对该变量声明的类型进行任何未来赋值:
> $a = @( 'one', 'two', 'three' ) # No type declaration
> $a
one
two
three
> [string]$b = @( 'one', 'two', 'three' ) # Declared as string
> $b
one two three
> $b = @( 'four', 'five' ) # Re-using variable declared as string
> $b
four five您可以在当前会话中修复此问题,方法是将变量重新声明为所需的类型,在本例中使用[string[]]$srvA = @( ... )。
https://stackoverflow.com/questions/25630616
复制相似问题