尝试使用以下代码从受保护的HTTP源下载文件会返回401未经授权:
$pfile = "\\some\local\leaf\path"
$user = "MyUserName"
$pwdIn = read-host -assecurestring | convertfrom-securestring | out-file $pfile
$pwdOut = get-content $pFile| convertto-securestring
$url="http://path.to/file"
$file = "\\localpath\to\file"
$webclient = new-object System.Net.WebClient
$webclient.Credentials = new-object System.Net.NetworkCredential($user, $pwdOut)
$webclient.DownloadFile($url,$file)
那么,跳过编写密码文件的步骤会怎样呢?
$pwd = read-host -assecurestring
...
$webclient.Credentials = new-object System.Net.NetworkCredential($user, $pwd)
然而,跳过安全字符串的创建也可以正常工作:
$pwd = read-host
...
$webclient.Credentials = new-object System.Net.NetworkCredential($user, $pwd)
上述代码没有返回任何其他错误。在测试原始代码版本时,我验证了目标密码文件的存在和明显的结构有效性。整个代码都在单个脚本中,因此在执行期间convertto和convertfrom具有相同的环境。我在x86和64位powershell中尝试过这种方法。
事实上,我甚至可以将安全字符串转换回正确的基本字符串,并使用WebClient。
$pwdtmp = get-content $pFile| convertto-securestring
$pwdOut = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pwdtmp))
$webclient.Credentials = new-object System.Net.NetworkCredential($user, $pwdOut)
因此,问题必须在使用SecureString与System.Net.NetworkCredential类上,然而http://msdn.microsoft.com/en-us/library/system.net.networkcredential.aspx,以及我发现的一些示例表明SecureString应该作为第二个参数工作。
在撰写本文时,事实上我已经找到了解决方案:
$user = "user"
$pwd = read-host -assecurestring
$creds = New-Object System.Management.Automation.PSCredential `
-ArgumentList $user, $pwd
$webclient.Credentials = new-object System.Net.NetworkCredential($user, $Creds.GetNetworkCredential().Password)
$webclient.DownloadFile($url,$file)
但是没有解释为什么SecureString类型不起作用,而PSCredential.Password可以。执行$creds|gm清楚地表明$creds.Password实际上也是SecureString:
类型名称:System.Management.Automation.PSCredential
名称 成员类型 定义
---- ---------- ---------- Equals 方法 bool Equals(System.Object obj)
GetHashCode 方法 int GetHashCode()
GetNetworkCredential 方法 System.Net.NetworkCredential GetNetworkCredential() GetType 方法 type GetType() ToString 方法 string ToString()
Password 属性 System.Security.SecureString Password {get;}
这是怎么回事?