我有一个WinSCP PowerShell脚本,用于下载服务器上的最新文件。我想让它适应下载服务器上每种文件类型的最新文件。
将文件扩展名命名为filename.txt
(example.al
- > al.txt
)的每个文件的加分点。这是我的代码:
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()
现在它将文件保存为.extension
,我希望将其保存为extension.txt
。
谢谢!
编辑:
尝试了这段代码并下载了服务器上的每个文件:
$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()
}
答案 0 :(得分:1)
Group-Object
第一部分很简单。使用它按扩展名分组并从每组中拉出一个。
$latest = $directoryInfo.Files |
Where-Object { -Not $_.IsDirectory } |
Group-Object { [System.IO.Path]::GetExtension($_.Name) } |
ForEach-Object{
$_.Group | Sort-Object LastWriteTime -Descending | Select -First 1
}
接下来我们处理每个扩展王并下载。你可以在同一个循环中完成这个,但我把它放在一个单独的循环中。 尚未考虑单独的扩展程序。
$latest | ForEach-Object{
$session.GetFiles($session.EscapeFileMask($remotePath + $_.Name), $localPath + $extension).Check()
}
我对扩展部分的要求有点模糊,但为此我们还需要循环中的扩展逻辑。
$latest | ForEach-Object{
$extension = ([System.IO.Path]::GetExtension($_.Name)).Trim(".")
$session.GetFiles($session.EscapeFileMask($remotePath + $_.Name), "$localPath\$extension.txt" ).Check()
}