问题:
客户要求我们将提取的数据从我们的系统上传到他们的 box.com 平台,而不是我们正常的 SFTP 实用程序。我有 box.com 凭据,并且知道它们需要 FTPS 而不是 SFTP,并且需要被动模式。我从 ThomasMaurer's Powershell FTP Upload and Download script 抄录了一个片段.我服务器上的 Powershell 版本是 4.0
代码片段为:
#config
$Username = "username@host.com"
$Password = "redactedpassword"
$LocalFile = "C:\path\to\my\file.csv"
$RemoteFile = "ftp://ftp.box.com:990/file.csv"
#Create FTPWebRequest
$FTPRequest = [System.Net.FtpWebRequest]::Create($RemoteFile)
$FTPRequest = [System.Net.FtpWebRequest]$FTPRequest
$FTPRequest.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$FTPRequest.Credentials = New-Object System.Net.NetworkCredential($Username, $Password)
$FTPRequest.UseBinary = $true
$FTPRequest.UsePassive = $true
#read file for upload
$FileContent = gc -en byte $LocalFile
$FTPRequest.ContentLength = $FileContent.Length
#get stream request by bytes
$run = $FTPRequest.GetRequestStream()
$run.Write($FileContent,0,$FileContent.Length)
#cleanup
$run.Close()
$run.Dispose()
错误:
Exception calling "GetRequestStream" with "0" argument(s): "System error." At C:\path\to\my\powershellscript.ps1:28 char:1
+ $Run = $FTPRequest.GetRequestStream()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: () [], MethodInvocationException
+ FullyQualifiedErrorId: WebException
我在调用 $FileContent.Length
属性以及 $run.close
和 $run.dispose()
时也遇到下游错误。
有没有人仅使用 PowerShell 4.0 命令成功地(特别是)自动装箱或被动隐式 ssl,您有我可以重用的可靠模式吗?非常感谢
最佳答案
我正在上传带有 System.Net.WebClient 派生版本的文件,它支持基于 TLS 的 FTP。这可以通过在 PowerShell 中嵌入 C# 代码轻松实现:
$typeDefinition = @"
using System;
using System.Net;
public class FtpClient : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
FtpWebRequest ftpWebRequest = base.GetWebRequest(address) as FtpWebRequest;
ftpWebRequest.EnableSsl = true;
return ftpWebRequest;
}
}
"@
Add-Type -TypeDefinition $typeDefinition
$ftpClient = New-Object FtpClient
$ftpClient.UploadFile("ftp://your-ftp-server/yourfile.name", "STOR", "C:\YourLocalFile.name")
关于PowerShell FTPS 上传失败并显示 "System error.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37606809/