unable to delete a directory with square brackets in name



unable to delete a directory with square brackets in name

Hi all,

I am trying to write a Powershell script that automatically deletes empty directories on our ftp server. I don't have any direct access to the server on which the directories reside - I can only access them via ftp. For this reason, I have written a powershell script that uses winscp to (try to) delete the empty directories.

However, I have a problem, in that many of the directories on the server have square brackets in the directory name.

For example, the directory name might be called:


There are lots of these directories, hence my desire to write a script to delete them.

This occurs because they've been created by a program that uses a number to create the directories it requires.

In order to work on this program, I created an empty directory


My program goes like this:


# program to test deletion of directories with square-brackets in the name.

$DLL_LOCATION="C:\Program Files (x86)\WinSCP\WinSCPnet.dll"

# Load WinSCP .NET assembly
[Reflection.Assembly]::LoadFrom($DLL_LOCATION) | Out-Null

# Session.FileTransferred event handler

$sessionOptions = New-Object WinSCP.SessionOptions
$sessionOptions.Protocol = [WinSCP.Protocol]::ftp
$sessionOptions.HostName = $HOSTNAME
$sessionOptions.UserName = $USERNAME
$sessionOptions.Password = $PASSWORD

$session = New-Object WinSCP.Session
# Connect

$remoteFileWithUnixPath = "/latest/[b]test"

$removalResult = $session.RemoveFiles($remoteFileWithUnixPath)
if ($removalResult.IsSuccess)
Write-Host ("Removal of remote file {0} succeeded" -f $remoteFileWithUnixPath)
Write-Host ("Removal of remote file {0} failed" -f $remoteFileWithUnixPath)
# Disconnect, clean up
exit 0
catch [Exception]
Write-Host $_.Exception.Message
exit 1


When I run it, it displays the following message:

PS C:\Users\dbuddrige\Documents\dps> .\delete-squarebracket-dir.ps1
Removal of remote file /latest/[b]test succeeded

However, the directory is not deleted.

BUT, if I change the directory name [and the variable $remoteFileWithUnixPath] to something like


And then re-run the program, it delete's the directory /latest/foo just fine.

Does anyone have any ideas what I need to do to get this to work?

thanks heaps,

David Buddrige

Reply with quote


You can post new topics in this forum