0

I have several folders dir_01, dir_02, dir_03 that I want to backup in a zip file, say, backup.zip. This has to be saved in a folder with today's date. I need to get a .bat file to do the job; no additional third party executables allowed.

Here I found how to create a folder with today's date, but I am having problems to pass $destination to -DestinationPath. I created a .bat that calls PowerShell. Code giving me problems:

powershell.exe $destination = New-Item -Path 'C:\path\to\destionation' -ItemType Directory -Name ("$(Get-Date -f yyyy-MM-dd)") powershell.exe -nologo -noprofile -command Compress-Archive -Path 'C:\path\dir_01', 'C:\path\dir_02', 'C:\path\dir_03' -DestinationPath $destination\backup.zip -Force 

The error message is the following:

New-Object : Exception calling ".ctor" with "2" argument(s): "Access to the path 'C:\backup.zip' is denied." At C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\Microsoft.PowerShell.Archive\Microsoft.PowerShell.Archive.psm1:729 char:30 + ... ileStream = New-Object -TypeName System.IO.FileStream -ArgumentList $ ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvocationException + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand 

However, the code works if I hard-code the path to destination, like this:

powershell.exe -nologo -noprofile -command Compress-Archive -Path 'C:\path\dir_01', 'C:\path\dir_02', 'C:\path\dir_03' -DestinationPath 'C:\whole\path\backup.zip' -Force 

But doing so, I'm unable to save backup.zip in today's folder.

Question: How can I save backup.zip in the folder that I created with today's date?

1 Answer 1

1

You can perform both commands in the same PowerShell session by separating them with a semicolon.

powershell.exe $destination = New-Item -Path 'C:\path\to\destionation' -ItemType Directory -Name ("$(Get-Date -f yyyy-MM-dd)"); Compress-Archive -Path 'C:\path\dir_01', 'C:\path\dir_02', 'C:\path\dir_03' -DestinationPath $destination\backup.zip -Force 

That will launch PowerShell and have it create the folder and then zip things into it in the same session, rather than create a session, in that session create a folder, close the session, start a new PowerShell session, zip things up, close the second session.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.