PowerShell FTP上传无法正常工作 - 创建零字节文件

时间:2015-07-20 23:56:55

标签: windows powershell ftp ftpwebrequest

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

  1. 首先,它会压缩指定的文件(ExampleFile
  2. 然后删除原来的
  3. 通过FTP将压缩文件上传到服务器
  4. 我的问题在FTP过程中开始:因为它存在于下面 - 在本地系统中正确创建了ZIP文件,并在FTP服务器上创建了一个ZIP文件,但是文件大小为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();
    

1 个答案:

答案 0 :(得分:1)

您错过了对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