![](/img/trans.png)
[英]Downloading files from multiple directory in one FTP Connection with FTPWebRequest in .NET
[英]Downloading multiple files from FTP site using PowerShell
我想使用 Windows 7 的 PowerShell 5.0 从 FTP 下载多个文件。我编写的脚本适用于单个文件,但不适用于具有通配符的多个文件。 有人可以告诉我我做错了什么吗? 当我执行脚本时,我收到一条错误消息:
Exception calling "DownloadFile" with "2" argument(s): "An exception occurred during a WebClient request."At
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'
DownloadFile
如何知道如何处理您的星号? 您已经在$file
变量中获得了这些信息。 仅以文件夹路径开头,而不是完整的本地文件名:
$localfolder = "C:\Users\database\Nightly_Files\"
您也可以使用一个if
而不是三个使用-like
运算符:
if ($file -like "file[1-3].nightly.out.$YestDate")
并启动下载连接本地路径与文件名:
$webclient.DownloadFile($fileuri, "$localfolder$file")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.