How do I query a file on FTP server in PowerShell to determine if an upload is required?

末鹿安然 提交于 2019-11-29 12:45:34

You can use the FtpWebRequest class with its GetDateTimestamp FTP "method" and parse the UTC timestamp string it returns. The format is specified by RFC 3659 to be YYYYMMDDHHMMSS[.sss].

That would work only if the FTP server supports MDTM command that the method uses under the cover (most servers do, but not all).

$ftprequest =
    [System.Net.FtpWebRequest]::Create("ftp://ftp.example.com/remote/folder/file.txt")

$ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::GetDateTimestamp

$response = $ftprequest.GetResponse().StatusDescription

$tokens = $response.Split(" ")

$code = $tokens[0]

if ($code -eq 213)
{
    Write-Host "Timestamp is $($tokens[1])"
}
else
{
    Write-Host "Error $response"
}

It would output something like:

Timestamp is 20171019230712

Now you parse it, and compare against a UTC timestamp of a local file:

(Get-Item "file.txt").LastWriteTimeUtc

Or save yourself some time and use an FTP library/tool that can do this for you.

For example with WinSCP .NET assembly, you can synchronize whole local folder with a remote folder with one call to the Session.SynchronizeDirectories. Or your can limit the synchronization to a set of files only.

# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"

# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions
$sessionOptions.Protocol = [WinSCP.Protocol]::Ftp
$sessionOptions.HostName = "ftpsite.com"

$session = New-Object WinSCP.Session

# Connect
$session.Open($sessionOptions)

$session.SynchronizeDirectories(
    [WinSCP.SynchronizationMode]::Remote, "C:\local\folder", "/remote/folder").Check()

To use the assembly, just extract a contents of .NET assembly package to your script folder. No other installation is needed.

The assembly supports not only the MDTM, but also other alternative methods to retrieve the timestamp.

(I'm the author of WinSCP)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!