使用 PowerShell 遍历目录中的文件 [英] Loop through files in a directory using PowerShell

查看:62
本文介绍了使用 PowerShell 遍历目录中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何更改以下代码以查看目录中的所有 .log 文件而不仅仅是一个文件?

How can I change the following code to look at all the .log files in the directory and not just the one file?

我需要遍历所有文件并删除所有不包含step4"或step9"的行.目前这将创建一个新文件,但我不确定如何在此处使用 for each 循环(新手).

I need to loop through all the files and delete all lines that do not contain "step4" or "step9". Currently this will create a new file, but I'm not sure how to use the for each loop here (newbie).

实际文件的名称如下:2013 09 03 00_01_29.log.我希望输出文件要么覆盖它们,要么使用相同的名称,并附加out".

The actual files are named like this: 2013 09 03 00_01_29.log. I'd like the output files to either overwrite them, or to have the SAME name, appended with "out".

$In = "C:\Users\gerhardl\Documents\My Received Files\Test_In.log"
$Out = "C:\Users\gerhardl\Documents\My Received Files\Test_Out.log"
$Files = "C:\Users\gerhardl\Documents\My Received Files\"

Get-Content $In | Where-Object {$_ -match 'step4' -or $_ -match 'step9'} | `
Set-Content $Out

推荐答案

试试这个:

Get-ChildItem "C:\Users\gerhardl\Documents\My Received Files" -Filter *.log | 
Foreach-Object {
    $content = Get-Content $_.FullName

    #filter and save content to the original file
    $content | Where-Object {$_ -match 'step[49]'} | Set-Content $_.FullName

    #filter and save content to a new file 
    $content | Where-Object {$_ -match 'step[49]'} | Set-Content ($_.BaseName + '_out.log')
}

这篇关于使用 PowerShell 遍历目录中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆