【问题标题】:Powershell ftp download failedPowershell ftp 下载失败
【发布时间】: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


【解决方案1】:

有关问题的详细信息隐藏在此通用异常的内部异常中。您应该更深入地挖掘错误以找出真正的问题所在。

由于 PowerShell 错误存储在 $error 中,您可以在收到错误后立即尝试以下命令来检查最后一个错误的内部异常

$error[0].Exception.InnerException

要充分利用错误消息,您可以使用人们编写的函数,例如 Resolve-Error

如果您希望脚本在这种情况下始终显示更好的错误消息,您可以使用 try catch 块来捕获错误并更好地显示它。像这样的:

try {
  $download.DownloadFile($sourceFile, $destinationFile)
}
catch [System.Net.WebException] {
  if ($_.Exception.InnerException) {
    Write-Error $_.Exception.InnerException.Message
  } else {
    Write-Error $_.Exception.Message
  }
}

【讨论】:

    猜你喜欢
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    • 1970-01-01
    • 1970-01-01
    • 2012-02-02
    • 2016-09-02
    • 2017-04-12
    相关资源
    最近更新 更多