Tuesday 2 August 2011

Powershell Find Rar files

Script purpose
Find all rar files in a folder and child folders. Then use the Extract-RAR-File function to decompress and remove the rar files.

Script notes
The rar files are matched using the regular expression ".*(?:(?<!\.part\d\d\d|\.part\d\d|\.part\d)\.rar|\.part0*1\.rar)". This could be improved as it matches all rar files and not just the first one is a set. I forget where found this regexp, Thanks to those who wrote it.
I excluded rar files in folders named trash as these have already been extracted.

function Extract-RARs-in-Folder([string]$Folder) {
<#
    .Synopsis
        Extracts all the rar files in the folder
    .Description
    .Example
        Extract-RARs-in-Folder C:\temp\
        would extract C:\temp\foo.rar and C:\temp\bar.rar
    .Parameter Folder
        Path of folder to be processed 
  .Link
        http://heazlewood.blogspot.com
#>
    #reference to source folder
    $basketFolder = get-item -LiteralPath $Folder   

    #Search the basket folder for any rar files
    $rarFiles = get-Childitem -LiteralPath $basketFolder.FullName -recurse |  
    where{$_.Name -match ".*(?:(?<!\.part\d\d\d|\.part\d\d|\.part\d)\.rar|\.part0*1\.rar)"} 
        
    foreach ($rarfile in $rarFiles)
    { 
        #if none are found an empty object is returned filter these by checking if the object exists
        if ($rarfile.Exists -eq $true)
        {
            write-verbose "processing matched rar : $($rarfile.Name)"
            if ($rarfile.Directory.Name -ne "Trash" )
            { 
                #this is a hack needed because I remove or move rar files in the Extract-RAR-File function.
                #regexp should be updated to only match on the first file of a span so this is not needed
                if (Test-Path $rarfile.Fullname  ) 
                {
                    $result = Extract-RAR-File $rarfile.FullName $true
                }
            }
            else
            {
                write-verbose "skipping item due to folder name$($_.FullName)"
            }
        }
    }
}

No comments:

Post a Comment