1

I have an array of ntp-server passed at a function to loop through that. This is what happens:

  $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

As you see $srvList seems to be one sring not an array of strings and
$Server is not a single server but all and the length is 70 not 4.
The definition of the array seems to be incorrect but where why and how? (I tried version of 1 line-array - no difference)

3
  • 1
    What version of PowerShell are you running? Running the exact code you show on v4 I get the expected results, not what you got. Commented Sep 2, 2014 at 19:14
  • @TheMadTechnician I don't know the version, but this is very basic? Commented Sep 2, 2014 at 19:22
  • I got the solution - I just had to restart the ISE - funny. Commented Sep 2, 2014 at 19:23

2 Answers 2

2

You should type your $srvList parameter as an array.

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

    # ...snip...
}
Sign up to request clarification or add additional context in comments.

Comments

2

Based on your comment that restarting the ISE fixed the issue, it sounds like $srvA had been declared as a string variable at one point during the session. Once declared with a specific type, PowerShell will coerce any future assignments to the variable's declared type:

> $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

You could fix this in the current session by re-declaring the variable as the desired type, in this case using [string[]]$srvA = @( ... ).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.