Search code examples
powershellzipunzip

PowerShell partial zip file name


Currently I have a code that extracts a zip file that is uploaded nightly and it has the name CallRecording_1-000-XXXXXXXX the X's represent the date and time that the zip file was generated. What I would like to do is have a powershell script that looks for the partial name. So for example it would look for just CallRecording_1-000 or CallRecording.

At the moment I have the following script:

#expand archive into folder
expand-archive ("Y:\CallRecording_1-000.zip") -destinationPath $folder

#rename zip file with yesterdays date
$yesDateName = $yesDate + ".zip"
Rename-Item "Y:\CallRecording_1-000.zip" -NewName $yesDateName

The scripts that I have found previously that use partial names seems to focus mostly on the extension rather than the name itself.

Any help would be appreciated!


Solution

  • It sounds like you only expect 1 zip file however I tailored this answer around the possibility of having more than 1

    • We are going to use Get-ChildItem to get any zip files from y:\ that match 'CallRecordings*.zip'
    • We then pipe these files one at a time to the ForEach-Object cmdlet where we
      • assign the extraction folder
      • unzip the file
      • and then rename the file.

    $i is used to allow us different names for our renamed zip file in case there are more than 1 being processed.

        $i = 0
        Get-ChildItem -Path 'Y:\' -Filter 'CallRecording*.zip' | ForEach-Object -Process {
            $extractFolder = "C:\temp\$($_.BaseName)"
            $_ | Expand-Archive -DestinationPath $extractFolder 
            
            # ($? tells us if the last command completed successfully)
            if ($?) {
                # only rename file if Expand-Archive was successful
                $_ | Rename-Item -NewName ((Get-Date).AddDays(-1).ToString('yyyyMMdd') + "_$((++$i)).zip")
            }
        }