不要使用 WinSCP 将整个本地文件夹传输到远程目录,而只传输其中的文件

Do not transfer whole local folder to remote directory using WinSCP but only files in it

我制作了一个 PowerShell 脚本,可将 .txt 和 .csv 文件从本地文件夹传输到远程目录。

我想排除子目录并仅从我的本地文件夹传输 .txt 和 .csv 文件。

$transferOptions.FileMask = "*.txt, *.csv |*/";

如果我在此处添加排除掩码 | */ 脚本将不执行任何操作。没有文件被转移或排除。

如果我删除它,脚本可以运行,但是 整个本地 info 文件夹及其文件会传输到远程目录。

我只想远程传输 .txt 和 .csv 文件,而不是本地文件夹本身。

这是我脚本的传输部分的样子:

# Set the folder name variables
$DirCustomerData = @("001201", "001753", "001952", "002587", "002833", "002863", "003150", "003716", 

"004826", "003010", "004099", "006222", "002545", "006805", "001433", "006839")

$LocalDir = "\customer_data\"+$DirCustomerData[$i]+"\info\"

# Check for files
if((Get-ChildItem $LocalDir | Measure-Object).Count -eq 0)
{
    "Local directory $LocalDir has currently no files. Skipping to next folder"
    "`n"
} else {
    "Local directory $LocalDir contains "+(Get-ChildItem $LocalDir -Recurse -File -Exclude -Directory | Measure-Object | %{$_.Count})+" files. Starting now FTP Upload Session..."
    "`n"
    
    # Retrieve the local files
    $LocalDirFiles = Get-ChildItem $LocalDir

    # Open the FTP Session
    $session = New-Object WinSCP.Session
    $session.Open($sessionOptions)

    # Upload the files
    $transferOptions = New-Object WinSCP.TransferOptions
    $transferOptions.TransferMode = [WinSCP.TransferMode]::Binary
    $transferOptions.FileMask = "*.txt, *.csv";

    $RemoteDir = "/"+$DirCustomerData[$i]+"/info/"

    foreach ($LocalDirFiles in $LocalDir) {

        $transferResult = $session.PutFiles($LocalDir, $RemoteDir, $true, $transferOptions)

        # Throw on any error
        $transferResult.Check()

        # Print results
        foreach ($transfer in $transferResult.Transfers)
        {
            Write-Host "Upload of $($transfer.FileName) to remote FTP directory $RemoteDir succeeded."
        }
    }       
}

你能帮我只传输需要的文件并排除子目录吗?谢谢!

localPath argument of Session.PutFiles 的文档说:

Full path to local file or directory to upload. Filename in the path can be replaced with Windows wildcard to select multiple files. To upload all files in a directory, use mask *.

您的代码缺少掩码,应该是:

$LocalDir = "\customer_data\"+$DirCustomerData[$i]+"\info\*"

注意 *localDir 变量名不计算值的用途。


更直接的方法是使用 Session.PutFilesToDirectory,它适用于您当前的路径值:

$session.PutFilesToDirectory($LocalDir, $RemoteDir, $true, $transferOptions)