为了账号安全,请及时绑定邮箱和手机立即绑定

使用PowerShell循环浏览目录中的文件

使用PowerShell循环浏览目录中的文件

如何更改以下代码以查看目录中的所有.log文件,而不仅仅是一个文件?我需要遍历所有文件并删除所有不包含“ step4”或“ step9”的行。当前,这将创建一个新文件,但是我不确定如何在for each此处使用循环(新手)。实际文件的命名如下:2013 09 03 00_01_29.log。我希望输出文件覆盖它们,或者具有相同的名称,并附加“ 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
查看完整描述

3 回答

?
慕村225694

TA贡献1880条经验 获得超4个赞

试试看:


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')

}


查看完整回答
反对 回复 2019-11-25
?
Smart猫小萌

TA贡献1911条经验 获得超7个赞

要获取目录的内容,可以使用


$files = Get-ChildItem "C:\Users\gerhardl\Documents\My Received Files\"

然后,您也可以遍历此变量:


for ($i=0; $i -lt $files.Count; $i++) {

    $outfile = $files[$i].FullName + "out" 

    Get-Content $files[$i].FullName | Where-Object { ($_ -match 'step4' -or $_ -match 'step9') } | Set-Content $outfile

}

放置foreach循环的一种更简单的方法是循环(感谢@Soapy和@MarkSchultheiss):


foreach ($f in $files){

    $outfile = $f.FullName + "out" 

    Get-Content $f.FullName | Where-Object { ($_ -match 'step4' -or $_ -match 'step9') } | Set-Content $outfile

}


查看完整回答
反对 回复 2019-11-25
?
开满天机

TA贡献1786条经验 获得超12个赞

如果您需要递归地在目录中循环查找特定类型的文件,请使用以下命令,该命令将过滤所有doc文件类型的文件

$fileNames = Get-ChildItem -Path $scriptPath -Recurse -Include *.doc

如果需要对多种类型进行过滤,请使用以下命令。

$fileNames = Get-ChildItem -Path $scriptPath -Recurse -Include *.doc,*.pdf

现在,$fileNames变量充当一个数组,您可以从中循环并应用业务逻辑。


查看完整回答
反对 回复 2019-11-25
  • 3 回答
  • 0 关注
  • 975 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信