Powershell Delete folders and content via. WIN SCP

Hi there Forum!

I am struggling with re-purposing this code to instead of downloading data, to simply delete it, and let me know if the delete process succeeded.

The goal is, to be able to initiate a delete process on a server, cleaning up unwanted folders.
( These folders are domain content on a webserver ).


The purpose of the script os to allow me to target the two unwanted ones, and delete all their content and the folder itself.

This example refers to deletion commands, that i cannot seems to make work in my case:

The current working code i am using to download files from a specific folder is this:

I would really appreciate some ideas on how to make this work.

Best regards

I don’t really have any way to test this at the moment. In the script that refers to deleting, it expects to first download that file and only if successful will it delete it from the remote host. Is that what you’re trying? If you just want to delete, would removing the "if ($download.Error -eq $Null) condition from the code below help you achieve your goal?

           if ($download.Error -eq $Null)
                Write-Host "Download of $($download.FileName) succeeded, removing from source"
                # Download succeeded, remove file from source
                $filename = [WinSCP.RemotePath]::EscapeFileMask($download.FileName)
                $removalResult = $session.RemoveFiles($filename)
                if ($removalResult.IsSuccess)
                    Write-Host "Removing of file $($download.FileName) succeeded"
                    Write-Host "Removing of file $($download.FileName) failed"
                Write-Host (
                    "Download of $($download.FileName) failed: $($download.Error.Message)")

Hi Doug!

Thanks for your response.

I actually managed to make it work, by changing False to True, in the usual download pattern, and by purpose allowing the download to fail.

This part:

$transferResult =
$session.GetFiles("/jonatantest/", "C:\Users\Dern\Desktop\WINSCP PS DOWNLOAD\", $True, $transferOptions)
So, it does do what i need it to now, even though this is probable not the best method out there :)