我想检查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‘的驱动器不包含exist.At C:\documents\upload-file.ps1:67 char:19 + $sourcefilesize = Get-Item($urlDest) ++ CategoryInfo : ObjectNotFound:(ftp:String) Get-Content,DriveNotFoundException + FullyQualifiedErrorId : DriveNotFound,CategoryInfo
知道如何解决这个错误吗?有什么方法可以将一些存在的文件签入FTP服务器吗?任何有关这方面的线索都会有帮助。
发布于 2018-04-13 20:54:01
您不能将Test-Path或Get-Content与FTP一起使用。
您必须使用FTP客户端,比如WebRequest (FtpWebRequest)。
尽管它没有任何显式的方法来检查文件的存在(部分原因是FTP协议本身没有这样的功能)。您需要“滥用”像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 = [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)
}
}该代码基于来自C#的https://stackoverflow.com/q/347897/850848代码。
如果你想要一个更简单的代码,使用一些第三方FTP库。
例如,对于WinSCP .NET组装,您可以使用它的方法
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的作者)
https://stackoverflow.com/questions/49824373
复制相似问题