powershell - 使用 PowerShell 循环遍历目录中的文件

标签 powershell

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

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

实际文件的命名如下: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

最佳答案

尝试一下:

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 - 使用 PowerShell 循环遍历目录中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18847145/

相关文章:

powershell - 在 Get-ChildItem 中指定 *.xls 过滤器也会返回 *.xlsx 结果

PowerShell:使用 Invoke-Expression 管理错误

powershell - 使用 PowerShell 删除超过 15 天的文件

c# - PowerShell 脚本在 IIS 执行时不返回任何内容

powershell - 如何在Powershell中使用cd命令

windows - 将 powershell 输出导出到文本文件

amazon-web-services - 如何在用户数据中重新启动后运行多个 PowerShell 命令?

xml - 使用 powershell 编辑 XML 文件时转义字符转义 "."

azure - 在 Azure Shell 文本编辑器中创建的文件位于 Azure 门户中的什么位置?

c# - 如何调试 Entity Framework 迁移LoaderExceptions?