Search code examples
powershellwinrar

Adding Multiple files into Winrar archive with Powershell


I have a script that used to work and add multiple files to a Winrar archive, test the archive, then delete the original files. It worked great, then I broke it, and now cannot fix. problem now is that for each file I am adding to the archive, a new Winrar window pops up and tells me that a file is in use by another process.

The powershell here is likely fine, but I think i'm doing something wrong with the rar command and/or the paths.

thanks in advance for any suggestions.

    set-alias rar "c:\Program Files\WinRAR\WinRAR.exe"
$startdate = get-date("7/20/2015 00:00")
$enddate = get-date("7/21/2015 00:00")
$path = "D:\TFS.Backup"
$files = Get-ChildItem $path | Where-Object {$_.creationtime -gt $startdate -and $_.creationtime -lt $enddate}
$filedate = $startdate.day
$fileyear = $startdate.year
$filemonth = $startdate.month
$rarname = "$fileyear-$filemonth-$filedate.rar"
$destination = "$path\archive"
foreach ($file in $files) {rar  a -r -m3 -t -df -mt4 $destination\$rarname $path\$file}

Solution

  • First, you should use $file.fullname instead of $path\$file, for better practice. And second, use rar.exe not winrar.exe to archive via command line, because rar.exe is a console application, and it does not release the script to continue to the next file until this file would be added to the archive. Also it might be needed to use & before rar.