我有一个名为答案.txt, 使用批处理命令将文件复制到 SFTP 服务器。复制完成后答案.txt,复制答案.txt再次将文件复制到同一路径上的 SFTP。同一路径上的两个文件不可能有相同的名称,因此我想重命名第二个复制的文件,例如A2.txt。
如何使用'新名字' WinSCP 命令行中的命令?
我复制了多个带有文件扩展名(*.txt)的文件,只想重命名 SFTP 服务器中已存在的同名文件。
答案1
这“新名字”命令WinSCP GUI 无法自动重命名上传的文件以免与现有文件冲突。
也没有这样的功能WinSCP 脚本。
尽管您可以使用以下方式进行编码WinSCP .NET 程序集,例如使用PowerShell 脚本:
try
{
# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"
# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions
# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions
$sessionOptions.Protocol = [WinSCP.Protocol]::Sftp
$sessionOptions.HostName = "example.com"
$sessionOptions.UserName = "username"
$sessionOptions.Password = "password"
$sessionOptions.SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx...="
$localPath = "c:\local\path\*.txt"
$remotePath = "/remote/path/"
try
{
# Connect
Write-Host "Connecting..."
$session = New-Object WinSCP.Session
$session.SessionLogPath = "session.log"
$session.Open($sessionOptions)
# Upload files
Write-Host "Uploading..."
$localFiles = Get-ChildItem -Path $localPath
foreach ($localFile in $localFiles)
{
$name = $localFile.Name;
Write-Host "Found file $name"
$index = 0;
while ($session.FileExists($remotePath + $name))
{
Write-Host "$name exists already in remote directory"
$index++;
$name = $localFile.Name + " ($index)"
}
Write-Host "Uploading as $name ..."
$session.PutFiles($localFile, $remotePath + $name).Check()
}
Write-Host "Done"
}
finally
{
# Disconnect, clean up
$session.Dispose()
}
exit 0
}
catch [Exception]
{
Write-Host $_.Exception.Message
exit 1
}