0

I have the below code which is meant to total up the time offset as the loop rotates (I will then need to divide this by 10 to get the average but first I need to get this bit working).

I'm assuming I need to cast something as [INT] but I've tried multiple locations that would make sense to no avail. I just end up with O's.

$winTimeStripchart = w32tm /stripchart /computer:0.pool.ntp.org /dataonly /samples:10
$WinTimeOffset = $null

For($i=3; $i -le 12; $i++){

    $Offset = $winTimeStripchart[$i].split("-")
    $trimmedOffset = $Offset[1].trim("s")
    $winTimeOffset  = $winTimeOffset + $trimmedOffset
}

Write-Host "Total: $winTimeOffset"
# Now need to divide by 10. 

sample data:

20:30:23, -00.0698082s
20:30:25, -00.0704645s
20:30:27, -00.0708694s
20:30:29, -00.0728990s
20:30:31, -00.0719226s
20:30:33, -00.0749031s
20:30:36, -00.0778656s
20:30:38, -00.0782183s
20:30:40, -00.0752974s
20:30:42, -00.0760958s
1
  • 1
    OK, you want to .Split it on a space if there is a chance the number could be positive. You don't want to cast the number as integer as that will make it zero for all your example values, instead a Decimal may be the best type: PowerShell Data Types. Commented Jul 20, 2014 at 19:36

2 Answers 2

1

You can try this one line command :

$a = w32tm /stripchart /computer:0.fr.pool.ntp.org /dataonly /samples:10 | select -Skip 3 | % {[double]$_.Substring(11,10)} | Measure-Object -Average -sum

$a can also give you maximum and minimum adding Measure-Object params.

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

Comments

0

You'll want to cast to a double rather than int. The following should do it:

[System.Collections.ArrayList]$winTimeStripchart = w32tm /stripchart  /computer:0.pool.ntp.org /dataonly /samples:10
$WinTimeOffset = $null
$winTimeStripchart.RemoveRange(0,3)

foreach($entry in $winTimeStripchart){
$Offset = $entry.split("-")
$trimmedOffset = $Offset[1].trim("s")    
$winTimeOffset  = [double]$winTimeOffset + [double]$trimmedOffset
}

Write-Host "Total: $winTimeOffset"
Write-Host "Average: $($winTimeOffset/$winTimeStripchart.count)"

Sample output:

Total: 6.1581437
Average: 0.61581437

I've make some other tweaks to the script as well to make it more scalable:

  • Foreach rather than a for loop
  • Using a list rather than array and stripping first 3 entries.
  • Dividing buy number of entries in list.

regards

Arcas

2 Comments

Is there any particular reason to use $WinTimeOffset = $null instead of [decimal]$WinTimeOffset = 0.0 (or [double])?
Hi Andrew, $WinTimeOffset = $null was legacy code and I just forgot to tweak it.

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.