gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 23:13:18 26 4
gpt4 key购买 nike

我想检查 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-Path也不是 Get-Content带有 FTP URL。
您必须使用 FTP 客户端,例如 WebRequest ( FtpWebRequest )。
虽然它没有任何明确的方法来检查文件是否存在(部分原因是 FTP 协议(protocol)本身没有这样的功能)。你需要“滥用”一个像 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)
}
}
该代码基于来自 How to check if file exists on FTP before FtpWebRequest 的 C# 代码.

如果您想要更直接的代码,请使用一些 3rd 方 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的作者)

关于powershell - 在 PowerShell 中检查 FTP 服务器上的文件是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49824373/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com