使用PowerShell从FTP服务器删除文件

时间:2018-04-05 12:01:33

标签: c# .net powershell ftp ftpwebrequest

我编写了一个PowerShell脚本,使用FTP将文件下载到我的本地计算机上。

下载文件后,我想从FTP服务器上删除它。我也写了这段代码。但不幸的是它没有用。

任何人都可以帮我指出我的代码有什么问题吗?任何线索都会有所帮助......

这是我的代码

function Delete-File($Source,$Target,$UserName,$Password)
{

    $ftprequest = [System.Net.FtpWebRequest]::create($Source)
    $ftprequest.Credentials =  New-Object System.Net.NetworkCredential($UserName,$Password)

    if(Test-Path $Source)
    {
       "ABCDEF File exists on ftp server."
       $ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::DeleteFile
       $ftprequest.GetResponse()

       "ABCDEF File deleted."
    }

}

function Get-FTPFile ($Source,$Target,$UserName,$Password)  
{  

    # Create a FTPWebRequest object to handle the connection to the ftp server  
    $ftprequest = [System.Net.FtpWebRequest]::create($Source)  

    # set the request's network credentials for an authenticated connection  
    $ftprequest.Credentials =  
    New-Object System.Net.NetworkCredential($username,$password)  
    if(Test-Path $targetpath)
    {
        "ABCDEF File exists"
    }
    else 
    { 
        "ABCDEF File downloaded"
         $ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile  

         $ftprequest.UseBinary = $true  
         $ftprequest.KeepAlive = $false  
         Delete-File $sourceuri $targetpath $user $pass
    }

    # send the ftp request to the server  
    $ftpresponse = $ftprequest.GetResponse()  

    # get a download stream from the server response  
    $responsestream = $ftpresponse.GetResponseStream()  

    # create the target file on the local system and the download buffer  
    $targetfile = New-Object IO.FileStream ($Target,[IO.FileMode]::Create)  
    [byte[]]$readbuffer = New-Object byte[] 1024  

    # loop through the download stream and send the data to the target 
    file  
    do{  
          $readlength = $responsestream.Read($readbuffer,0,1024)  
          $targetfile.Write($readbuffer,0,$readlength)  
    }  
    while ($readlength -ne 0)  

    $targetfile.close()  
}  

$sourceuri = "ftp://ftpxyz.com/vit/ABCDEF.XML"  
$targetpath = "C:\Temp\M\NEWFOLDER\ABCDEF.XML"  
$user = "*******"  
$pass = "*******"  
Get-FTPFile $sourceuri $targetpath $user $pass 
Delete-File $sourceuri $targetpath $user $pass

每次执行此脚本时,我得到的唯一声明

  

下载ABCDEF文件

  

ABCDEF文件存在

我猜Delete-File根本没有执行......任何类型的线索都会有所帮助。

2 个答案:

答案 0 :(得分:3)

我在本地运行您的脚本试用它并发现了一些问题。我还重构了一些事情,只是为了让它更具可读性(至少在我看来:) :)。

问题

  • 第13行。$Source参数有一个ftp://...路径。 Test-Path将始终在此处返回$false,并且永远不会执行删除请求。
  • Get-FTPFile中,您没有引用函数的输入参数,而是在其外部定义的变量。我不知道这是不是一个副本&粘贴bug或故意。在我看来,你应该使用你发送给函数的参数。第38,39和50行至少在我的代码中。

代码

function Delete-File
{  
   param(
       [string]$Source,
       [string]$Target,
       [string]$UserName,
       [string]$Password
   ) 

   $ftprequest = [System.Net.FtpWebRequest]::create($Source)
   $ftprequest.Credentials =  New-Object System.Net.NetworkCredential($UserName,$Password)

   if(Test-Path $Source)
   {
      "ABCDEF File exists on ftp server."
      $ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::DeleteFile
      $ftprequest.GetResponse()

      "ABCDEF File deleted."
   }

}

function Get-FTPFile
{  
   param(
       [string]$Source,
       [string]$Target,
       [string]$UserName,
       [string]$Password
   ) 

   # Create a FTPWebRequest object to handle the connection to the ftp server  
   $ftprequest = [System.Net.FtpWebRequest]::create($Source)  

   # set the request's network credentials for an authenticated connection  
   $ftprequest.Credentials =  
   New-Object System.Net.NetworkCredential($UserName,$Password)  
   if(Test-Path $Target)
   {
       "ABCDEF File exists"
   }
   else 
   { 
       "ABCDEF File downloaded"
        $ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile  

        $ftprequest.UseBinary = $true  
        $ftprequest.KeepAlive = $false  
        Delete-File $Source $Target $UserName $Password
  }

  # send the ftp request to the server  
  $ftpresponse = $ftprequest.GetResponse()  

  # get a download stream from the server response  
  $responsestream = $ftpresponse.GetResponseStream()  

  # create the target file on the local system and the download buffer  
  $targetfile = New-Object IO.FileStream ($Target,[IO.FileMode]::Create)  
  [byte[]]$readbuffer = New-Object byte[] 1024  

  # loop through the download stream and send the data to the target 
  file  
  do{  
        $readlength = $responsestream.Read($readbuffer,0,1024)  
        $targetfile.Write($readbuffer,0,$readlength)  
  }  
  while ($readlength -ne 0)  

  $targetfile.close()  
}  

$sourceuri = "ftp://ftpxyz.com/vit/ABCDEF.XML"  
$targetpath = "C:\Temp\M\NEWFOLDER\ABCDEF.XML"  
$user = "*******"  
$pass = "*******"   
Get-FTPFile $sourceuri $targetpath $user $pass 
#Delete-File $sourceuri $targetpath $user $pass

还有现成的PowerShell cmdlet用于与FTP / SFTP通信,除非您需要,否则无需从头开始创建所有内容。

无论如何,作为参考,请查看例如。

答案 1 :(得分:3)

您不能将Test-Path与FTP网址一起使用。因此,删除文件的代码永远不会执行。

只需删除Test-Path条件,然后尝试无条件删除该文件。然后检查错误并根据需要处理“文件不存在”错误。

$ftprequest = [System.Net.FtpWebRequest]::create($Source)
$ftprequest.Credentials =  New-Object System.Net.NetworkCredential($UserName, $Password)

try
{
   $ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::DeleteFile
   $ftprequest.GetResponse() | Out-Null

   Write-Host ("File {0} deleted." -f $Source)
}
catch
{
    if ($_.Exception.InnerException.Response.StatusCode -eq 550)
    {
        Write-Host ("File {0} does not exist." -f $Source)
    }
    else
    {
        Write-Host $_.Exception.Message
    }
}

虽然当您尝试在成功下载文件后尝试删除文件时,实际上文件不太可能不存在。

因此,您可以考虑放弃任何特定的错误处理。