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

时间:2018-04-13 20:04:48

标签: powershell ftp 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)

此代码无效。

错误

  

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

1 个答案:

答案 0 :(得分:5)

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

您必须使用FTP客户端,例如WebRequestFtpWebRequest)。

虽然它没有任何明确的方法来检查文件是否存在。您需要滥用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 = [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)
    }
}

代码基于How to check if file exists on FTP before FtpWebRequest的C#代码。

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

例如,使用WinSCP .NET assembly,您可以使用其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的作者)

相关问题