WinSCP批处理脚本能否递归删除目标文件夹中X天以上的文件?
解决WinSCP脚本添加过期文件删除逻辑的可行方案
方案1:目标为Linux/Unix服务器时,直接执行远程命令
如果你的目标服务器是Linux/Unix系统,无需复杂遍历,直接在WinSCP脚本末尾添加远程find命令即可实现删除。示例(以删除30天前创建的文件为例,目标路径为/remote/target/path):
# 执行远程命令删除过期文件 call find /remote/target/path -type f -ctime +30 -delete
- 若服务器用
-birth而非-ctime识别创建时间(如FreeBSD),替换参数即可;若按修改时间删除,改用-mtime - 若需要管理员权限,在
find前加sudo(需确保用户有免密sudo权限)
方案2:用WinSCP .NET程序集实现跨平台逻辑
WinSCP的原生脚本模式缺少文件时间判断的API,可借助其.NET程序集编写C#代码实现完整逻辑,兼容所有服务器类型:
using WinSCP; using System; class Program { static void Main() { // 配置服务器连接信息 SessionOptions sessionOpts = new SessionOptions { Protocol = Protocol.Sftp, HostName = "你的服务器地址", UserName = "用户名", Password = "密码", SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx:xx..." }; using (Session session = new Session()) { session.Open(sessionOpts); // 原有文件传输逻辑(替换成你的传输代码) TransferOptions transferOpts = new TransferOptions(); transferOpts.TransferMode = TransferMode.Binary; session.PutFiles(@"C:\本地源路径\*", "/远程目标路径/", false, transferOpts); // 删除过期文件(这里设为30天) RemoteDirectoryInfo dir = session.ListDirectory("/远程目标路径/"); DateTime cutoff = DateTime.Now.AddDays(-30); foreach (RemoteFileInfo file in dir.Files) { if (file.IsDirectory || file.Name is "." or "..") continue; if (file.CreationTime < cutoff) { session.RemoveFile(file.FullName); Console.WriteLine($"已删除过期文件: {file.FullName}"); } } } } }
- 需下载WinSCP .NET程序集并添加到项目引用,编译后直接运行
- 可根据需求修改过期天数、协议(如改为FTP)、传输逻辑
方案3:原生WinSCP脚本结合本地PowerShell处理
若必须用WinSCP原生脚本,可通过导出文件列表、本地分析、生成删除命令的间接方式实现:
- WinSCP脚本中导出远程文件列表:
# 导出目标文件夹文件列表到本地 ls "/远程目标路径/" > "C:\temp\filelist.txt"
- 调用本地PowerShell脚本分析生成删除命令(脚本
clean-expired.ps1):
call powershell -File "C:\scripts\clean-expired.ps1" -ListPath "C:\temp\filelist.txt" -ExpireDays 30 -RemoteRoot "/远程目标路径/"
- PowerShell脚本
clean-expired.ps1内容:
param( [string]$ListPath, [int]$ExpireDays, [string]$RemoteRoot ) $cutoffTime = (Get-Date).AddDays(-$ExpireDays) $fileLines = Get-Content $ListPath foreach ($line in $fileLines) { # 匹配WinSCP ls输出的时间和文件名 if ($line -match "^(\d{4}-\d{2}-\d{2}\s\d{2}:\d{2})\s+(?:<DIR>|\d+)\s+(\S+)$") { $fileCreateTime = [DateTime]::Parse($matches[1]) $fileName = $matches[2] if ($fileCreateTime -lt $cutoffTime -and $fileName -notmatch "^\.{1,2}$") { Add-Content "C:\temp\delete-cmds.txt" "rm ""$RemoteRoot/$fileName""" } } }
- WinSCP脚本中执行生成的删除命令:
# 执行删除脚本 script "C:\temp\delete-cmds.txt"
- 注意:WinSCP的
ls输出格式可能随版本变化,需根据实际输出调整正则表达式
内容的提问来源于stack exchange,提问作者João Garcia
相关产品推荐
相关产品推荐

