我的工作使用WinSCP.NET程序集进行SFTP传输。在成功地将文件从服务器传输到本地之后,我只想列出同步的文件和文件夹的名称(不包括路径(。
我正在使用PowerShell。
这是我的远程文件的树状结构:/home/etc/
文件夹:foldername1
、foldername2
。在每个foldername?
下,我都有文件matricule*.pdf
foldername1
----> matricule12455-126.pdf
----> matricule12456-125.pdf
foldername2
----> matricule1249-127.pdf
----> matricule1241-128.pdf
我尝试过这个脚本:
$filename = [WinSCP.RemotePath]::EscapeFileMask($download.FileName)
Write-Host "*** $filename ***"
$matr = (Split-Path -Path $filename -Leaf).Split(".")[0];
Write-Host "*** $matr ***"
它显示了整个路径:
/home/etc/foldername1/matricule12455-126.pdf
matricule12455-126
因此,我想要这个:
foldername1-12455-126
foldername1-12456-125
foldername2-1249-127
foldername2-1241-128
使用SynchronizationResult.Downloads
获取所有下载文件的列表。源文件的完整路径位于TransferEventArgs.FileName
中。
然后迭代列表,从文件路径中删除同步根路径,并进行其他需要的修改:
$localPath = "c:localpath"
$remotePath = "/remote/path"
# Bitvise SFTP
$results = $session.SynchronizeDirectories(
[WinSCP.SynchronizationMode]::Local, $localPath, $remotePath, $False)
$results.Check()
$remotePath = [WinSCP.RemotePath]::AddDirectorySeparator($remotePath)
foreach ($download in $results.Downloads)
{
$filename = $download.FileName
if (-not $filename.StartsWith($remotePath))
{
# Should never happen
Write-Host "File path $filename does not start with root path $remotePath"
}
else
{
# Remove synchronization root path from the file path
$filename = $filename.SubString($remotePath.Length)
# Replace path separators with dashes
$filename = $filename.Replace("/", "-")
# Remove "matricule"
$filename = $filename.Replace("matricule", "")
# Remove file extension (it would also remove file path, but there is none)
$filename = [IO.Path]::GetFileNameWithoutExtension($filename)
Write-Host $filename
}
}
该输出:
foldername1-12455-126
foldername1-12456-125
foldername2-1241-128
foldername2-1249-127