Powershell to search for files based on words / phrase but also Zip files and within zip files

主宰稳场 提交于 2019-12-18 09:36:28

问题


I have this script...

Which looks at a given network location and then goes through all the folders / subfolders to search for specific words / phrases. Looking to modify to be able to do the same for ZIP files. Working in the same manner, report back any ZIP files which contain the words set out but also any files within the ZIP...

Any help?

"`n" 
write-Host "Search Running" -ForegroundColor Red
$filePath = "\\fileserver\mydepts\IT"
"`n" 

Get-ChildItem -Recurse -Force $filePath -ErrorAction SilentlyContinue | Where-Object { ($_.PSIsContainer -eq $false) -and  ( $_.Name -like "*test*" -or $_.Name -like "*bingo*" -or $_.Name -like "*false*" -or $_.Name -like "*one two*" -or $_.Name -like "*england*") } | Select-Object Name,Directory,CreationTime,LastAccessTime,LastWriteTime | Export-Csv "C:\scripts\searches\csv\results.csv" -notype

write-Host "------------END of Result--------------------" -ForegroundColor Green

回答1:


If you have .Net 4.5 installed you can use System.IO.Compression.FileSystem library to create a function which will open and traverse contents of your zip files

$searchTerms = @( "test","bingo","false","one two","england")
function openZip($zipFile){
    try{
        [Reflection.Assembly]::LoadWithPartialName( "System.IO.Compression.FileSystem" ) | Out-Null;
        $zipContens = [System.IO.Compression.ZipFile]::OpenRead($zipFile);  
        $zipContens.Entries | % {
            foreach($searchTerm in $searchTerms){
                if ($_.Name -imatch $searchTerm){
                    Write-Output ($_.Name + "," + $_.FullName + "," + $_.CompressedLength + "," + $_.LastWriteTime + "," + $_.Length);
                }
            }               
        }
    }
    catch{
        Write-Output ("There was an error:" + $_.Exception.Message);
    }
}  

You can then run something like this to obtain filename,full path within zip, compressed size etc.

Get-ChildItem -Path -$filePath *.zip -Recurse -ErrorAction SilentlyContinue | %  {
    openZip $_.FullName  >> c:\path\to\report.csv
    }



回答2:


You cannot scan the contents of a zip file, since it is compressed and will just come out as garbage. You would have to unzip the file and then search through it.

Follow these instructions: http://www.howtogeek.com/tips/how-to-extract-zip-files-using-powershell/

Copy it down locally and then search for it there, then delete the copies, repeat.



来源:https://stackoverflow.com/questions/21378521/powershell-to-search-for-files-based-on-words-phrase-but-also-zip-files-and-wi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!