如何使用简易PowerShell脚本上传文件到Azure Blob容器
零依赖Azure Blob单文件上传PowerShell脚本
首先明确基础概念:
- Blob容器内的文件夹是虚拟目录,不属于独立容器,本质是Blob文件名的路径前缀,上传时直接写在目标路径中即可,无需提前创建
- 以下脚本不需要安装Az、RM等任何Azure相关PowerShell模块,直接调用存储账户REST接口实现上传,仅需你已有的Account Name和Account Key即可运行,适配无安全要求的测试/内部使用场景。
脚本不需要提前配置环境,Windows自带的PowerShell 5.1及以上版本可直接运行。
# ===== 只需修改以下5个配置项即可 ===== $storageAccountName = "替换为你的存储账户名" $storageAccountKey = "替换为你的存储账户Account Key" $targetContainer = "替换为目标Blob容器名" $targetFolderInContainer = "容器内的目标文件夹路径,传根目录就留空" # 例:"docs/2024",不要加前后斜杠 $localFileToUpload = "替换为待上传本地文件的完整路径" # 例:"D:\files\data.csv" # ==================================== # 以下逻辑无需手动修改 $fileName = Split-Path $localFileToUpload -Leaf $cloudBlobPath = if ([string]::IsNullOrWhiteSpace($targetFolderInContainer)) { $fileName } else { "$targetFolderInContainer/$fileName" } # 自动构造请求鉴权头 $apiVer = "2020-04-08" $utcTime = [DateTime]::UtcNow.ToString("R") $fileContentType = [System.Web.MimeMapping]::GetMimeMapping($localFileToUpload) $fileContent = [System.IO.File]::ReadAllBytes($localFileToUpload) $signRaw = "PUT`n`n`n$($fileContent.Length)`n`n$fileContentType`n`n`n`n`n`n`nx-ms-blob-type:BlockBlob`nx-ms-date:$utcTime`nx-ms-version:$apiVer`n/$storageAccountName/$targetContainer/$cloudBlobPath" $hmac = New-Object System.Security.Cryptography.HMACSHA256 $hmac.Key = [Convert]::FromBase64String($storageAccountKey) $sign = [Convert]::ToBase64String($hmac.ComputeHash([Text.Encoding]::UTF8.GetBytes($signRaw))) $requestUri = "https://$storageAccountName.blob.core.windows.net/$targetContainer/$cloudBlobPath" $requestHeaders = @{ "x-ms-blob-type" = "BlockBlob" "x-ms-date" = $utcTime "x-ms-version" = $apiVer "Authorization" = "SharedKey $storageAccountName:$sign" "Content-Type" = $fileContentType } Invoke-RestMethod -Uri $requestUri -Method Put -Headers $requestHeaders -Body $fileContent Write-Host "上传完成,文件云端地址:$requestUri"
使用说明
- 直接把上述代码复制到本地.ps1文件,修改开头配置项的参数即可右键运行,也可以直接粘贴到PowerShell窗口执行
- 虚拟目录不存在也能正常上传,上传完成后会自动在Storage Explorer里显示对应的文件夹结构
- 需要批量上传本地文件夹内所有文件时,只需要在外层加遍历逻辑:
Get-ChildItem "本地文件夹路径" -File | ForEach-Object { 把上传逻辑里的$localFileToUpload替换为$_.FullName }即可 - 上传效果和手动在Storage Explorer里点上传完全一致,不会出现文件损坏、路径错乱的问题
内容的提问来源于stack exchange,提问作者Kees Netelvrees
相关产品推荐
相关产品推荐

