在我的PowerShell FTP脚本中转义@字符 [英] Escape the @ character in my PowerShell FTP script

查看:181
本文介绍了在我的PowerShell FTP脚本中转义@字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一些数据上传到三个不同的FTP服务器.它适用于三台服务器中的两台.对于第三台服务器不起作用的原因是,密码中有一个@-登录名,而我却无法转义它.就是行不通.抱歉,我无法为您显示密码,但请想象ftp://username:p@ssword@ftp-server.com.现在,PowerShell认为密码已经在第一个@符号处停止了,但是没有.因此,PowerShell使用的密码是错误的,而FTP服务器的地址也是错误的.

I want to upload some data to three different FTP servers. It's working for two of the three servers. The reason why it's not working for the third server is, that there is an @-sign in the password and I am not capable of escaping it. It just doesn't work. Sorry I cant show you the password, but just imagine ftp://username:p@ssword@ftp-server.com. The PowerShell now thinks, that the password already stops at the first @-sign, but it does not. So the password the PowerShell is using is wrong and the address to the FTP server is wrong too.

我尝试用'@'或ASCII码[char]64或作为参数转义. 我真的不知道该怎么办...

I tried escaping it with '@' or in ASCII code [char]64 or as parameters. I really don't know what to try else...

$request = [Net.WebRequest]::Create("ftp://username:p@ssword@example.com/")
$request.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile 

$fileStream = [System.IO.File]::OpenRead("C:\Users\Desktop\file.zip")
$ftpStream = $request.GetRequestStream()

$buffer = New-Object Byte[] 10240
while (($read = $fileStream.Read($buffer, 0, $buffer.Length)) -gt 0)
{
    $ftpStream.Write($buffer, 0, $read)
    $pct = ($fileStream.Position / $fileStream.Length)
    Write-Progress `
        -Activity "Uploading" -Status ("{0:P0} complete:" -f $pct) `
        -PercentComplete ($pct * 100)
}

$fileStream.CopyTo($ftpStream)

$ftpStream.Dispose()
$fileStream.Dispose()

推荐答案

最简单的方法是使用 WebRequest.Credentials 而不是在URL中指定凭据:

Easiest is to use WebRequest.Credentials instead of specifying the credentials in the URL:

$request = [Net.WebRequest]::Create("ftp://example.com/")
$request.Credentials = New-Object System.Net.NetworkCredential("username", "p@ssword") 


或者,您可以使用 Uri.EscapeDataString :


Alternatively, you can use Uri.EscapeDataString:

$encodedPassword = [Uri]::EscapeDataString("p@ssword") 
$request = [Net.WebRequest]::Create("ftp://username:$encodedPassword@example.com/")

它将为您提供:p%40ssword–了解 URL编码.

It will give you: p%40ssword – Learn about URL encoding.

WebClient类似:在带有WebClient的FTP凭据中使用特殊字符(斜杠)

这篇关于在我的PowerShell FTP脚本中转义@字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆