0

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
AdamL
  • 12,421
  • 5
  • 50
  • 74
Shahpari
  • 115
  • 2
  • 8

1 Answers1

1

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

Theo
  • 57,719
  • 8
  • 24
  • 41
  • 1
    The __best__ compression is reached with the switch `-m5` while the switch `-m4` is just for __good__ compression. There could be used also the *WinRAR* command `m` (move) instead of the *WinRAR* command `a` (add) with switch `-df` (delete file/folder). That is explained all in help of *WinRAR* which is installed with *WinRAR* and can be opened in started *WinRAR* by clicking in last menu __Help__ on first item __Help topics__, expanding on first tab __Contents__ the list item __Command line mode__ and read the referenced help pages. That is just for all *WinRAR* users who read never the help. – Mofi Nov 14 '22 at 17:39
  • I recommend to read also [How to compress each subfolder in a folder into a separate RAR archive using WinRAR?](https://stackoverflow.com/a/24936153/3074564) What I wrote in this answer can be used also to compress each file in a folder into a separate archive. There is no PowerShell script needed at all. The task can be done with just a few mouse button clicks in *WinRAR* (seven mouse button clicks after browsing to the directory with the text files). – Mofi Nov 14 '22 at 17:39