user2707263
user2707263

Reputation: 113

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

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

Upvotes: 1

Views: 602

Answers (2)

Raf
Raf

Reputation: 10107

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
    }

Upvotes: 2

Cole9350
Cole9350

Reputation: 5570

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.

Upvotes: 0

Related Questions