通过文本文件搜索
Searching through a text file
我有一个脚本可以搜索最新修改的日志文件。然后假设读取该文本文件并选择一个关键短语,然后显示它后面的行。
到目前为止我有这个
$logfile = get-childitem 'C:\logs' | sort {$_.lastwritetime} | where {$_ -notmatch "X|Zr" }| select -last 1
$error = get-content $logfile | select-string -pattern "Failed to Modify"
它读取的示例行是这样的
20150721 12:46:26 398fbb92 To CV Failed to Modify
CN=ROLE-x-USERS,OU=Role Groups,OU=Groups,DC=gyp,DC=gypuy,DC=net
MDS_E_BAD_MEMBERSHIP One or more members do not exist in the directory
我试图获得的关键信息是
有人可以帮忙吗?
谢谢
试试这个:
$error = get-content $logfile |
Where-Object { $_ -like "*Failed to Modify*" } |
Select-Object -First 1
前提是您要查找文件中的第一个匹配项。 Select-String
cmdlet returns 一个 MatchInfo
对象。根据您的要求,如果您只是想找出文件中第一次出现的错误,则可能没有理由增加那种复杂程度。
如果做不到这一点,我的建议是调试它并逐步完成它。中断 Get-Content
调用并查看 $logfile
是什么。 运行 Get-Content $logfile
看看内容是什么样的。然后在该输出上执行 Select-String
。看看 MatchInfo.ToString()
是什么样子的。也许你会看到一些脱节。
同样,我的建议是手动解析文件并在此时使用 Where-Object
cmdlet。
这应该有效:
get-childitem 'c:\logs' | where {$_.Name -notmatch "X|Zr" } | sort {$_.lastwritetime} | select -last 1 | select-string "Failed to Modify"
但我不喜欢 "X|Zr" 部分。如果您的日志文件有 .txt 扩展名,它不会列出它们,因为您说您不希望任何文件的全名包含 "x" 或 "zr"。使用$_.BaseName
(不带扩展名的名称),或修改正则表达式。
我有一个脚本可以搜索最新修改的日志文件。然后假设读取该文本文件并选择一个关键短语,然后显示它后面的行。
到目前为止我有这个
$logfile = get-childitem 'C:\logs' | sort {$_.lastwritetime} | where {$_ -notmatch "X|Zr" }| select -last 1
$error = get-content $logfile | select-string -pattern "Failed to Modify"
它读取的示例行是这样的
20150721 12:46:26 398fbb92 To CV Failed to Modify CN=ROLE-x-USERS,OU=Role Groups,OU=Groups,DC=gyp,DC=gypuy,DC=net MDS_E_BAD_MEMBERSHIP One or more members do not exist in the directory
我试图获得的关键信息是
有人可以帮忙吗? 谢谢
试试这个:
$error = get-content $logfile |
Where-Object { $_ -like "*Failed to Modify*" } |
Select-Object -First 1
前提是您要查找文件中的第一个匹配项。 Select-String
cmdlet returns 一个 MatchInfo
对象。根据您的要求,如果您只是想找出文件中第一次出现的错误,则可能没有理由增加那种复杂程度。
如果做不到这一点,我的建议是调试它并逐步完成它。中断 Get-Content
调用并查看 $logfile
是什么。 运行 Get-Content $logfile
看看内容是什么样的。然后在该输出上执行 Select-String
。看看 MatchInfo.ToString()
是什么样子的。也许你会看到一些脱节。
同样,我的建议是手动解析文件并在此时使用 Where-Object
cmdlet。
这应该有效:
get-childitem 'c:\logs' | where {$_.Name -notmatch "X|Zr" } | sort {$_.lastwritetime} | select -last 1 | select-string "Failed to Modify"
但我不喜欢 "X|Zr" 部分。如果您的日志文件有 .txt 扩展名,它不会列出它们,因为您说您不希望任何文件的全名包含 "x" 或 "zr"。使用$_.BaseName
(不带扩展名的名称),或修改正则表达式。