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

4

我想要检查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:找不到驱动器。名称为“ftp”的驱动器不存在。位置:C:\documents\upload-file.ps1:67 字符:19 + $sourcefilesize = Get-Item($urlDest) + ~~~~~~~~~~~~~~~~~~~~~ + 类别信息 : ObjectNotFound: (ftp:String) [Get-Content],DriveNotFoundException + 完全合格的错误 ID:DriveNotFound,Microsoft.PowerShell.Commands.GetContentCommand

有什么解决此错误的方法吗?有没有办法检查FTP服务器中是否存在某些内容?任何关于此问题的线索都将是有帮助的。

1个回答

9

您不能使用Test-PathGet-Content来处理FTP URL。

您需要使用FTP客户端,例如WebRequestFtpWebRequest)。

尽管它没有任何明确的方法来检查文件的存在性(部分原因是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)
    }
}

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


如果您想要更简单的代码,请使用一些第三方FTP库。

例如,使用WinSCP .NET程序集,您可以使用它的Session.FileExists方法

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


2
再次感谢您 :) ..绝对正确的答案。从您那里学到了很多。再次向您致以无数的感谢 :) - user9161162

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接