如何在Powershell中验证文件是否为zip文件

时间:2015-11-06 22:01:08

标签: powershell

我收到一个供应商每月处理的文件集合。这些文件没有扩展名,但它们具有一致的命名约定。但是,缺少扩展会导致一些问题,有时在那里有一个压缩文件夹,其中包含我要处理的代码的文件名。所以,我正在寻找一种对每个文件进行布尔检查的方法,以确认它是否实际上是一个压缩文件夹。扭曲的是,Excel文件可以像压缩文件夹一样打开(并且其中包含docProps,xl,_rels。)

我尝试使用get-childitem和Get-Content失败了。 有没有办法做一个"测试"在一个文件,如果它实际上是一个zip文件,返回true?

2 个答案:

答案 0 :(得分:4)

Carbon Powershell模块包含一个cmdlet Test-ZipFile,它会告诉您它是否为zipfile。

如果您无法使用该模块,则可以查看file header。这有点难看(时间紧迫)但有效:

$contents = [string](get-content -raw -Encoding Unknown -path $filepath).ToCharArray();

[convert]::tostring([convert]::toint32($contents[0]),16);

对于一个已知为ZIP文件的文件,输出为4b50,该文件与签名的前两个字节相匹配,相反。

从长远来看,让供应商修复他们的系统以提供有关文件的更多信息。特别是如果他们是你想要的类型。

如果你需要区分Excel(2007+)和真正的ZIP文件,没有扩展名,你就会陷入困境 - 正如你所知,你可以将.xlsx文件重命名为.zip并且&#&# 39;像任何其他ZIP文件一样打开 - 没有什么可以区分的。

答案 1 :(得分:0)

我最终做了这样的事情,希望有人发现它很有用:

$ErrorStatus=Start-Process -FilePath $env:7ZipExe -ArgumentList " x $FullFileName -o$env:ProcessingFolder"  -passthru -Wait

If (($ErrorStatus.ExitCode -eq 0) -or ($ErrorStatus.ExitCode -eq $null))
{
    $FileContents=get-childitem -path $FullFileName
    #_rels is a folder in a Word or Excel file when you open it with 7-zip. If it is able to be opened with 7-zip and 
    #  doesn't have that folder, consider the file to be a zip file.
    if (!($FileContents -like "*rels*"))
    {   
        if (!($FileContents -like "*xl*") -and (!($FullFileName.ToLower().EndsWith('.xlsx'))))
        {
            Rename-Item $FullFileName "$FullFileName.xlsx"
        }
        elseif (!($FileContents -like "*word*") -and (!($FullFileName.toLower().EndsWith('.docx')))-and (!($FullFileName.toLower().EndsWith('.xlsx'))))
        {
            Rename-Item $FullFileName "$FullFileName.docx"
        }
    }
    else
    {
        If (!($FileName.ToLower().EndsWith(".zip")))
        {
            Rename-Item $FullFileName "$FullFileName.zip"
            Add-Content $env:LogReportFile "$(Get-Date) - $FileName was a zip file. Added extension."
        }
    }
}