Tutorial :Exception Handling in Powershell 1.0


I am using the following code to upload a file using PowerShell 1.0. How can I tell if the upload completed successfully or if there was an error? I need to delete the file if the upload was successful.

What I have tried:
1. the trap clause. Cant seem to get this one to work.
2. Checking the return value of $webclient.UploadFile -- this seems to always be an empty string, success or not

$File = "D:\Dev\somefilename.zip"  $ftp = "ftp://username:password@example.com/pub/incoming/somefilename.zip"

"ftp url: $ftp"

$webclient = New-Object System.Net.WebClient $uri = New-Object System.Uri($ftp)

"Uploading $File..."

$webclient.UploadFile($uri, $File)


Drop the trap down into a new scope so that you trap on the exception thrown by Upload e.g.:

$succeeded = $true;  & {      trap { $script:succeeded = $false; continue }      $webclient.UploadFile($uri, $File)  }  if ($succeeded) { 'Yay!' } else { 'Doh!' }  

You could also try to catch a specific exception like so:

trap [System.Net.WebException] { ... }  


The UploadFile method is synchronous. If it completes without throwing an exception, you have had success. You should get a trappable WebException if it fails.


I'll leave out details about error trapping, as it appears you are familiar with it already.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »