1

I have a powershell script that archives all files that aren't ps1 and csv files, and it works, but if the zip archive already exists, I have to copy the archive or delete it before running the command again, otherwise the Error appears indicating that the file already exists.

Get-ChildItem -Path .\* -Exclude *.ps1, *.csv | Compress-Archive -DestinationPath .\NonEssArch.zip -verbose

Add-Type -AssemblyName PresentationFramework

$msgBoxInput =  [System.Windows.MessageBox]::Show('Do you also want to delete these non-essential files?','Attention','YesNo','Info')

switch  ($msgBoxInput) {
  'Yes' {
  del -Path *.* -Exclude *.csv, *.ps1, *.zip
  }
  'No' {
  Exit
  }
}

I want to be able to run the script after the archive has already been created, without having it replacing the existing archive. The problem lies in the "-DestinationPath .\NonEssArch.zip" part, but I am having trouble implementing a numbering system of sort.

Any help will be appreciated, thanks.

2
  • 1
    the simplest way is to add a timestamp to the file name. since you can get as granular as you want [right down to milliseconds], there aint likely to be any file name collisions. [grin] something like >>> $NewFileName = 'NonEssarch_{0}.zip' -f (Get-Date).ToString('yyyy-MM-dd_HH-mm-ss') <<< otta do the job. Commented May 4, 2019 at 17:10
  • you are most welcome! glad to have helped somewhat ... [grin] Commented May 4, 2019 at 17:45

1 Answer 1

2

the simplest way to "unique-ify" a file name is to add a timestamp to it. you can adjust the granularity to suit your situation. right down to milliseconds if needed. [grin]

something like this ...

$NewFileName = 'NonEssArch_{0}.zip' -f (Get-Date).ToString('yyyy-MM-dd_HH-mm-ss')

right now, that would give you ...

NonEssArch_2019-05-04_17-12-27.zip
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.