FTP PowerShell Script

Automated PS script to run a FTP via Windows Task Scheduler using:

  • Powershell.exe -ExecutionPolicy Bypass -command ".'C:path\to\SCRIPTNAME.ps1' optional argument -WindowStyle Hidden
  • For console testing, use Set-ExecutionPolicy RemoteSigned   or --bypass


# Location where csv file is to be created, with results from query.
 $dir = Get-ChildItem -Path "PATH TO DIRECTORY HERE" | Sort-Object LastAccessTime -Descending | Select-Object -First 1
 $reportFile = $dir.name
 $extractfile = "PATH TO DIRECTORY HERE" + $reportFile

#ftp configuration
 $ftpuid = "FTP USERNAME"
 $ftppwd = 'FTP PASSWORD'
 $ftpdoc = "FTP LOCATION"

# Create FTP Rquest Object
 $FTPRequest = [System.Net.FtpWebRequest]::Create("$ftpdoc")
 $FTPRequest = [System.Net.FtpWebRequest]$FTPRequest
 $FTPRequest.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
 $FTPRequest.Credentials = new-object System.Net.NetworkCredential($ftpuid, $ftppwd)
 $FTPRequest.UseBinary = $true
 $FTPRequest.UsePassive = $true

# Read the File for Upload
 $FileContent = gc -en byte $extractfile
 $FTPRequest.ContentLength = $FileContent.Length

# Get Stream Request by bytes
 $Run = $FTPRequest.GetRequestStream()
 $Run.Write($FileContent, 0, $FileContent.Length)

# Cleanup

Remove-Item $extractfile

Comments are closed.