2015-11-06 35 views
4

我收到一組文件以供應商每月處理。這些文件沒有擴展名,但它們具有一致的命名約定。但是,缺少擴展會導致一些問題,因爲有時在那裏存在一個壓縮文件夾,其中包含要處理的代碼的文件名。所以,我正在尋找對每個文件進行布爾檢查的方法,以確認它是否實際上是一個壓縮文件夾。扭曲的是,Excel文件能夠像壓縮文件夾一樣打開(並且有docProps,xl,_rels在裏面。)如何驗證文件是否爲PowerShell中的壓縮文件

我一直試圖get-childitem和Get-Content失敗。 有沒有辦法對文件做一個「測試」,如果它實際上是一個zip文件,則返回true?

回答

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." 
     } 
    } 
} 
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); 

輸出是4b50爲這是衆所周知的是一個ZIP文件,該文件簽名的前兩個字節相匹配的文件,逆轉。

長期來看,使供應商修復他們的系統提供有關文件的更多信息。特別是如果他們是你想要的類型。

如果您需要區分Excel(2007+)和真正的ZIP文件,但沒有擴展名,則會卡住 - 如您所知,只需將.xlsx文件重命名爲.zip即可像任何其他ZIP文件一樣打開 - 沒有任何區別。

+0

我試圖對一個Word,Excel中提供的代碼,拉鍊Word和拉鍊的Excel測試文檔和所有有#4b50作爲結果。 – Phoenix14830

相關問題