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

Check file existence on FTP server in PowerShell

我想检查 FTP 服务器上是否存在某些文件。我用 Test-Path 编写了代码,但它不起作用。然后我写了代码来获取 FTP 服务器文件大小,但它也不起作用。

我的代码

function File-size()
{
   Param ([int]$size)
   if($size -gt 1TB) {[string]::Format("{0:0.00} TB ",$size /1TB)}
   elseif($size -gt 1GB) {[string]::Format("{0:0.00} GB ",$size/1GB)}
   elseif($size -gt 1MB) {[string]::Format("{0:0.00} MB ",$size/1MB)}
   elseif($size -gt 1KB) {[string]::Format("{0:0.00} KB ",$size/1KB)}
   elseif($size -gt 0) {[string]::Format("{0:0.00} B ",$size)}
   else                {""}
}

$urlDest = "ftp://ftpxyz.com/folder/ABCDEF.XML"
$sourcefilesize = Get-Content($urlDest)
$size = File-size($sourcefilesize.length)
Write-Host($size)

此代码无效。

错误

Get-Content : Cannot find drive. A drive with the name 'ftp' does not exist.At C:\documents\upload-file.ps1:67 char:19 + $sourcefilesize = Get-Item($urlDest) + ~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (ftp:String) [Get-Content], DriveNotFoundException + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.GetContentCommand

知道如何解决这个错误吗?有什么方法可以检查 FTP 服务器中是否存在某些内容?关于此的任何线索都会有所帮助。

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

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

虽然它没有任何明确的方法来检查文件是否存在(部分原因是 FTP 协议本身没有这样的功能)。您需要“滥用”像 GetFileSizeGetDateTimestamp.

这样的请求
$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 = [Net.WebRequestMethods+Ftp]::GetFileSize

try
{
    $request.GetResponse() | Out-Null
    Write-Host "Exists"
}
catch
{
    $response = $_.Exception.InnerException.Response;
    if ($response.StatusCode -eq [Net.FtpStatusCode]::ActionNotTakenFileUnavailable)
    {
        Write-Host "Does not exist"
    }
    else
    {
        Write-Host ("Error: " + $_.Exception.Message)
    }
}

该代码基于 How to check if file exists on FTP before FtpWebRequest.

中的 C# 代码

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

例如 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的作者)