How to catch UploadFileAsync error?

$web = New-Object System.Net.WebClient
$web.UseDefaultCredentials = $True
$filename = Read-Host (“file path”)
$File = dir $filename
$TargetFolder = Read-Host (“SharePoint Doc lib URL,example http://sp13/Doc1”)
$TargetFile = $TargetFolder+”/”+$File.name
$web.UploadFileAsync($TargetFile,”PUT”,($File.fullname))
if ($? -eq $false) {$error[0]}

When asynchronizing, how to know an error has occurred?

UploadFileAsync should throw error if an problem occured.

btnw, please format your code when posting in this forum. It’ll make the code readable.

see this post for the instructions: https://powershell.org/forums/topic/read-me-before-posting-youll-be-glad-you-did/

Thanks for your reply.

$web = New-Object System.Net.WebClient
$web.UseDefaultCredentials = $True
$filename = "D:\Install\UlsViewer v6.0.rar"
$File = dir $filename
$TargetFolder = "http://sp16.athena.com/Doc11"
$TargetFile = $TargetFolder+"/"+$File.name

$web.UploadFileAsync($TargetFile,"PUT",($File.fullname))
#$web.UploadFile($TargetFile,"PUT",($File.fullname))
if ($? -eq $false) {$error[0]}

because http://sp16.athena.com/doc11 not exist ,so if use uploadfile will:

$web.UploadFile($TargetFile,"PUT",($File.fullname))
if ($? -eq $false) {$error[0]}

使用“3”个参数调用“UploadFile”时发生异常:“远程服务器返回错误: (409) 冲突。”
所在位置 D:\Script\upload test v1.0.ps1:10 字符: 1
+ $web.UploadFile($TargetFile,"PUT",($File.fullname))
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : WebException

but use UploadFileAsync ,no error to display

From documentation, it throws exception,but for some particular scenarios.

https://docs.microsoft.com/en-us/dotnet/api/system.net.webclient.uploadfileasync?view=netframework-4.8