我有一个PowerShell脚本,可以下载特定文件扩展名的最新文件。 FTP目录中有数百个每小时带有时间戳的文件(mmddhh),它在每小时结束时清除。每个文件都有唯一的扩展名。我每小时都会为扩展程序.tn1
,.tn2
,.tn3
,.tn4
,.tn5
,.ky1
和.nc1
下载文件
该文件在本地保存为extension.txt
(例如tn1.txt
,tn2.txt
等。
我遇到的问题是,下载的tn5
文件的创建日期为2015年12月,但在服务器上是最新的(2016年4月)。
我每次访问网页时都已将IE选项设置为“检查存储页面的较新版本”。
我正在从VBA执行脚本:
Shell("powershell ""H:\Worksheets\FTP\FTP.ps1""", vbHide)
try
{
# Load WinSCP .NET assembly
Add-Type -Path "C:\Program Files (x86)\WinSCP\WinSCPnet.dll"
$localPath = "H:\Worksheets\FTP"
$remotePath = "/outgoing/data/LatestData/"
# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions
$sessionOptions.Protocol = [WinSCP.Protocol]::ftp
$sessionOptions.HostName =
$sessionOptions.UserName =
$sessionOptions.Password =
$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} |
Where-Object {
[System.IO.Path]::GetExtension($_.Name) -eq ".nc1" -or
[System.IO.Path]::GetExtension($_.Name) -eq ".ky1" -or
[System.IO.Path]::GetExtension($_.Name) -like ".tn*" }
Group-Object { [System.IO.Path]::GetExtension($_.Name) } |
ForEach-Object{
$_.Group | Sort-Object LastWriteTime -Descending | Select -First 1
}
$extension = [System.IO.Path]::GetExtension($latest.Name)
"GetExtension('{0}') returns '{1}'" -f $fileName, $extension
if ($latest -eq $Null)
{
Write-Host "No file found"
exit 1
}
$latest | ForEach-Object{
$extension = ([System.IO.Path]::GetExtension($_.Name)).Trim(".")
$sourcePath = [WinSCP.RemotePath]::EscapeFileMask($remotePath + $_.Name)
$session.GetFiles($sourcePath, "$localPath\$extension.txt" ).Check()
}
$stamp = $(Get-Date -f "yyyy-MM-dd-HHmm")
$filename = $stamp.subString(0,$stamp.length-6)
$session.GetFiles(
($remotePath + $fileName),
($localPath + $fileName + "." + $stamp)).Check()
}
finally
{
# Disconnect, clean up
$session.Dispose()
}
exit 0
}
catch [Exception]
{
Write-Host $_.Exception.Message
exit 1
}
答案 0 :(得分:1)
The target file name is specified by the second argument of the GetFiles
method call, i.e. the "$localPath\$extension.txt"
in the:
$sourcePath = [WinSCP.RemotePath]::EscapeFileMask($remotePath + $_.Name)
$session.GetFiles($sourcePath, "$localPath\$extension.txt").Check()
If you want to append a "1" to the basename, use "$localPath\${extension}1.txt"
:
$sourcePath = [WinSCP.RemotePath]::EscapeFileMask($remotePath + $_.Name)
$session.GetFiles($sourcePath, "$localPath\${extension}1.txt").Check()