Check file existence on FTP server in PowerShell

萝らか妹 提交于 2019-12-03 21:57:08

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. 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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!