PowerShell make web request with credentials

旧时模样 提交于 2019-12-23 02:31:32

问题


I'm trying to access a site that has Windows Security on it:

So I referenced this post and wrote the following code:

$web = New-Object Net.WebClient
$web.Credentials = new-object System.Net.NetworkCredential($username, $password, $domain)
$content = $web.DownloadString("https://my.url")

But I still get the same error I got before adding credentials: "The remote server returned an error: (401) Unauthorized." I then referenced this post, but I don't think basic authentication applies in this case. I have verified the username, password, and domain several times. Are there other commonly used solutions for making web requests with authentication?


回答1:


Not sure which PowerShell version you are using but if you are using PowerShell3.0 or greater you can use Invoke-WebRequest CommandLet like below

$username = "domain_name\user_name"
$password = "mypassword" | ConvertTo-SecureString -asPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($username,$password)

$res = Invoke-WebRequest https://my.url -Credential $cred


来源:https://stackoverflow.com/questions/24874189/powershell-make-web-request-with-credentials

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