PowerShell下载图片丢失属性数据且无法打开,求助解决
PowerShell下载壁纸图片损坏的问题解决
由于GPO仅支持为Enterprise版计算机部署壁纸,尝试用PowerShell为Pro版计算机下载图片作为壁纸,先后使用两条命令:
Invoke-WebRequest -URI $url -OutFile $output(New-Object System.Net.WebClient).DownloadFile($url,$output)
下载过程无报错,但图片无法打开(提示格式不支持),jpg、png格式均无效。对比发现PowerShell下载的图片属性缺失,文件大小仅为手动下载的1/7,更换多个图片托管网站及下载目录后问题依旧。原代码如下:
#Open the folder in Windows Explorer under C:\Users\USERNAME\AppData\Roaming\*** ######################################################################################## Set-ExecutionPolicy unrestricted $path = [Environment]::GetFolderPath('ApplicationData') + "\***" If(!(test-path $path)) { New-Item -ItemType Directory -Force -Path $path } ######################################################################################## #Download the image to user profile ######################################################################################## $url = "{image URL}" $output = $path + "\Background.jpg" (New-Object System.Net.WebClient).DownloadFile($url,$output)
问题原因
核心问题出在图片托管网站的请求校验机制:
- 多数图片站点会检查请求的
User-Agent头,PowerShell默认请求的UA标识为PowerShell相关,会被识别为非浏览器请求,返回跳转页面的HTML而非图片文件 - 部分图片URL为短链接或需要重定向,即便WebClient默认支持重定向,站点的额外校验依然会返回非图片内容
解决方案
给请求添加模拟浏览器的User-Agent头,确保服务器返回真实图片资源:
修正后的WebClient代码
#Open the folder in Windows Explorer under C:\Users\USERNAME\AppData\Roaming\*** ######################################################################################## Set-ExecutionPolicy unrestricted -Scope CurrentUser -Force $path = [Environment]::GetFolderPath('ApplicationData') + "\***" If(!(test-path $path)) { New-Item -ItemType Directory -Force -Path $path } ######################################################################################## #Download the image to user profile ######################################################################################## $url = "{image URL}" $output = Join-Path -Path $path -ChildPath "Background.jpg" # 创建WebClient并添加浏览器UA头 $webClient = New-Object System.Net.WebClient $webClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36") try { $webClient.DownloadFile($url, $output) } finally { $webClient.Dispose() # 释放资源 }
Invoke-WebRequest修正版本
$url = "{image URL}" $output = Join-Path -Path $path -ChildPath "Background.jpg" Invoke-WebRequest -Uri $url -OutFile $output -UserAgent "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36" -MaximumRedirection 10
额外注意事项
- 用
Join-Path拼接路径比字符串拼接更可靠,避免路径分隔符问题 - 设置
Set-ExecutionPolicy时指定-Scope CurrentUser和-Force,减少权限提示和影响范围 - 若站点需要Cookie或身份验证,需额外添加对应请求头
内容的提问来源于stack exchange,提问作者Rob
相关产品推荐
相关产品推荐

