使用PowerShell向Azure容器上传文件遇问题求助
问题描述
我需要在所有租户设备上运行脚本,将生成的电池报告上传至Azure容器。参考了相关PowerShell上传脚本但无法正常运行,已经尝试使用Account key和User Delegation key生成的SAS密钥,以下是我的代码:
#Variable $FolderPath= "D:\BatteryReport" #Check if Folder exists If(!(Test-Path -Path $FolderPath)) { New-Item -ItemType Directory -Path $FolderPath Write-Host "New folder created successfully!" -f Green } Else { Write-Host "Folder already exists!" -f Yellow } powercfg /batteryreport /output D:\BatteryReport\BatteryReport_$(hostname).html Install-Module -Name Az -AllowClobber $StorageURL = "https://mytenant.blob.core.windows.net/pub" $FileName = "BatteryReport_$(hostname).html" $SASToken = "mySASkey" $blobUploadParams = @{ URI = "{0}/{1}?{2}" -f $StorageURL, $FileName, $SASToken Method = "PUT" Headers = @{ 'x-ms-blob-type' = "BlockBlob" 'x-ms-blob-content-disposition' = "attachment; filename=`"{0}`"" -f $FileName 'x-ms-meta-m1' = 'v1' 'x-ms-meta-m2' = 'v2' } Body = $Content Infile = $FileToUpload }
问题排查与修正
你的脚本存在几个关键问题导致无法运行,以下是针对性修正方案:
- 核心变量未定义:
$FileToUpload和$Content没有赋值,Infile需要指向生成的电池报告完整路径;同时使用Infile参数时不需要Body,直接移除Body = $Content即可。 - 模块安装逻辑冗余:每次运行都执行
Install-Module会浪费资源,先检查Az模块是否已安装,再决定是否安装,同时加上-Force和-Scope CurrentUser适配普通用户权限。 - 缺少上传执行命令:只定义了请求参数哈希表,但没有调用
Invoke-RestMethod或Invoke-WebRequest执行实际的上传操作。 - SAS密钥格式校验:确保
$SASToken开头没有?,因为URI拼接时已经添加了?,重复符号会导致请求失败。
修正后的完整脚本
# 定义变量 $FolderPath = "D:\BatteryReport" $FileName = "BatteryReport_$(hostname).html" $FileToUpload = Join-Path -Path $FolderPath -ChildPath $FileName # 检查并创建目录 if (!(Test-Path -Path $FolderPath)) { New-Item -ItemType Directory -Path $FolderPath | Out-Null Write-Host "新目录创建成功!" -ForegroundColor Green } else { Write-Host "目录已存在!" -ForegroundColor Yellow } # 生成电池报告 powercfg /batteryreport /output $FileToUpload # 检查并安装Az模块(按需安装) if (!(Get-Module -ListAvailable -Name Az)) { Install-Module -Name Az -AllowClobber -Force -Scope CurrentUser -ErrorAction Stop Write-Host "Az模块安装完成!" -ForegroundColor Green } else { Write-Host "Az模块已存在,跳过安装!" -ForegroundColor Yellow } # Azure存储配置 $StorageURL = "https://mytenant.blob.core.windows.net/pub" $SASToken = "mySASkey" # 确保此处SASToken开头没有? # 构造上传参数并执行上传 $blobUploadParams = @{ URI = "{0}/{1}?{2}" -f $StorageURL, $FileName, $SASToken Method = "PUT" Headers = @{ 'x-ms-blob-type' = "BlockBlob" 'x-ms-blob-content-disposition' = "attachment; filename=`"{0}`"" -f $FileName 'x-ms-meta-m1' = 'v1' 'x-ms-meta-m2' = 'v2' } Infile = $FileToUpload } # 执行上传操作 try { Invoke-RestMethod @blobUploadParams -ErrorAction Stop Write-Host "文件上传成功!" -ForegroundColor Green } catch { Write-Host "文件上传失败:$($_.Exception.Message)" -ForegroundColor Red }
内容的提问来源于stack exchange,提问作者AndreSantos
相关产品推荐
相关产品推荐

