Powershell:仅返回搜索的第二行

时间:2015-10-18 05:13:29

标签: powershell

我试图返回我在txt文件上执行的第二行搜索结果。 数据的格式为

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 个答案:

答案 0 :(得分:2)

至于pointed out in the comments graphicImage.DrawString(TextBox1.Text, new Font("Times New Roman", 24, FontStyle.Bold), new SolidBrush(Color.White), new Point(200, 350)); Response.ContentType = "image/jpeg"; bitMapImage.Save (Response.OutputStream, ImageFormat.Jpeg); 应该是-Context的参数,而不是Select-String

ForEach-Object参数采用一个或两个整数来表示您希望包含的每个匹配之前和之后的行数。

在您的情况下,您需要之前的0行和之后的1行,因此参数应为-Context。我可能不会将整个文件加载到变量中,而是直接将0,1指向文件:

Select-String

$RAM = Select-String -Path $file -Pattern "available mbytes :" -Context 0,1 | ForEach-Object { +$_.Context.PostContext[0].Trim() } 将确保+是整数而不是字符串