我在一个位置有很多.txt文件。此txt内容如下所示。
%-ile | Read (ms) | Write (ms) | Total (ms) ----------------------------------------------
min | N/A | 0.018 | 0.018
25th | N/A | 0.055 | 0.055
50th | N/A | 0.059 | 0.059
75th | N/A | 0.062 | 0.062
90th | N/A | 0.070 | 0.070
95th | N/A | 0.073 | 0.073
99th | N/A | 0.094 | 0.094
3-nines | N/A | 0.959 | 0.959
4-nines | N/A | 67.552 | 67.552
5-nines | N/A | 75.349 | 75.349
6-nines | N/A | 84.994 | 84.994
7-nines | N/A | 85.632 | 85.632
我正在从上面的内容中阅读3-9,并且想要编写一个程序,像它,道达尔(ms)列的值大于1,关于3-9行,它应该打印那个文件名。为此,我编写了如下程序:
$data = get-content "*.txt" | Select-String -Pattern "3-nines"
$data | foreach {
$items = $_.split("|")
if ($items[0] -ge 1 ) {Echo $items[1]}
}但是越来越少的错误。
Method invocation failed because [Microsoft.PowerShell.Commands.MatchInfo] doesn't contain a method named 'split'.
At line:2 char:18
+ $items = $_.split <<<< ("|")
+ CategoryInfo : InvalidOperation: (split:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Cannot index into a null array.
At line:3 char:12
+ if ($items[ <<<< 0] -lt 1 ) {Echo $items[1]}
+ CategoryInfo : InvalidOperation: (0:Int32) [], RuntimeException
+ FullyQualifiedErrorId : NullArray你能帮帮我吗。我对powershell脚本非常陌生。
发布于 2016-09-06 05:15:49
变化
$items = $_.split("|")至:
$items = ([string]$_).split("|")匹配的内容作为数组返回,并且没有拆分方法。将其转换为字符串将为您提供拆分方法。
更新:要打印文件名,您必须稍微更改脚本,因为String的当前输入是一个数组,因此您需要松掉文件名:
Select-String -Pattern "3-nines" -Path "*.txt" | foreach {
$items = ([string]$_).split("|")
if ([double]$items[3] -ge 1 ) {
Write-Output "FileName: $($_.Filename)"
Echo $items[3]
}
}发布于 2016-09-06 05:57:29
首先-你为什么要在这里向Select-String吹烟斗?您可以使用-Path参数并直接将*.txt传递给它。
split不起作用的原因是您应该再次调用[Microsoft.PowerShell.Commands.MatchInfo]对象的[Microsoft.PowerShell.Commands.MatchInfo]属性。我想你需要的是一个简单的Where-Object
Select-String -Pattern 3-nines -Path *.txt |
Where-Object { [double]($_.line.Split('|')[-1]) -gt 1 } |
Select-Object Path, Line或者,您可以使用Import-Csv cmdlet将文件的内容转换为对象:
foreach ($file in Get-ChildItem -Path *.txt) {
# Existing headers are terrible - replacing them...
$3nines = Import-Csv -Path $file.FullName -Delimiter '|' -Header Percent, Read, Write, Total |
Where-Object Percent -match 3-nines
if ([double]$3nines.Total -gt 1) {
$3nines | Select-Object *, @{
Name = 'Path'
Expression = { $file.FullName }
}
}
}https://stackoverflow.com/questions/39340902
复制相似问题