2012-09-05 30 views
15

我想使用PowerShell登录到网站并下载文件。如何使用PowerShell基本认证登录网站

但是我无法让PS正确传递凭据。

这是我PS:

$webclient = new-object System.Net.WebClient 
$webclient.Credentials = new-object System.Net.NetworkCredential("username","password","domain") 
$webpage = $webclient.DownloadString("url goes here") 

这里是登录框,我得到时,我打在IE的网站: enter image description here

回答

15

这就是我的工作。我认为,关键部分是“基本”的CredentialCache

$webclient = new-object System.Net.WebClient 
$credCache = new-object System.Net.CredentialCache 
$creds = new-object System.Net.NetworkCredential("un","pw") 
$credCache.Add("url", "Basic", $creds) 
$webclient.Credentials = $credCache 
$webpage = $webclient.DownloadString("url") 
-1

你有什么要(重试代码与其他一些网站)。通常情况下,无效的用户名/密码会导致代码失败并出现401错误(而不是Windows安全登录窗口)。这个问题可能与网站要求相关Windows Integrated Authentication

5

如果你想使用Invoke-WebRequest代替WebClient

$securepassword = ConvertTo-SecureString "password" -AsPlainText -Force 
$credentials = New-Object System.Management.Automation.PSCredential("username", $securepassword) 
Invoke-WebRequest -Uri "url goes here" -Credential $credentials 

我基于this blog article by Douglas Tarr的代码。请注意,在文章中,用户名和密码很混乱,但我已经在我的示例中修复了它们。

0

这是我做到了,

首次创建download.ps1文件,其中包含了PowerShell脚本,

然后通过批处理文件运行此脚本:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -File C:\Users\SS\Desktop\download.ps1 

这是PowerShell脚本:

$Username = 'Domain\user' 
    $Password = 'pass' 
    $Url = "http://google.com/target/filename.zip" 
    $Path = "C:\path\to\downloaded\file\filename.zip" 
    $WebClient = New-Object System.Net.WebClient 
    $WebClient.Credentials = New-Object System.Net.Networkcredential($Username, $Password) 
    $WebClient.DownloadFile($url, $path) 
3

出于某种原因,我无法获得任何这些解决方案的工作(在Win 10上使用PowerShell 5)。由于我不经常使用PS,这可能是一个明显的,笨拙的情况。但是,FWIW这是我通过手动设置授权标头来实现它的工作方式。

$url = "{url here}" 
$username = "{username here}" 
$password = "{password here}" 

$b = [System.Text.Encoding]::UTF8.GetBytes($username + ":" + $password) 
$p = [System.Convert]::ToBase64String($b) 

$creds = "Basic " + $p 

Invoke-WebRequest -Uri $url -Headers @{"Authorization"=$creds} 

无论出于何种原因,这里的其他答案确实发出请求,但没有发送授权标头。