Powershell 1.0 中的异常处理

发布于 2024-09-12 18:02:17 字数 709 浏览 8 评论 0原文

我正在使用以下代码使用 PowerShell 1.0 上传文件。如何判断上传是否成功完成或是否出现错误?如果上传成功,我需要删除该文件。

我尝试过的:
1.陷阱条款。似乎无法让这个工作。
2. 检查$webclient.UploadFile的返回值——无论成功与否,这似乎总是一个空字符串

$File = "D:\Dev\somefilename.zip"
$ftp = "ftp://username:[email protected]/pub/incoming/somefilename.zip"

“ftp url:$ftp”

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

"正在上传$File..."

$webclient.UploadFile($uri, $File)

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:[email protected]/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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

爱你是孤单的心事 2024-09-19 18:02:17

将陷阱放入新的范围中,以便捕获上传引发的异常,例如:

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

您还可以尝试捕获特定的异常,如下所示:

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

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] { ... }
ゝ杯具 2024-09-19 18:02:17

UploadFile 方法是同步的。如果它完成且没有抛出异常,那么您就成功了。如果失败,您应该得到一个可捕获的 WebException。

http://msdn.microsoft.com/en-us/library/36s52zhs。 aspx

我将省略有关错误捕获的详细信息,因为看来您已经熟悉它了。

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.

http://msdn.microsoft.com/en-us/library/36s52zhs.aspx

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文