2016-06-09 24 views
2

編輯:我發現它絕對是造成問題的密碼。我的密碼有一個斜線,並且無法弄清楚如何讓它接受它。我已經嘗試用%5B替換它。更改密碼不是可能的。PowerShell:通過WebClient在FTP憑證中使用特殊字符(斜槓)

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://[email protected]/IN/$file" 
      Write-Host $ftp 
      $uri = New-Object -TypeName System.Uri -ArgumentList $ftp 
      $webclient.UploadFile($uri, $file) 
     } 
    } 
} 


ftp-test 

當我運行上面的代碼,我得到

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 

我不知道是什麼問題。搜索帶來了代理問題,但我沒有代理,我需要通過。

我可以用ftp.exe手動上傳文件,但是我寧願在PowerShell中儘可能做所有這些,而不是生成腳本以使用ftp.exe

回答

1

你必須URL-encode的特殊字符。 請注意,編碼的斜槓(/)是%2F,而不是%5B(即[)。

而不是硬編碼編碼的字符,請使用Uri.EscapeDataString

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

或者使用WebClient.Credentials property,你不需要逃避什麼:

$webclient.Credentials = New-Object System.Net.NetworkCredential($username, $password) 

... 

$ftp = "ftp://ftp.example.com/IN/$file" 
+0

我不知道爲什麼我認爲它是%5B(也是一個反斜槓(\\),我很蠢),我最終使用了NetworkCredential方法並且工作。謝謝你的幫助。 – godofgrunts