Powershell WinSCPnet, not deleting remote files when using $session.RemoveFiles()

Advertisement

chrsjo
Joined:
Posts:
1
Location:
malmö

Powershell WinSCPnet, not deleting remote files when using $session.RemoveFiles()

Hi,
I struggle to get the RemoveFiles() function to delete remote files. Using the WinSCPnet in a PowerShell script.

The errormessage I get is "{WinSCP.SessionRemoteException: Can't get attributes of file "
This is the barebone code I am trying.
Grateful for any assistance, or alternative ways to solve the problem

Add-Type -Path "C:\Program Files (x86)\WinSCP\WinSCPnet.dll"
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
    Protocol = [WinSCP.Protocol]::ftp
    HostName = "xxxxx"
    UserName = "xxxxx"
    password = "xxxxx"
    }
$session = New-Object WinSCP.Session
$session.ExecutablePath = "C:\Program Files (x86)\WinSCP\winscp.exe"
try
{
    # Connect
    $session.Open($sessionOptions)
    $transferOptions = New-Object WinSCP.TransferOptions
    $transferOptions.TransferMode = [WinSCP.TransferMode]::Binary
    #Listing remote directory to avoid the problem of how the file is named.
    # NOT all remote files should be deleted, in real life I would like to loop through a list
    # local filenames that should be deleted on the remote location
    $Directory = $session.ListDirectory("/")
    foreach ($FileInfo in $Directory.Files)
    {
     $RemovalFile = ($FileInfo.Name)
     $session.RemoveFiles($RemovalFile)
     }
}
finally
{
    $session.Dispose()
}

Reply with quote

Advertisement

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

Re: Powershell WinSCPnet, not deleting remote files when using $session.RemoveFiles()

It should be:
$RemovalFile = $FileInfo.FullName
Or even better:
$RemovalFile = [WinSCP.RemotePath]::EscapeFileMask($FileInfo.FullName)
If this does not help, please attach a full session log file showing the problem (using the latest version of WinSCP).

To generate the session log file, set Session.SessionLogPath. Submit the log with your post as an attachment. Note that passwords and passphrases not stored in the log. You may want to remove other data you consider sensitive though, such as host names, IP addresses, account names or file names (unless they are relevant to the problem). If you do not want to post the log publicly, you can mark the attachment as private.

Reply with quote

Advertisement

You can post new topics in this forum