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

sah*_*jan 2 ftp powershell ftpwebrequest

我想检查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)
Run Code Online (Sandbox Code Playgroud)

此代码无效.

错误

获取内容:找不到驱动器.名为"ftp"的驱动器不存在.在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服务器?任何关于此的线索都会有所帮助.

Mar*_*ryl 5

您不能使用Test-Path也不能使用Get-ContentFTP URL.

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

虽然它没有任何明确的方法来检查文件的存在.你需要滥用像GetFileSize或的请求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)
    }
}
Run Code Online (Sandbox Code Playgroud)

该代码基于如何在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"
}
Run Code Online (Sandbox Code Playgroud)

(我是WinSCP的作者)

  • 再次感谢:) ..绝对正确的答案。从你那里学到了很多。再次感谢你:) (2认同)