首页 > 解决方案 > 我想在 foreach 循环中使用 invoke-rest 方法通过 Infile 参数上传多个文件

问题描述

每次循环执行时,文件都会被替换为第一个文件的位置。我想将它作为一个新文件上传而不破坏现有文件..

foreach ($blob in $blobs)
{   
    $file=New-TemporaryFile
    $file=Get-AzureStorageBlobContent -Container $container_name -Blob $blob.Name -Context $ctx -Destination $localFile -Force
    $contents = Get-Content $localFile -Raw -ErrorAction:SilentlyContinue
    $f=New-TemporaryFile
    Add-Content $f $contents
    $Header = @{
"Content-Disposition"="attachment;filename=$($blob.Name)"
"Authorization"=$accessToken
        }
    Invoke-RestMethod -Uri $apiUrl -Headers $Header  -Method put -InFile $f 


}

标签: azurepowershellazure-blob-storageazure-webjobsinvoke-command

解决方案


New-TemporaryFile我认为您使用代码中的命令过度执行了它。为什么要使用Get-AzureStorageBlobContent将 blob 内容存储在文件中,然后创建另一个临时文件将内容复制到?

这会简单得多:

foreach ($blob in $blobs) {  
    $localFile = New-TemporaryFile
    Get-AzureStorageBlobContent -Container $container_name -Blob $blob.Name -Context $ctx -Destination $localFile.FullName -Force

    $Header = @{
        "Content-Disposition"="attachment;filename=$($blob.Name)"
        "Authorization"=$accessToken
    }

    Invoke-RestMethod -Uri $apiUrl -Headers $Header  -Method put -InFile $localFile.FullName
}

编辑

New-TemporaryFile命令返回一个System.IO.FileInfo不能直接用作InFile参数的对象。相反,它需要一个完整的路径和文件名,所以我们使用$localFile.FullName


推荐阅读