Powershell 中的 FTPS 上传

FTPS Upload in Powershell

我正在学习 Powershell,并且正在编写一个小脚本,每晚将一组文件上传到 FTPS 服务器。这些文件位于网络共享的子目录中,名称中包含日期。这些文件本身都将以相同的字符串开头,比方说 "JONES_"。我有这个脚本适用于 FTP,但我不太明白我需要做什么才能让它适用于 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"
    }

如果可能的话,我宁愿不必处理第 3 方软件解决方案。

我不确定您是否会将其视为“第 3 方软件”,但您可以 运行 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

使用 psftp 对我不起作用。我无法通过 SSL 连接到 FTP。我最终(不情愿地?)使用带有此代码的 WinSCP:

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

在foreach循环中。