【问题标题】:Deleting file from FTP server using PowerShell使用 PowerShell 从 FTP 服务器删除文件
【发布时间】:2018-09-15 05:58:03
【问题描述】:

我编写了一个 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 根本没有执行...任何类型的线索都会有所帮助。

【问题讨论】:

    标签: c# .net powershell ftp ftpwebrequest


    【解决方案1】:

    您不能将Test-Path 与 FTP URL 一起使用。所以你删除文件的代码永远不会执行。

    只需删除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
        }
    }
    

    虽然您只是在成功下载文件后才尝试删除该文件,但实际上该文件不太可能不存在。

    所以你可以考虑放弃任何特定的错误处理。

    【讨论】:

    • 这解决了我捕获异常的问题..再次感谢...我会说你是电力外壳之王:)
    • 你能帮我解决这个问题吗*.com/questions/49733374/…
    【解决方案2】:

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

    问题

    • 第 13 行。$Source 参数有一个ftp://... 路径。 Test-Path 将始终在此处返回 $false,并且永远不会执行删除请求。
    • Get-FTPFile 中,您没有引用函数的输入参数,而是在它之外定义的变量。我不知道这只是一个复制和粘贴错误还是故意的。在我看来,你应该使用你发送给函数的参数。至少在我下面的代码中的第 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 通信,除非您需要,否则无需从头开始创建所有内容。

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

    【讨论】:

    • 这也解决了我的问题......因为之前我不想分配像 Param([string] $Source) 这样的参数,这在执行脚本时导致了一些错误......非常感谢您指出我的错误:)