2014-01-21 86 views
-2

我有一個字符串,其中包含持續時間(以毫秒爲單位),我想獲取持續時間。如何從powershell中的子字符串中獲取數字

例如:

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

如何獲得的 「904」,在上面的例子中的時間?

+1

嗨,你有什麼試過?有很多方法可以做到這一點..你有沒有考慮過正則表達式?或者,如果持續時間始終始於字符串中的相同點,您是否可以將字符串分割爲一定長度? – msturdy

回答

0

一種方法是使用正則表達式提取值。在您的測試情況下工作並填充變量的值毫秒:

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

進一步閱讀here併發揮不好的地方就是here

0

以下是一種方法。我分割空間並查找數組中的第5項。

$a="Group policy waited for 904 milliseconds for the network subsystem at computer boot." 
$mil = ($a -split " ")[4] 
$mil += " milliseconds" 
$mil 
0

我的輸入字符串並不總是英文。它可以是其他語言,然後持續時間不總是在字符串中的相同點。另外,由於字符串可以是其他語言,因此可以根據語言更改子字符串「毫秒」。 可以肯定的是,在這個完整的字符串中,只有一個數值,這是我想要得到的。我發現這種方式: $ a =「組策略在計算機啓動時等待網絡子系統904毫秒。」 $ is_num_val = $ a -match'^。+([0-9] +)。+ $' $ num_val = $ matches [1]

相關問題