Skip to content

Instantly share code, notes, and snippets.

@kkbruce
Created May 19, 2020 08:10
Show Gist options
  • Save kkbruce/f24dbb8bd562d74c8a00caed8cdb8107 to your computer and use it in GitHub Desktop.
Save kkbruce/f24dbb8bd562d74c8a00caed8cdb8107 to your computer and use it in GitHub Desktop.
Provide PowerShell upload .zip file to FTPS script
param (
[string]$sourceDir
)
$ftpaddr = "example.com/upload/"
# option
$assemblies = (
"System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL",
"System.IO, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL",
"System.Net, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL")
# csharp code
$sourcecode = @"
using System;
using System.IO;
using System.Net;
namespace NetTool
{
public class FTPS
{
public static string Upload(string ftpaddr, string filepath)
{
string ftppath = string.Format("ftp://{0}",ftpaddr);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftppath);
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.UploadFile;
// support FTPS
request.EnableSsl = true;
request.UseBinary = true;
request.KeepAlive = true;
request.UsePassive = true;
byte[] fileContents;
using (StreamReader sourceStream = new StreamReader(filepath))
{
fileContents = System.Text.Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
}
request.ContentLength = fileContents.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(fileContents, 0, fileContents.Length);
}
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
string status = string.Format("Upload File Complete, status {0}", response.StatusDescription);
return status;
}
}
}
}
"@
# create .net object
Add-Type -ReferencedAssemblies $assemblies -TypeDefinition $sourcecode -Language CSharp
$files = Get-ChildItem -Path $sourceDir -Include *.zip
if ($files) {
foreach ($file in $files) {
$ftpaddr += $file.Name
$status = [NetTool.FTPS]::Upload($ftpaddr, $file.FullName)
Write-Host "Message: $status"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment