简体   繁体   中英

Using WinSCP from PowerShell to retrieve files modified within the last hour

I'm using a PowerShell script to retrieve a file from a remote directory. I only want to retrieve a file if it was modified within the last hour. I was able to get the most recent file using the following code:

$directoryInfo = $session.ListDirectory($remotePath) 

$latest = 
    $directoryInfo.Files | 
    Where-Object { -Not $_.IsDirectory } | 
    Sort-Object LastWriteTime -Descending | 
    Select-Object -First 1 

I believe that I need to add another condition to the Where-Object clause, but I don't know the proper format. For example,

    Where-Object { -Not $_.IsDirectory and <created/modified within the last hour> } 

How do I do this? Is there a better/simpler way?

Extend you current where -block to check if LastWriteTime is greater (newer) than a datetime -object representing the previous hour. Ex:

$lasthour = (Get-Date).AddHours(-1)

$directoryInfo = $session.ListDirectory($remotePath) 

$latest = $directoryInfo.Files | 
Where-Object { (-Not $_.IsDirectory) -and ($_.LastWriteTime -gt $lasthour) } | 
Sort-Object LastWriteTime -Descending |
Select-Object -First 1 

If you want to download all files created/modified within the last hour, use:

$directoryInfo = $session.ListDirectory($remotePath) 

$limit = (Get-Date).AddHours(-1)

$recentFiles = 
    $directoryInfo.Files | 
    Where-Object { (-Not $_.IsDirectory) -And ($_.LastWriteTime -Gt $limit) }

foreach ($fileInfo in $recentFiles)
{
    $sourcePath = [WinSCP.RemotePath]::EscapeFileMask($fileInfo.FullName)
    $session.GetFiles($sourcePath, $localPath + "\*").Check()
}

Some official WinSCP .NET assembly examples used to make the code:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM