introlux
asked on
Try Catch Finally and error handling in PowerShell
Hi,
I have a script and would like to create a handling script that ensures that the script is run successfully.
Any help will be appreciated
introlux
I have a script and would like to create a handling script that ensures that the script is run successfully.
Any help will be appreciated
introlux
ASKER
Here is my code:
$now = [datetime]::now.ToString('ddMMyyyy-HHMM')
Export-Mailbox –Identity "Mailbox1" -PSTFolderPath C:\Folder\mailbox1.$now.pst -Confirm:$false
Export-Mailbox –Identity "Mailbox2" -PSTFolderPath C:\Folder\mailbox2.$now.pst -Confirm:$false
Export-Mailbox –Identity "Mailbox3" -PSTFolderPath C:\Folder\mailbox3.$now.pst -Confirm:$false
Copy-Item -Path c:\Folder\* -Filter *.pst -Destination \\Server\FolderT\ –Recurse
get-childitem c:\Folder | where {$_.CreationTime -lt (date).adddays(-14)} | remove-item -recurse
get-childitem \\Server\Folder\ | where {$_.CreationTime -lt (date).adddays(-14)} | remove-item -recurse
Exit
IMHO there is nothing here you need to encapsulate in try catch blocks here, after you have tested the script to make sure it works in general. If one part fails, the reminder will still work, so the only thing to ascertain should be not to remove the very last copy of each PST. But it is not worth the added effort needed.
ASKER
What if the copy caused an error? Is there a way to notify that the script was completed successfully? Possibly via email will be usefull
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks!! Spot on!
There is the (old) trap statement, defining an error handling for the complete scope it is in. So this is for general (last resort) exception handling.
try is applied to the code in its scriptblock only, and so very specific to that.
That's all we can tell about seeing some code.