【问题标题】:FTPS Upload in PowershellPowershell 中的 FTPS 上传
【发布时间】:2016-07-07 21:30:04
【问题描述】:

我正在学习 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 方软件解决方案。

【问题讨论】:

    标签: powershell ftps


    【解决方案1】:

    使用 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 循环中。

    【讨论】:

      【解决方案2】:

      我不确定您是否会将其视为“第三方软件”,但您可以在 Powershell 中运行 PSFTP。以下是您如何做到这一点的示例 (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.exe -l $user -pw $pass $ftp -b batch.psftp -be 替换:$webclient = New-Object System.Net.WebClient $webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass) ?
      • 我认为它替换了您提供的代码中的几行。本质上,它运行 psftp,传入用户名、密码和要运行的命令列表,这意味着一行代码处理相关文件的登录和上传。根据我的统计,这删除了 ​​3 行代码,但您可以选择根据自己的需要实现它。
      猜你喜欢
      • 2016-10-03
      • 2019-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多