2014-09-02 61 views
1

我有一個函數傳遞的ntp-server數組來循環。這是發生了什麼:傳遞一個字符串數組和foreach循環不工作:沒有數組,但一個字符串?

$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似乎是一個不SRING字符串數組和
$服務器不是一個單一的服務器,但所有和長度爲70不是4
的數組的定義似乎不正確,但是爲什麼以及如何? (我試過版本的1行陣列 - 沒有區別)

+1

您運行的是哪個版本的PowerShell?運行你在v4上展示的確切代碼,我會得到預期的結果,而不是你得到的結果。 – TheMadTechnician 2014-09-02 19:14:15

+0

@TheMadTechnician我不知道版本,但這是非常基本的? – gooly 2014-09-02 19:22:16

+0

我得到了解決方案 - 我只好重新啓動ISE - 很有趣。 – gooly 2014-09-02 19:23:49

回答

2

你應該輸入你的參數$srvList作爲數組。

function Get-NtpTime 
{ 
    param(
     [string[]] 
     $srvList 
    ) 

    # ...snip... 
} 
2

基於your comment是重新啓動ISE固定的問題,這聽起來像$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 = @(...)

相關問題