Delete files, but not folders.

Advertisement

matrixiux
Joined:
Posts:
6

Delete files, but not folders.

I have below command
"get -filemask=*.zip `"`"${remoteDirectory}`"`" `"`"${localDirectory}`"`" -delete"
It deletes all downloaded files AND folders from the remote.
what's the best way using scripting to not delete remote folders, only files?

I know this is asked 1000 times, but I wonder if in 2024 we have a feature for it? Its just because it's been asked so many times... Please new feature if doesn't exist.
Last edited by matrixiux on 2024-10-08 12:38; edited 1 time in total

Reply with quote

Advertisement

matrixiux
Joined:
Posts:
6

I ended up like this (yuck):
& $winScpPath /log="$logOutputFilePath" /logsize=1*100M /ini=nul /command `
    "open `"`"sftp://${username}:${password}@${serverUrl}/`"`" -hostkey=`"`"${hostKey}`"`"" `
    "get -filemask=*.zip|*/ `"`"${remoteDirectory}/*`"`" `"`"${localDirectory}\`"`" -delete" `
    "get -filemask=*.zip|*/ `"`"${remoteDirectory}/1/*`"`" `"`"${localDirectory}\1\`"`" -delete" `
    "get -filemask=*.zip|*/ `"`"${remoteDirectory}/2/*`"`" `"`"${localDirectory}\2\`"`" -delete" `
    "get -filemask=*.zip|*/ `"`"${remoteDirectory}/3/*`"`" `"`"${localDirectory}\3\`"`" -delete" `
    "get -filemask=*.zip|*/ `"`"${remoteDirectory}/4/*`"`" `"`"${localDirectory}\4\`"`" -delete" `
    "get -filemask=*.zip|*/ `"`"${remoteDirectory}/5/*`"`" `"`"${localDirectory}\5\`"`" -delete" `
    "get -filemask=*.zip|*/ `"`"${remoteDirectory}/6/*`"`" `"`"${localDirectory}\6\`"`" -delete" `
    "get -filemask=*.zip|*/ `"`"${remoteDirectory}/7/*`"`" `"`"${localDirectory}\7\`"`" -delete" `
    "exit"
This also doesn't create folders locally and fails if folders are missing.

Is there a better way using scripting?

Reply with quote

martin
Site Admin
martin avatar
Joined:
Posts:
41,441
Location:
Prague, Czechia

As you are using PowerShell, then you better use WinSCP .NET assembly like:
$files =
    $session.EnumerateRemoteFiles(
        $remotePath, $mask, [WinSCP.EnumerationOptions]::AllDirectories)
 
foreach ($fileInfo in $files)
{
    Write-Host "Deleting $($fileInfo.FullName) ..."
    $session.RemoveFile($fileInfo.FullName) 
}
Though you actually want to call Session.GetFileToDirectory with remove = $True.

Reply with quote

Advertisement

You can post new topics in this forum