Using special characters (slash) in FTP credentials with WebClient

橙三吉。 提交于 2019-12-10 11:28:58

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/37732020/using-special-characters-slash-in-ftp-credentials-with-webclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!