使用 WinSCP .NET 程序集成功远程到本地同步后提取子文件夹和文件的名称

问题描述

我的工作使用 WinSCP .NET 程序集进行 SFTP 传输。成功将文件从服务器传输到本地后,我只想列出已同步的文件文件夹的名称(无路径)。

我正在使用 PowerShell。

这是我的远程文件的树结构:/home/etc/
文件夹:foldername1foldername2。在每个 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:\local\path"
$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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...