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

使用MemoryStream、WinSCP和PowerShell创建远程文件报错求助

问题排查与解决方案

错误原因分析

你的报错源于**New-Object语法误用**及对Session.PutFile参数逻辑的误解:

  1. 你将远程文件路径($FtpTriggerDirectory + $file.fullname)作为参数传给New-Object System.IO.MemoryStream,但MemoryStream构造函数不接受字符串路径参数,导致New-Object接收到一个对象数组,触发类型转换错误。
  2. Session.PutFile的正确参数顺序是:第一个参数为本地数据来源(流/文件路径),第二个参数为远程目标路径,你错误地将远程路径塞给流的构造函数,而非作为PutFile的第二个参数。

修正后的代码

正确调用PutFile创建空触发文件

function SftpCreateTriggerFile {
    param(
        [WinSCP.Session]$session,
        [string]$FtpTriggerDirectory,
        [System.IO.FileInfo]$file,
        [WinSCP.TransferOptions]$transferOptions
    )

    # 创建空的MemoryStream
    $emptyStream = New-Object System.IO.MemoryStream
    # 安全拼接远程触发文件路径
    $remoteTriggerPath = Join-Path -Path $FtpTriggerDirectory -ChildPath $file.Name
    # 上传空流到指定远程路径
    $session.PutFile($emptyStream, $remoteTriggerPath, $transferOptions)
    # 释放流资源
    $emptyStream.Dispose()
}

关键修正点

  • 单独创建空MemoryStream(无参数默认即为空流)
  • 用Join-Path拼接路径,避免手动拼接出现分隔符错误
  • 将远程路径作为PutFile的第二个参数传入,而非流的构造参数

替代简化方案(创建空文件)

如果仅需创建空文件,可直接调用WinSCP的Session.CreateFile方法,无需借助MemoryStream,代码更简洁:

$remoteTriggerPath = Join-Path -Path $FtpTriggerDirectory -ChildPath $file.Name
$session.CreateFile($remoteTriggerPath)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 13:26:06