我正在尝试使用WinSCP .NET程序集下载最后修改的文件作为ETL过程的一部分。因为我对Powershell脚本的知识很少,所以我很困难。
这是我在Windows 10 PowerShell中到目前为止所尝试的内容:
param (
$localPath = "C:\download\*",
$remotePath = "/home/folder/"
)
try
{
# Load WinSCP .NET assembly
Add-Type -Path "C:\Program Files (x86)\WinSCP\WinSCPnet.dll"
# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::ftp
HostName = "xxx.xxx.xxx.xxx"
UserName = "XXXXXXXX"
Password = "xxxxxxx"
}
$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 } |
Sort-Object LastWriteTime -Descending |
Select-Object -First 1
# Any file at all?
if ($latest -eq $Null)
{
Write-Host "No file found"
exit 1
}
# Download the selected file
$session.GetFiles(
[WinSCP.RemotePath]::EscapeFileMask($latest.FullName), $localPath).Check()
}
finally
{
# Disconnect, clean up
$session.Dispose()
}
exit 0
}
catch
{
Write-Host "Error: $($_.Exception.Message)"
}
我一直在尝试调试它,并注意到它运行直到$session.GetFiles
调用,输出以下错误:
错误:无法找到类型[WinSCP.RemotePath]。
我不知道为什么会这样。
这只是因为模块真的没有看到。
尝试使用MS PowerShellGallery中的包装器作为此工作的一部分,用于验证或代替您正在使用的包装器。
Find-Module -Name WinScp* | ft -a
Version Name Repository Description
------- ---- ---------- -----------
5.13.7.0 WinSCP PSGallery PowerShell Module Wrapper for WinSCP.
即使在WinSCP站点上使用它的说明,它与您在此处显示的内容略有不同:
https://winscp.net/eng/docs/library_powershell#loading
加载程序集PowerShell脚本需要先加载程序集,然后才能使用程序集公开的类。要加载程序集,请使用Add-Type cmdlet
Add-Type -Path "WinSCPnet.dll"
如果需要从其他目录运行脚本,则需要指定程序集的完整路径。您可以使用$ PSScriptRoot自动变量从脚本文件路径派生路径:5
Add-Type -Path (Join-Path $PSScriptRoot "WinSCPnet.dll")
如果您正在编写计划用作WinSCP扩展(自定义命令)的脚本,则可以使用随WinSCP一起安装的程序集的副本。在这种情况下,您可以使用WINSCP_PATH环境变量来解析程序集的路径。要允许脚本在WinSCP之外运行,如果未定义变量,则应该回退到$ PSScriptRoot方法(如上所述):
$assemblyPath = if ($env:WINSCP_PATH) { $env:WINSCP_PATH } else { $PSScriptRoot }
Add-Type -Path (Join-Path $assemblyPath "WinSCPnet.dll")
在您的调试和验证工作中。尝试将引用放在脚本的最顶部。
Add-Type -Path "C:\Program Files (x86)\WinSCP\WinSCPnet.dll"
param (
$localPath = "C:\download\",
$remotePath = "/home/folder/"
)
...
当您遇到WinSCP.RemotePath
的问题而不是之前使用过的WinSCP类(例如WinSCP.SessionOptions
或WinSCP.Session
)时,您很可能使用的是尚未安装WinSCP.RemotePath
class的旧版WinSCP .NET程序集。
确保更新到程序集的最新版本。