I need to compress several separate files with powershell

Asked

Viewed 168 times

3

I need to assemble a script to compress log files one by one, I arrived on that line, it calls the 7zip, lists the files, but returns "The system cannot find the file specified." where the folder is full of log files.

dir C:\Arquivos\Log\*.log | ForEach-Object { & "C:\Program Files\7-Zip\7z.exe" a $_.BaseName $_.Name }

Thanks in advance for the help.

2 answers

1

sl 'C:\Arquivos\Log'; dir *.log | % {& "${env:ProgramFiles}\7-Zip\7z.exe" a $_.BaseName $_.Name}

1. Enter the folder where you want to create your files or at least point to it:

# Entre na pasta: 
Set-Location 'C:\Arquivos\Log' ...

# Ou aponte para ela: 
pushd 'C:\Arquivos\Log'; dir *.log | ... ; popd

2. Use relative path to the 7zip or, set a path for him:

# Use caminho relativo:
"${env:ProgramFiles}\7-Zip\7z.exe"

# Ou defina o caminho dele:
$7z=(Get-Item -r $env:ProgramFiles -Filter 7-Zip\7z.exe -Force -EA 0).fullname

3. dir C:\Arquivos\Log\*.log and $_.BaseName results in the creation of files in the current working folder where Powershell is or has been started:

# Funciona se o usuario atual tem permição de escrita na pasta atual de trabalho

dir C:\Arquivos\Log\*.log | ForEach-Object { & "C:\Program Files\7-Zip\7z.exe" a $_.BaseName $_.Name }
  • Some issues suggesting the use of items 1 and 2:
Set-Location 'C:\Arquivos\Log'; dir *.log | ForEach-Object {& "${env:ProgramFiles}\7-Zip\7z.exe" a $_.BaseName $_.Name}

# ou...
sl 'C:\Arquivos\Log'; dir *.log | % {& "${env:ProgramFiles}\7-Zip\7z.exe" a $_.BaseName $_.Name}
pushd 'C:\Arquivos\Log' ; dir *.log | ForEach-Object {& "${env:ProgramFiles}\7-Zip\7z.exe" a $_.BaseName $_.Name} ; popd

# ou...
pushd 'C:\Arquivos\Log' ; dir *.log | ? {& "${env:ProgramFiles}\7-Zip\7z.exe" a $_.BaseName $_.Name} ; popd
$7z=(Get-ChildItem -r $env:ProgramFiles -Filter 7-Zip\7z.exe -Force -EA 0).fullname 
Set-Location 'C:\Arquivos\Log'; ls *.log | ForEach-Object {& "$7z" a $_.BaseName $_.Name} 

# Ou...
$7z=(ls -r $env:ProgramFiles -Filter 7-Zip\7z.exe -Force -EA 0).fullname 
sl 'C:\Arquivos\Log'; ls *.log | ? {& "$7z" a $_.BaseName $_.Name} 


1


Why didn’t you compress the files using the native function Compress-Archive?

Works the same way and there will be no dependency for an external tool.

Behold:

dir C:\Arquivos\Log\*.log | % { Compress-Archive -LiteralPath $_ -DestinationPath "$_.zip" }
  • 1

    Thanks Bruno, it worked the way I wanted it. Hug.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.