Reputation: 445
I have a WinSCP PowerShell script that downloads the most recent file on the server. I'd like to adapt it to download the most recent file of every file type on the server.
Bonus points for naming each file with the extension of the file as the filename.txt
(example.al
-> al.txt
). Here's my code:
try
{
# Connect
$session.Open($sessionOptions)
# Get list of files in the directory
$directoryInfo = $session.ListDirectory($remotePath)
# Select the most recent file
$latest =
$directoryInfo.Files |
Where-Object { -Not $_.IsDirectory } |
Sort-Object LastWriteTime -Descending |
Select-Object -First 1
$extension = [System.IO.Path]::GetExtension($latest.Name)
"GetExtension('{0}') returns '{1}'" -f $fileName, $extension
# Any file at all?
if ($latest -eq $Null)
{
Write-Host "No file found"
exit 1
}
# Download the selected file
$session.GetFiles($session.EscapeFileMask($remotePath + $latest.Name), $localPath + $extension).Check()
Right now it saves the file as .extension
, what I'd like is to save it as extension.txt
.
Thanks!
EDIT:
Tried this code and it downloaded every file on the server:
$session = New-Object WinSCP.Session
try
{
# Connect
$session.Open($sessionOptions)
# Get list of files in the directory
$directoryInfo = $session.ListDirectory($remotePath)
# Select the most recent file
$latest = $directoryInfo.Files |
Where-Object { -Not $_.IsDirectory } |
Group-Object Extension |
ForEach-Object {
$_.Group | Sort-Object LastWriteTime -Descending | Select -First 1
$session.GetFiles($session.EscapeFileMask($remotePath + $_.Name), $localPath).Check()
}
$extension = [System.IO.Path]::GetExtension($latest.Name)
"GetExtension('{0}') returns '{1}'" -f $fileName, $extension
# Any file at all?
if ($latest -eq $Null)
{
Write-Host "No file found"
exit 1
}
# Download the selected file
}
finally
{
# Disconnect, clean up
$session.Dispose()
}
Upvotes: 1
Views: 1219
Reputation: 46710
The first part is easy with Group-Object
. Use that to group by extension and pull to right one out of each group.
$latest = $directoryInfo.Files |
Where-Object { -Not $_.IsDirectory } |
Group-Object { [System.IO.Path]::GetExtension($_.Name) } |
ForEach-Object{
$_.Group | Sort-Object LastWriteTime -Descending | Select -First 1
}
Next we process each extension king and download. You could do this in the same loop but I have it in a separate one. The does not account for the separate extensions yet.
$latest | ForEach-Object{
$session.GetFiles($session.EscapeFileMask($remotePath + $_.Name), $localPath + $extension).Check()
}
I'm a little fuzzy on what you want with extension piece but for that we need to the extension logic in the loop as well.
$latest | ForEach-Object{
$extension = ([System.IO.Path]::GetExtension($_.Name)).Trim(".")
$session.GetFiles($session.EscapeFileMask($remotePath + $_.Name), "$localPath\$extension.txt" ).Check()
}
Upvotes: 1