首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用PowerShell遍历目录中的文件

使用PowerShell遍历目录中的文件
EN

Stack Overflow用户
提问于 2013-09-17 18:16:38
回答 4查看 611.2K关注 0票数 285

如何更改以下代码以查看目录中的所有.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
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2013-09-17 19:37:14

试一试:

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')
}
票数 421
EN

Stack Overflow用户

发布于 2013-09-17 18:23:56

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

$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
}
票数 115
EN

Stack Overflow用户

发布于 2016-04-28 23:24:00

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

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

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

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

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

票数 40
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18847145

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档