PowerShell FTP 上传不工作 - 创建零字节文件

PowerShell FTP upload not working - Creating zero byte file

我正在处理 运行 来自另一个应用程序的 PowerShell 脚本,该脚本在成功事件后调用并执行一系列命令:

  1. 首先压缩一个指定的文件(ExampleFile)
  2. 然后把原来的删了
  3. 通过FTP
  4. 将压缩文件上传到服务器

我的问题是在 FTP 过程中出现的:因为它存在于下面 - ZIP 文件在本地系统中正确创建,并且 ZIP 文件在 FTP 服务器上创建但卡住了文件大小为 0 字节。

从服务器上看,上传好像挂了?

所以:第 1-3 行都工作正常,本地压缩文件的大小不为零。

Add-Type -A 'System.IO.Compression.FileSystem';
[IO.Compression.ZipFile]::CreateFromDirectory("ExampleFolder\ExampleFile", "ExampleFolder\ExampleFile_Datestamp.zip");
Remove-Item -Recurse -Force "ExampleFolder\ExampleFile"; 

$Username = "exampleusername"; 
$Password = "examplepassword";
$LocalFile = "C:\Users\example_path\ExampleFolder\ExampleFile.zip";
$RemoteFile = "ftp://exampleserver/examplepath2/ExampleFile_Datestamp.zip";

$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; 

$FileContent = gc -en byte $LocalFile; 
$FTPRequest.ContentLength = $FileContent.Length; 

$Run = $FTPRequest.GetRequestStream(); 
$Run.Write($FileContent, 0, $FileContent.Length); 
$Run.Close(); 
$Run.Dispose();

这让我很困惑,所以任何想法或想法都会受到赞赏。

powershell.exe -nologo -noprofile -command "Add-Type -A 'System.IO.Compression.FileSystem'; [IO.Compression.ZipFile]::CreateFromDirectory(\"ExampleFolder\ExampleFile\", \"ExampleFolder\ExampleFile_Datestamp.zip\"); Remove-Item -Recurse -Force \"ExampleFolder\ExampleFile\"; $Username = \"exampleusername\"; $Password = \"examplepassword\"; $LocalFile = \"C:\Users\example_path\ExampleFolder\ExampleFile.zip\"; $RemoteFile = \"ftp://exampleserver/examplepath2/ExampleFile_Datestamp.zip\"; $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; $FileContent = gc -en byte $LocalFile; $FTPRequest.ContentLength = $FileContent.Length; $Run = $FTPRequest.GetRequestStream(); $Run.Write($FileContent, 0, $FileContent.Length); $Run.Close(); $Run.Dispose();

您未接来电 FtpWebRequest.GetResponse:

...

$Run = $FTPRequest.GetRequestStream(); 
$Run.Write($FileContent, 0, $FileContent.Length); 
$Run.Close(); 

$FTPResponse = $FTPRequest.GetResponse()

Write-Out $FTPResponse.StatusCode
Write-Out $FTPResponse.StatusDescription

参见How to: Upload Files with FTP