Home > Blockchain >  Using powershell archive individual files with winrar command line
Using powershell archive individual files with winrar command line

Time:11-15

I am struggling to archive file using PowerShell command with winrar

Folder has some text files N:\Download: abc.txt, xyz.txt

i would like to get output: N:\Download: abc.rar, xyz.rar and delete the text file after archive. and how can I set the compressed level maximum?

https://documentation.help/WinRAR/HELPSwM.htm

here is my sample script

$Source = get-ChildItem -path N:\Download -filter "*.txt"
$Rarfile = "C:\Program Files\WinRAR\WinRAR.exe" 
$Dest = "N:\Download"

&$WinRar a $Source.Fullname $Dest

CodePudding user response:

From the documentation,

  • To delete the files after archiving, use the -df switch
  • To set the compression level use the -m<n> switch

Note, you have defined the full path to the winrar.exe file in variable $Rarfile, but later on you use undefined variable $WinRar..

If you want to create a .rar file for each source file separately, you will need a loop to be able to construct the output .rar filename

Try

$WinRar = "C:\Program Files\WinRAR\WinRAR.exe" 
$Dest   = "N:\Download"

(Get-ChildItem -Path 'N:\Download' -Filter '*.txt') | ForEach-Object {
    $outFile = Join-Path -Path $Dest -ChildPath ('{0}.rar' -f $_.BaseName)
    & $WinRar a -m4 -df $outFile $($_.Fullname)
    # or use 
    # & $WinRar m -m4 $outFile $($_.Fullname)
}

If you do not want WinRar to include the folder structure of the files, append the -ep switch to the command

  • Related