且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在PowerShell中检查FTP服务器上的文件是否存在

更新时间:2023-11-27 18:45:28

您不能将Test-PathGet-Content与FTP URL一起使用.

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

您必须使用FTP客户端,例如WebRequest( FtpWebRequest ).

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

尽管它没有任何明确的方法来检查文件是否存在(部分原因是FTP协议本身不具有这种功能).您需要滥用" GetFileSizeGetDateTimestamp之类的请求.

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

该代码基于如何在FtpWebRequest之前在FTP上检查文件是否存在的C#代码.

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

如果您想要更直接的代码,请使用一些第三方FTP库.

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

例如,对于 WinSCP .NET程序集,您可以使用其

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"
}

(我是WinSCP的作者)