我正在尝试返回对 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
最佳答案
正如已经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
是整数而不是字符串
关于Powershell:仅返回搜索的第二行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33194543/