Search code examples
powershellftppowershell-2.0webclient

Using special characters (slash) in FTP credentials with WebClient


EDIT: I have discovered it's definitely the password that is causing issues. I have a forward slash in my password and cannot figure out how to get this to accept it. I've already tried replacing it with %5B. Changing the password is not a possibility.

cd v:
$username = "*********"
$password = "*********"
$usrpass = $username + ":" + $password
$webclient = New-Object -TypeName System.Net.WebClient

function ftp-test 
{
    if (Test-Path v:\*.204)
    {
        $files = Get-ChildItem v:\ -name -Include *.204 | where { ! $_.PSIsContainer } #gets list of only the .204 files

        foreach ($file in $files)
        {
            $ftp = "ftp://$usrpass@ftp.example.com/IN/$file"
            Write-Host $ftp
            $uri = New-Object -TypeName System.Uri -ArgumentList $ftp
            $webclient.UploadFile($uri, $file)
        }
    }
}


ftp-test

When I run the above code I get

Exception calling "UploadFile" with "2" argument(s): "An exception occurred during a WebClient request."
At line:13 char:34
+             $webclient.UploadFile <<<< ($uri, $file)
+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException

I'm not sure what the issue is. Searching has brought issue with proxies, but I have no proxy that I need to get through.

I can manually upload the file with ftp.exe, but I'd rather do all this in PowerShell if possible instead of generating a script to use ftp.exe with.


Solution

  • You have to URL-encode the special characters. Note that encoded slash (/) is %2F, not %5B (that's [).

    Instead of hard-coding encoded characters, use Uri.EscapeDataString:

    $usrpass = $username + ":" + [System.Uri]::EscapeDataString($password)
    

    Or use the WebClient.Credentials property, and you do not need to escape anything:

    $webclient.Credentials =
        New-Object System.Net.NetworkCredential($username, $password)
    
    ...
    
    $ftp = "ftp://ftp.example.com/IN/$file"
    

    Similarly for (Ftp)WebRequest: Escape the @ character in my PowerShell FTP script