如何使用PowerShell的Invoke-WebRequest从SQL列表下载图片按名称存储
PowerShell批量从SQL Express拉取URL下载图片方案
前置检查
执行脚本前先确认以下信息:
- SQL Express实例的连接权限,若使用SQL账号密码登录可自行修改连接字符串配置
- 运行脚本的主机可以正常访问图片对应的站点域名
完整执行脚本
# 配置参数,请根据实际情况修改 $sqlInstance = ".\SQLEXPRESS" # SQL Express实例名,本地默认实例一般为.\SQLEXPRESS $database = "你的数据库名" # 存储图片数据的数据库名称 $tableName = "你的表名" # 存储URL和Name字段的表名 $savePath = "C:\images" # 图片本地保存路径 # 创建保存目录(如果不存在) if (-not (Test-Path -Path $savePath)) { New-Item -ItemType Directory -Path $savePath | Out-Null } # 拼接SQL查询语句 $query = "SELECT URL, Name FROM $tableName" # 建立SQL连接 $connection = New-Object System.Data.SqlClient.SqlConnection $connection.ConnectionString = "Data Source=$sqlInstance;Initial Catalog=$database;Integrated Security=True;" $command = New-Object System.Data.SqlClient.SqlCommand($query, $connection) # 执行查询获取数据 try { $connection.Open() $reader = $command.ExecuteReader() $table = New-Object System.Data.DataTable $table.Load($reader) $connection.Close() } catch { Write-Host "SQL查询失败:$_" -ForegroundColor Red exit } # 循环下载图片 foreach ($row in $table) { $imgUrl = $row.URL $fileName = $row.Name + ".jpg" $fullPath = Join-Path -Path $savePath -ChildPath $fileName Write-Host "正在下载:$imgUrl -> $fullPath" try { # 加UseBasicParsing避免依赖IE引擎 Invoke-WebRequest -Uri $imgUrl -OutFile $fullPath -UseBasicParsing -TimeoutSec 30 Write-Host "下载成功:$fullPath" -ForegroundColor Green } catch { Write-Host "下载失败 $imgUrl:$_" -ForegroundColor Yellow } }
关键配置说明
- 身份验证切换:当前默认用Windows身份验证连接SQL,若需要用SQL账号密码,将连接字符串替换为
"Data Source=$sqlInstance;Initial Catalog=$database;User ID=你的账号;Password=你的密码;" - 后缀调整:如果实际图片不是jpg格式,修改
$fileName = $row.Name + ".jpg"中的后缀即可 - HTTPS适配:如果是HTTPS的图片链接报协议错误,在脚本开头添加一行
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12, [System.Net.SecurityProtocolType]::Tls13
常见问题解决
- 报错提示Internet Explorer引擎不可用:脚本中已经加了
-UseBasicParsing参数,可解决该类PowerShell默认配置问题 - 下载超时:可调整
-TimeoutSec参数的数值,延长超时时间 - 部分URL下载403:可在Invoke-WebRequest中添加
-Headers参数传入对应的Referer、Cookie等请求头信息,模拟正常浏览器请求
内容的提问来源于stack exchange,提问作者Hugo Pereira
相关产品推荐
相关产品推荐

