Link to home
Start Free TrialLog in
Avatar of introlux
introluxFlag for United Kingdom of Great Britain and Northern Ireland

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
Avatar of Qlemo
Qlemo
Flag of Germany image

Appropriate error handling cannot be done on an "anonymous" base, because you need to know exactly how to treat which exceptions. So it depends on your code.

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.
Avatar of 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

Open in new window

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.
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
Avatar of Qlemo
Qlemo
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks!! Spot on!