2015-10-18 153 views
2

我试图返回我在txt文件上执行的搜索的第二行结果。 的数据是在Powershell:返回仅搜索的第二行

Readings  : \\Server1\memory\available mbytes : 
       2107 

格式我想只得到2107。 这是我到目前为止有:

$file = "D:\PerfTest.txt" # import data 
$data = gc $file 
$RAM = $Data | Select-String -Pattern "available mbytes :" | ForEach-Object -Context 1 

,但它给了我下面的:

Readings  : \\Server1\memory\available mbytes : 
        2107 

但我只想得到这个数字。请帮忙吗?

感谢

我想补充到上述情况,如果我用

$RAM = $Data | Select-String -Pattern "available mbytes :" -Context 1 | Foreach {if ($_ -match '(\d+)$') {$matches[1]}} 

返回整数和小数不。所以用一个小数点什么出来78125,而不是0.78125

+1

'$数据| Select-String -Pattern“available mbytes:”-Context 1 | ForEach-Object {$ _.Context.PostContext [0] .Trim()}' – PetSerAl

+0

这工作完全谢谢 – mattnicola

回答

2

正如已经pointed out in the comments-Context应该是一个参数Select-String,不ForEach-Object

-Context参数需要一个或两个整数来指示要包括的每个匹配前后的行数。

在你的情况下,你需要前面的0行和后面的1行,所以参数应该是0,1。而不是整个文件加载到一个变量的,我可能会直接指向Select-String的文件,而不是:

$RAM = Select-String -Path $file -Pattern "available mbytes :" -Context 0,1 | ForEach-Object { 
    +$_.Context.PostContext[0].Trim() 
} 

+将确保$RAM是一个整数,而不是一个字符串

+0

这个答案也工作。 – mattnicola

+0

使用'$ _。line',如果你还想要这个行的模式 –