Check file existence on FTP server in PowerShell

后端 未结 1 834
面向向阳花
面向向阳花 2021-01-01 05:21

I want to check if some file exists on FTP server. I wrote code with Test-Path but it\'s not working. Then I wrote code to get FTP server file size, but it\'s n

相关标签:
1条回答
  • 2021-01-01 05:44

    You cannot use Test-Path nor Get-Content with FTP URL.

    You have to use FTP client, like WebRequest (FtpWebRequest).

    Though it does not have any explicit method to check file existence (partly because FTP protocol itself does not have such functionality). You need to "abuse" a request like GetFileSize or GetDateTimestamp.

    $url = "ftp://ftp.example.com/remote/path/file.txt"
    
    $request = [Net.WebRequest]::Create($url)
    $request.Credentials = New-Object System.Net.NetworkCredential("username", "password");
    $request.Method = [System.Net.WebRequestMethods+Ftp]::GetFileSize
    
    try
    {
        $request.GetResponse() | Out-Null
        Write-Host "Exists"
    }
    catch
    {
        $response = $_.Exception.InnerException.Response;
        if ($response.StatusCode -eq [System.Net.FtpStatusCode]::ActionNotTakenFileUnavailable)
        {
            Write-Host "Does not exist"
        }
        else
        {
            Write-Host ("Error: " + $_.Exception.Message)
        }
    }
    

    The code is based on C# code from How to check if file exists on FTP before FtpWebRequest.


    If you want a more straightforward code, use some 3rd party FTP library.

    For example with WinSCP .NET assembly, you can use its Session.FileExists method:

    Add-Type -Path "WinSCPnet.dll"
    
    $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
        Protocol = [WinSCP.Protocol]::Ftp
        HostName = "ftp.example.com"
        UserName = "username"
        Password = "password"
    }
    
    $session = New-Object WinSCP.Session
    $session.Open($sessionOptions)
    
    if ($session.FileExists("/remote/path/file.txt"))
    {
        Write-Host "Exists"
    }
    else
    {
        Write-Host "Does not exist"
    }
    

    (I'm the author of WinSCP)

    0 讨论(0)
提交回复
热议问题