使用PowerShell 5从ftp站点下载多个文件

时间:2018-02-12 22:27:46

标签: powershell

我想使用Powershell 5.0和Windows 7从FTP下载多个文件。我编写的脚本适用于单个文件,但不适用于带有通配符的多个文件。有人可以告诉我我做错了什么吗? 当我执行脚本时,我得到一个错误说明:

使用“2”参数调用“DownloadFile”的异常:“WebClient请求期间发生异常。” C:\ Users \ Documents \ Powershell_Script \ write-demo7.ps1:49 char:9 + $ webclient.DownloadFile($ fileuri,$ localfilename + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     + CategoryInfo:NotSpecified:(:) [],MethodInvocationException     + FullyQualifiedErrorId:WebException

我搜索了互联网,找不到答案。 请帮忙......

这是我的脚本:

function Get-FtpDir ($url,$credentials)
{
    $request = [Net.WebRequest]::Create($url)
    $request.Credentials = $credentials
    $request.Method = [System.Net.WebRequestMethods+FTP]::ListDirectory
    $response = $request.GetResponse()
    $reader = New-Object IO.StreamReader $response.GetResponseStream()
    $readline = $reader.ReadLine()
    $output = New-Object System.Collections.Generic.List[System.Object]
    while ($readline -ne $null)
    {
        $output.Add($readline)
        $readline = $reader.ReadLine()
    }
    $reader.Close()
    $response.Close()
    $output
}

$server = "msftran.tran.com"
$user = "myusername"
$pass = "mypassword"
$invocation = (Get-Variable MyInvocation).Value
$localpath = Split-Path $invocation.MyCommand.Path
$YestDate = (Get-Date).AddDays(-2).ToString('yyMMdd') 
$remotefilepath = "/"
$localfilename = "C:\Users\database\Nightly_Files\file*.nightly.out."+$YestDate
$localfilelocation = "$localfilename"
$uri = New-Object System.Uri(“ftp://$server/$remotefilepath”)

#List of all files on FTP-Server
$files = Get-FTPDir $uri -credentials (New-Object System.Net.NetworkCredential($user, $pass))

foreach ($file in $files)
{    
   if ($file -eq "file1.nightly.out.$YestDate" -or 
       $file -eq "file2.nightly.out."+$YestDate -or
       $file -eq "file3.nightly.out."+$YestDate)
     {
        $file        
        $fileuri = New-Object System.Uri(“ftp://$server/$remotefilepath/$file”)               
        $webclient = New-Object System.Net.WebClient        
        $webclient.Credentials = New-Object System.Net.NetworkCredential($user, $pass)
        $webclient.DownloadFile($fileuri, $localfilelocation       
        )

     }

}
echo 'download completed'  

1 个答案:

答案 0 :(得分:1)

DownloadFile如何知道如何处理星号?并且您已在$file变量中获得了该信息。而不是完整的本地文件名,只能从文件夹的路径开始:

$localfolder = "C:\Users\database\Nightly_Files\"

使用if运算符,您也可以使用一个-like而不是三个:

if ($file -like "file[1-3].nightly.out.$YestDate")

启动下载连接本地路径,文件名为:

$webclient.DownloadFile($fileuri, "$localfolder$file")