Reputation: 145
I am working on a PowerShell script that is run from another application that is called after a success event and executes a series of commands:
ExampleFile
)My problem starts during the FTP process: as it exists below - the ZIP file is created correctly in the local system, and a ZIP file is created on the FTP server but it's stuck with a filesize of 0 bytes.
From the server, it looks like the upload hangs?
So: Lines 1-3 all work fine and the local zipped file has a non-zero size.
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();
This has me pretty well stumped, so any ideas or thoughts appreciated.
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();
Upvotes: 2
Views: 1098
Reputation: 202514
You are missing a call to FtpWebRequest.GetResponse
:
...
$Run = $FTPRequest.GetRequestStream();
$Run.Write($FileContent, 0, $FileContent.Length);
$Run.Close();
$FTPResponse = $FTPRequest.GetResponse()
Write-Out $FTPResponse.StatusCode
Write-Out $FTPResponse.StatusDescription
See How to: Upload Files with FTP.
Upvotes: 1