繁体   English   中英

使用Powershell递归搜索目录以查找仅包含零的文件

[英]Using Powershell to recursively search directory for files that only contain zeros

我有一个目录,其中包含数百万个二进制格式的文件。 其中一些文件被错误地写入磁盘(不知道如何)。 文件不是空的,但它们仅包含零。 这是一个例子http://pastebin.com/5b7jHjgr

我需要搜索该目录,找到全为零的文件,并将其路径写出到文件中。

我一直在尝试使用format-h​​ex和get-content,但是我有限的powershell经验使我大跌眼镜。 当我只需要前几个字节时,Format-Hex会读取整个文件,而Get-Content需要文本文件。

使用IO.BinaryReader

Get-ChildItem r:\1\ -Recurse -File | Where {
    $bin = [IO.BinaryReader][IO.File]::OpenRead($_.FullName)
    foreach ($byte in $bin.ReadBytes(16)) {
        if ($byte) { $bin.Close(); return $false }
    }
    $bin.Close()
    $true
}

在旧的PowerShell 2.0中,您需要手动过滤它,而不是-File参数:

Get-ChildItem r:\1\ -Recurse | Where { $_ -is [IO.FileInfo] } | Where { ..... }

您可以使用System.IO.FileStream对象读取每个文件的前n个字节。

以下代码读取每个文件的前十个字节:

Get-ChildItem -Path C:\Temp -File -Recurse | ForEach-Object -Process {

    # Open file for reading
    $file = [System.IO.FileStream]([System.IO.File]::OpenRead($_.FullName))

    # Go through the first ten bytes of the file
    $containsTenZeros = $true
    for( $i = 0; $i -lt $file.Length -and $i -lt 10; $i++ )
    {
        if( $file.ReadByte() -ne 0 )
        {
            $containsTenZeros = $false
        }
    }

    # If the file contains ten zeros then add its full path to List.txt
    if( $containsTenZeros )
    {
        Add-Content -Path List.txt -Value $_.FullName
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM