jms2k
jms2k

Reputation: 81

FTPS Upload in Powershell

I'm in the process of learning Powershell, and am working on a little script that will upload a group of files to an FTPS server nightly. The files are located on a network share in a sub-directory containing the date in the name. The files themselves will all begin with the same string, let's say "JONES_". I have this script working for FTP, but I don't quite get what I need to do to get it to work for FTPS:

# Set yesterday's date (since uploads will happen at 2am)
$YDate = (Get-Date).AddDays(-1).ToString('MM-dd-yyyy')

#Create Log File
$Logfile = "C:\powershell\$YDate.log"
Function LogWrite
{
    Param ([string]$logstring)

    Add-Content $Logfile -value $logstring
}


# Find Directory w/ Yesterday's Date in name
$YesterdayFolder = Get-ChildItem -Path "\\network\storage\location" | Where-Object {$_.FullName.contains($YDate)}


If ($YesterdayFolder) {

    #we specify the directory where all files that we want to upload are contained 
    $Dir= $YesterdayFolder
    #ftp server
    $ftp = "ftp://ftps.site.com"
    $user = "USERNAME"
    $pass = "PASSWORD"

    $webclient = New-Object System.Net.WebClient 
    $webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)


$FilesToUpload = Get-ChildItem -Path (Join-Path $YesterdayFolder.FullName "Report") | Where-Object {$_.Name.StartsWith("JONES","CurrentCultureIgnoreCase")}
foreach($item in ($FilesToUpload))
    { 
        LogWrite "Uploading file:  $YesterdayFolder\Report\$item"
        $uri = New-Object System.Uri($ftp+$item.Name) 
        $webclient.UploadFile($uri, $item.FullName)  
    }
    } Else {
        LogWrite "No files to upload"
    }

I'd rather not have to deal with a 3rd party software solution, if at all possible.

Upvotes: 1

Views: 5861

Answers (2)

morgb
morgb

Reputation: 2312

I'm not sure if you would consider this as "3rd party software" or not, but you can run PSFTP from within Powershell. Here is an example of how you could do that (source):

$outfile=$YesterdayFolder"\Report\"$item.Name
"rm $outfile`nput $outfile`nbye" | out-file batch.psftp -force -Encoding ASCII

$user = "USERNAME"
$pass = "PASSWORD"

&.\psftp.exe  -l $user -pw $pass  $ftp -b batch.psftp -be

Upvotes: 1

jms2k
jms2k

Reputation: 81

Using psftp didn't work for me. I couldn't get it to connect to the FTP over SSL. I ended up (reluctantly?) using WinSCP with this code:

$PutCommand = '& "C:\Program Files (x86)\WinSCP\winscp.com" /command "open ftp://USER:[email protected]:21/directory/ -explicitssl" "put """"' + $Item.FullName + '""""" "exit"' 
Invoke-Expression $PutCommand 

In the foreach loop.

Upvotes: 1

Related Questions