首页 > 解决方案 > 如何使用 PowerShell 解析文件夹和文件?

问题描述

我正在尝试构建一个在特定文件夹和其中的日志文件中移动的脚本,并过滤错误代码。之后,它将它们传递到一个新文件中。

我不太确定如何使用 for 循环来做到这一点,所以我将在下面留下我的代码。

如果有人能告诉我我做错了什么,那将不胜感激。

$file_name = Read-Host -Prompt 'Name of the new file: '

$path = 'C:\Users\user\Power\log_script\logs'

Add-Type -AssemblyName System.IO.Compression.FileSystem
function Unzip
{
    param([string]$zipfile, [string]$outpath)

    [System.IO.Compression.ZipFile]::ExtractToDirectory($zipfile, $outpath)
}

if ([System.IO.File]::Exists($path)) {
    Remove-Item $path
    Unzip 'C:\Users\user\Power\log_script\logs.zip' 'C:\Users\user\Power\log_script'
} else {
    Unzip 'C:\Users\user\Power\log_script\logs.zip' 'C:\Users\user\Power\log_script'
}

$folder = Get-ChildItem -Path 'C:\Users\user\Power\log_script\logs\LogFiles'

$files = foreach($logfolder in $folder) {
    $content = foreach($line in $files) {
        if ($line -match '([ ][4-5][0-5][0-9][ ])') {
        echo $line
        }
    }
}


$content | Out-File $file_name -Force -Encoding ascii 

在 LogFiles 文件夹中还有另外三个文件夹,每个文件夹都包含日志文件。谢谢

标签: powershelllogging

解决方案


扩展上面关于递归文件夹结构的评论,然后实际检索文件的内容,您可以尝试以下内容:

$allFiles = Get-ChildItem -Path 'C:\Users\user\Power\log_script\logs\LogFiles' -Recurse

# iterate the files
$allFiles | ForEach-Object {
    # iterate the content of each file, line by line
    Get-Content $_ | ForEach-Object {
        if ($_ -match '([ ][4-5][0-5][0-9][ ])') {
            echo $_
        }
    }
}


推荐阅读