-2

I have a string which contains a duration in milliseconds, and I want to get the duration.

For example:

$a="Group policy waited for 904 milliseconds for the network subsystem at computer boot."

How do I get the duration of "904" in the above example?

Matthias
  • 3,582
  • 2
  • 30
  • 41
SA345
  • 251
  • 1
  • 3
  • 3
  • 1
    Hi, what have you tried? There are lots of ways to do this.. Have you considered regex? Or can you split the string at a certain length, if the duration will always start at the same point in the string? – msturdy Jan 21 '14 at 11:17

3 Answers3

0

One method would be to extract the value using a regular expression. The following works in your test case and populates the milliseconds variable with the value:

$ex = new-object System.Text.RegularExpressions.Regex('(\d+)(.milliseconds)', [System.Text.RegularExpressions.RegexOptions]::Singleline)
$a="Group policy waited for 904 milliseconds for the network subsystem at computer boot."
        foreach($match in $ex.Matches($a)){
        $milliseconds = $match.Groups[1]
        Write-Host $milliseconds
        }

Further reading here and a good place to play is here.

nimizen
  • 3,345
  • 2
  • 23
  • 34
0

Here is one method. I split on spaces and look for the 5th item in the array.

$a="Group policy waited for 904 milliseconds for the network subsystem at computer boot."
$mil = ($a -split " ")[4]
$mil += " milliseconds"
$mil
Knuckle-Dragger
  • 6,644
  • 4
  • 26
  • 41
0

My input string is not always in english. It can be in other languages, and then the duration is not always in the same point in the string. Also, as the string can be in other language, then the substring "milliseconds" can changed according to the language. What is sure is that in this complete string, there is only one numeric value, which is what I want to get. I found this way: $a="Group policy waited for 904 milliseconds for the network subsystem at computer boot." $is_num_val = $a -match '^.+ ([0-9]+) .+$' $num_val = $matches[1]

SA345
  • 251
  • 1
  • 3
  • 3