【发布时间】:2014-04-06 00:03:43
【问题描述】:
我在 powershell 中从 ftp 下载文件时遇到问题,此脚本尝试设置连接,搜索一些文件(我正确理解了这部分),然后将其下载到工作目录中,但我遇到了问题知道为什么,请帮忙!!
代码如下:
#IP address of DNS of the target % protocol
$protocol="ftp"
$target = "XXXX"
$connectionString = $protocol+"://"+$target
#Method to connect
$Request = [System.Net.WebRequest]::Create($connectionString)
$Request.Method = [System.Net.WebRequestMethods+Ftp]::ListDirectoryDetails
# Set Credentials "username",password
$username = "XXXXXXX"
$password = "XXXXXX"
# Read Username/password
$Request.Credentials = New-Object System.Net.NetworkCredential $username,$password
$Response = $Request.GetResponse()
$ResponseStream = $Response.GetResponseStream()
# Select Pattern to search
$pattern = "CCS"
# Set directory for download Files
$directory = [IO.Directory]::GetCurrentDirectory()
# Read and display the text in the file
$Reader = new-object System.Io.StreamReader $Responsestream
$files = ($Reader.ReadToEnd()) -split "`n" | Select-String "$pattern" | foreach { $_.ToString().split(” “)[28]}
$uri = (New-Object System.Uri($connectionString+"/"+$file))
$download = New-Object System.Net.WebRequestMethods+Ftp
foreach ($file in $files) {
$destinationFile = $directory+"\"+$file
$sourceFile = $uri.OriginalString
$download.DownloadFile($sourceFile, $destinationFile)
}
# Close Reader and Response objects
$Reader.Close()
$Response.Close()
当我运行它时,我得到了这个输出:
Exception calling "DownloadFile" with "2" argument(s): "An exception occurred during a WebClient request."
At C:\CRIF\BatchScripts\FTPCHECK\01.FTP_Check.ps1:44 char:5
+ $download.DownloadFile($sourceFile, $destinationFile)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
我在 Powershell 3.0 (Windows Server 2012) 上运行它。请帮忙!
【问题讨论】:
-
如果这是生产代码,是错误处理部门缺少的!你需要用 try...catch 块包装你的系统调用。
标签: exception powershell ftp webclient