使用PowerShell调用WinSCP .NET Assembly无法排除同步文件夹
解决WinSCP同步排除系统文件夹的问题
你的脚本存在两个关键问题,导致排除规则无法生效:
1. SynchronizeDirectories参数顺序错误
你调用该方法时,将transferOptions放在了mirror参数的位置,导致传输选项没有被正确加载。正确的参数顺序为:
- 同步模式
- 本地路径
- 远程路径
- 是否删除远程多余文件(
removeFiles) - 是否启用镜像模式(
mirror,可选,默认false) - 传输选项(
transferOptions,可选)
修正后的调用代码:
$synchronizationResult = $session.SynchronizeDirectories( [WinSCP.SynchronizationMode]::Remote, $localPath, $remotePath, $True, $False, # 根据需求设置是否启用镜像 $transferOptions )
2. FileMask排除格式错误
WinSCP的文件掩码中,排除文件夹需要明确标记为目录(以路径分隔符结尾),否则会误匹配同名文件。要排除System Volume Information文件夹及其所有内容,正确的掩码格式是:
$transferOptions.FileMask = "| System Volume Information/"
如果需要排除多个系统文件夹,用分号分隔即可:
$transferOptions.FileMask = "| System Volume Information/; $RECYCLE.BIN/"
完整修正后的脚本
param ( $localPath = "E:\path", $remotePath = "/disk_files_backup/disk_E", ) try { Add-Type -Path "C:\Program Files (x86)\WinSCP\WinSCPnet.dll" $sessionOptions = New-Object WinSCP.SessionOptions -Property @{ Protocol = [WinSCP.Protocol]::Sftp HostName = "*" UserName = "*" Password = "*" GiveUpSecurityAndAcceptAnySshHostKey = $True } $session = New-Object WinSCP.Session try { # 连接服务器 $session.Open($sessionOptions) # 设置传输选项 $transferOptions = New-Object WinSCP.TransferOptions $transferOptions.TransferMode = [WinSCP.TransferMode]::Binary # 排除指定系统文件夹 $transferOptions.FileMask = "| System Volume Information/" # 同步目录并获取结果 $synchronizationResult = $session.SynchronizeDirectories( [WinSCP.SynchronizationMode]::Remote, $localPath, $remotePath, $True, $False, $transferOptions ) $synchronizationResult.Check() # 检查同步过程中的错误 } finally { # 关闭会话 $session.Dispose() } exit 0 } catch { Write-Host "Error: $($_.Exception.Message)" exit 1 }
额外建议:添加$synchronizationResult.Check()可以主动抛出同步过程中的错误,便于排查问题。
内容的提问来源于stack exchange,提问作者my min_d




