You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用WinSCP .NET Assembly开发SFTP客户端时遇异常,无法获取错误详情

WinSCP .NET Assembly调用PutFileToDirectory时的错误排查问题

我在使用WinSCP的.NET Assembly开发SFTP客户端时,调用PutFileToDirectory()触发了奇怪的错误。执行以下代码后,流程直接进入catch块:

try {
   $hostDirectory = Get-PathBelowWebRoot -root $pcRoot -file $file
   $remove = $false
   $session.PutFileToDirectory($file.fullName, $hostDirectory, $remove, $options)
}
catch {
   $errorObject = $Error[0]
   Write-Error $errorObject
   $($errorObject.InvocationInfo)
   exit
}

但尝试用$Error[0]获取错误详情时,PowerShell抛出了新错误:

Write-Error: Cannot bind argument to parameter 'Exception' because it is null.

之前用$Error[0]能正常获取错误信息,这次却失效了,想知道该如何获取本次错误的详细内容。

环境信息

  • PowerShell版本:
Major  Minor  Patch  PreReleaseLabel BuildLabel
-----  -----  -----  --------------- ----------
7      3      4
  • 开发环境:Visual Studio Code PowerShell扩展 1.79.0

错误排查建议

  1. 直接使用catch块的$_变量
    在catch块中,当前错误的原始对象默认存储在$_里,直接输出它能获取最完整的错误信息,无需依赖$Error[0]:

    catch {
       Write-Host "错误详情:"
       $_ | Format-List -Force
       $_.InvocationInfo | Format-List -Force
       exit
    }
    
  2. 检查WinSCP专属错误属性
    WinSCP的.NET Assembly可能将错误信息存储在会话对象的LastError属性中,可在catch块中尝试读取:

    catch {
       if ($session.LastError) {
          Write-Host "WinSCP会话错误:"
          $session.LastError | Format-List -Force
       }
    }
    
  3. 避免直接传递$Error[0]给Write-Error
    Write-Error对参数格式有要求,当$Error[0]结构异常时会触发绑定错误,可改为直接输出错误对象的具体属性:

    catch {
       $errorObject = $Error[0]
       Write-Host "错误消息:" $errorObject.Message
       Write-Host "调用位置:" $errorObject.InvocationInfo.PositionMessage
    }
    

内容的提问来源于stack exchange,提问作者aksarben

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 18:42:17