Reputation: 5
I have a script that zips files from source for each year into year.zip format. It works fine, but in case if the zip already exists in the destination (same as source) I want to catch this exception and print it to the logs. Below is the code that I have to check if the file exists and then print it to the log. However, it is not doing just that. Can someone point out how to fix this?
Additionally, if zips do exist I want to undo transaction for that particular year (basically undo transaction of [System.IO.Compression.ZipFile]::CreateFromDirectory($Source, $destination))
. I will appreciate if I can get pointers on this as well.
ForEach ($group in $groups){
# delete temp directorty to save space on C:\
if (test-path -path $GroupDirectory){
del $GroupDirectory -recurse -force
}
# Create a new directory for the group
$GroupDirectory = New-Item -Path (Join-Path $TmpDirectory.FullName -ChildPath $group.Name) -ItemType Directory
if (test-path -path $destination$GroupDirectory.zip){
write-output $GroupDirectory.zip" already exists!"
}
# Move files into the new directory
$ZipNames = $group.Group | Move-Item -Destination $GroupDirectory.FullName
# Create the year-specific zip file
[System.IO.Compression.ZipFile]::CreateFromDirectory($GroupDirectory.FullName, ($destination -f $group.Name))
}
Above code creates a folder named "2012" at temp location,...after that what I need is to check if there's file called "2012.zip" in the destination folder. Is test-path smart enough to know the difference?
Upvotes: 0
Views: 1535
Reputation: 2917
Using Test-Path
won't return an exception; it will return $true
or $false
, i.e., a bool. You don't need to use try/catch for this. Just use if/else.
Upvotes: 3