我有一个小代码,该代码将日志文件中生成的错误复制到文本文件,但我也希望将错误复制到result.txt的文件名称。
# Path of the log files
$file = "C:Sdemopowershell scriptsdemo folder*.txt"
# Copies the error to the result,txt from log files.
(gc $file) -match 'Error:' > "C:Sdemopowershell scriptsNew folderresult.txt"
,我还想知道可以同时打开该错误已复制的文件。如果是的,我该怎么做?
使用Select-String
。它会自动将文件名和行号添加到输出。
$file = 'C:Sdemopowershell scriptsdemo folder*.txt'
Get-ChildItem $file |
Select-String -Pattern 'Error:' |
Set-Content 'C:Sdemopowershell scriptsNew folderresult.txt'
如果您只想超过每个文件的错误,则可以执行这样的操作:
Get-ChildItem $file | ForEach-Object {
$m = (Get-Content $_.FullName) -match 'Error:'
if ($m) {
$_.FullName, $m | Add-Content 'C:Sdemopowershell scriptsNew folderresult.txt'
}
}
但是,我不建议后者,因为当每行都以文件名为前缀时,要过滤数据要容易得多,并且您可以轻松地从结肠降低的文本中剥离文件名和行号。
<</p>请考虑所有评论:
#Path of the log files
$file= "C:Sdemopowershell scriptsdemo folder*.txt"
$lastFile = [string]::Empty
#Copies the error to the result,txt from log files.
(Get-Content $file) -match 'Error:' |
ForEach-Object {
if ( $_.PSPath -ne $lastFile) { $_.PSPath } # output merely on PSPath change
$_ # output matching line
$lastFile = $_.PSPath
} > "C:Sdemopowershell scriptsNew folderresult.txt"
查看以下命令的输出;您可以使用PSChildName
属性(仅文件名)而不是PSPath
(完全合格的文件名):
(gc $file) -match 'Error:' | % {$_ | get-member -MemberType Properties; '---'}