如何用PowerShell下载SharePoint带密码保护的共享文件?
SharePoint带密码的公开共享链接不支持通过URL参数传递密码,必须通过提交验证页面的表单完成身份验证,再利用会话Cookie发起下载请求。以下是可行的实现脚本:
# 配置参数 $sharePointUrl = "https://company.sharepoint.com/:x:/x/site/random_string&download=1" $sharePassword = "你的文件共享密码" $savePath = "C:\folder\file.ext" # 创建会话对象,用于维持验证状态(保存Cookie) $webSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession # 1. 访问共享链接,获取验证页面及表单信息 $authPageResponse = Invoke-WebRequest -Uri $sharePointUrl -WebSession $webSession $authForm = $authPageResponse.Forms[0] # 填充表单中的隐藏字段(自动提取页面中的VIEWSTATE等必要参数) foreach ($hiddenInput in $authForm.InputFields | Where-Object {$_.Type -eq "hidden"}) { $authForm.Fields[$hiddenInput.Name] = $hiddenInput.Value } # 设置密码字段(若页面中密码输入框的name不是"password",需替换为实际值) $authForm.Fields["password"] = $sharePassword # 2. 提交验证表单,完成身份认证 Invoke-WebRequest -Uri $authForm.Action -Method $authForm.Method -WebSession $webSession -Body $authForm.Fields # 3. 使用已认证的会话下载文件 Invoke-WebRequest -Uri $sharePointUrl -WebSession $webSession -OutFile $savePath
注意事项
- 若脚本执行失败,可打开共享链接的验证页面,查看源码确认密码输入框的
name属性,替换脚本中"password"为实际值 - 确保目标保存路径的文件夹已存在,可添加
New-Item -Path (Split-Path $savePath) -ItemType Directory -Force提前创建文件夹 - 测试时可分步执行,查看每一步的响应内容,排查验证环节的问题
内容的提问来源于stack exchange,提问作者Jonothon Starsmore
相关产品推荐
相关产品推荐

