首页 > 解决方案 > 在 Powershell 中下载带密码的文件

问题描述

我需要从互联网上下载一个 51gb 的 zip 文件,打开需要输入密码的网站。

我想用 PowerShell (PSVersion:5.1.18362.752) 中的一个函数来做到这一点,但我不能再进一步了。我的功能如下所示:

 $securepassword = "thepassword"

function Get-Files {
   
    $Properties = @{
        URI        = "https://theurl"
        Credential = $securepassword
    }
    Invoke-WebRequest @Properties -OutFile "C:\Users\$env:USERNAME\Desktop\thefiles.zip"

}

参数 Credential 是否只能用于 Windows Credential?

非常感谢您的帮助

标签: windowspowershelldownloadcredentialsinvoke-webrequest

解决方案


我认为您使用的凭据错误。凭据不仅仅是密码。它是用户名加密码,它们应该是ICredentials的实例

请注意,只有请求身份验证的网页才能以这种方式传递凭据HTTP 401。如果网页使用基于表单的身份验证,则应将其作为非标准情况处理,凭据将不起作用,您需要发布数据、保留 cookie 等。

$localPath = [System.IO.Path]::Combine(
    [System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::DesktopDirectory),
    'OutFileName.zip')

$wc = [System.Net.WebClient]::new()
$wc.Credentials = [System.Net.NetworkCredential]::new($username, $plainTextPassword)
$wc.DownloadFile($uri, $localPath)
$wc.Dispose()

推荐阅读