【问题标题】:How to catch specific start-bitstransfer "Proxy authentication is required" exception?如何捕获特定的 start-bitstransfer“需要代理身份验证”异常?
【发布时间】:2014-04-22 13:44:38
【问题描述】:

无论我做什么我都无法捕捉到这种类型的异常:

Start-BitsTransfer : HTTP status 407: Proxy authentication is required.
At line:4 char:6
+      Start-BitsTransfer -Source $url -Destination $fullPath
+      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Start-BitsTransfer], Exception
    + FullyQualifiedErrorId : StartBitsTransferCOMException,Microsoft.BackgroundIntelligentTransfer.Management.NewBitsTransferCommand

我无法使用“invoke-command”和 [System.Management.Automation.RuntimeException] (PSRemotingTransportException),因为运行远程脚本块时不支持 BITS。

怎么做?

【问题讨论】:

标签: powershell try-catch


【解决方案1】:

不是直接回答您的问题,但作为先发制人的解决方案,您可以在尝试开始 BITS 传输之前检查是否需要代理身份验证。它不会捕获该错误,但它会有效地测试相同的条件并允许您对其进行补偿。

您可以做的是创建一个System.Net.WebClient 对象并查看它是否需要代理身份验证:

$WC = New-Object System.Net.WebClient
$ProxyAuth = !$WC.Proxy.IsBypassed("http://www.stackoverflow.com")

现在,如果您使用代理 $ProxyAuth 将是 true,因此您可以根据需要进行测试,如果您运行的是 PSv3 或更高版本,您可以设置 Start-BitsTransfer 的默认参数以使用提供的凭据:

If($ProxyAuth){
    $ProxyCred = Get-Credential -Message "Enter credentials for Proxy Authentication"
    $PSDefaultParameterValues.Add("Start-BitsTransfer:ProxyAuthentication","Basic")
    $PSDefaultParameterValues.Add("Start-BitsTransfer:ProxyCredential",$ProxyCred)
}

现在您可以运行脚本,如果需要代理身份验证,它会要求提供凭据,然后执行您的传输。

其中很多内容来自或改编自PowerShell Magazine

【讨论】:

  • 谢谢。我正在考虑它,但我仍然更喜欢捕获异常方法。想知道它在 C# 中会如何。
【解决方案2】:

你试过什么?从发布的代码片段中,可以合理地假设使用普通的 TryCatch 块在使用 STOP 的 ErrorAction 时会起作用......

尝试{ Start-BitsTransfer -ea STOP ....;}catch{ DoSomething;}

【讨论】:

    【解决方案3】:

    因为这是这个问题的顶级互联网搜索结果,而且帖子太旧了,所以这里有一个对我有用的解决方案:

    try
    {
        Start-BitsTransfer -Source 'https://go.microsoft.com/fwlink/?linkid=2088631' -Destination 'C:\Windows\Temp\Net4.8.exe' -ErrorAction Stop
    }
    catch [System.Exception]
    {
        if($error[0].exception.message -match 'HTTP status 407:')
        {
            'Cannot transfer file with BITS as Proxy authentication is required'
        }
        Else
        {
            'Failed to transfer with BITS. Here is the error message:'
            $error[0].exception.message
        }
        break
    }
    catch
    {
        'Failed to transfer with BITS. Here is the error message:'
        $error[0].exception.message
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-10
      • 1970-01-01
      • 2017-07-02
      • 2012-04-07
      相关资源
      最近更新 更多