How to check if a zip file is a Powershell file

I get a collection of files for monthly processing from the supplier. Files do not have an extension, but they have a consistent naming convention. However, the lack of an extension causes some problems, when sometimes there is a compressed folder where there is a file name, I have code to process. So, I am looking for a way to do a logical check for each file to confirm if this is really a compressed folder. The twist is that Excel files can be opened as a compressed folder (and it has docProps, xl, _rels).

I tried unsuccessfully with get-childitem and Get-Content. Is there a way to run a “test” in a file that returns true if it is actually a zip file?

+4
source share
2 answers

In the end, I did something similar, I hope someone finds this useful:

$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."
        }
    }
}
0
source

The Carbon Powershell module includes a cmdlet Test-ZipFilethat tells you whether it is a zip file or not.

If you cannot use this module, you can see the file header . This is a bit ugly (short time), but works:

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

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

The output 4b50for the file, which, as you know, is a ZIP file that corresponds to the first two bytes of the signature, was canceled.

In the longer term, get the provider to fix their system to provide additional file information. Especially if you need them.

Excel (2007+) ZIP , , - , .xlsx .zip, ZIP - .

+4

Source: https://habr.com/ru/post/1614812/


All Articles