【问题标题】:How to rename a blob file using powershell如何使用 powershell 重命名 blob 文件
【发布时间】:2018-12-05 15:06:21
【问题描述】:

看似简单的任务。我只是想重命名一个 blob 文件,我知道我必须将它复制到重命名之类的东西,然后删除原始文件,但事实证明这很棘手。我已经创建了存储上下文 (New-AzureStorageContext),并获得了 blob (Get-AzureStorageBlob),并找到了 Start-AzureStorageBlobCopy,但我该如何重命名它呢?

如果可能的话,我也想在同一个容器中执行此操作。理想情况下,我会在 Azure Runbook 中运行它并使用 Webhook I Azure Data Factory v2 调用它。我确实尝试在 DFv2 的复制作业接收器中使用“添加动态内容”重命名文件,但我认为你不能。顺便说一句,我只想将日期附加到现有文件名。谢谢。

【问题讨论】:

    标签: powershell blob azure-data-factory


    【解决方案1】:

    您可以使用我的Rename-AzureStorageBlobconvenience 功能:

    function Rename-AzureStorageBlob
    {
        [CmdletBinding()]
        Param
        (
            [Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0)]
            [Microsoft.WindowsAzure.Commands.Common.Storage.ResourceModel.AzureStorageBlob]$Blob,
    
            [Parameter(Mandatory=$true, Position=1)]
            [string]$NewName
        )
    
      Process {
        $blobCopyAction = Start-AzureStorageBlobCopy `
            -ICloudBlob $Blob.ICloudBlob `
            -DestBlob $NewName `
            -Context $Blob.Context `
            -DestContainer $Blob.ICloudBlob.Container.Name
    
        $status = $blobCopyAction | Get-AzureStorageBlobCopyState
    
        while ($status.Status -ne 'Success')
        {
            $status = $blobCopyAction | Get-AzureStorageBlobCopyState
            Start-Sleep -Milliseconds 50
        }
    
        $Blob | Remove-AzureStorageBlob -Force
      }
    }
    

    它接受 blob 作为管道输入,因此您可以通过管道将 Get-AzureStorageBlob 的结果传递给它并提供一个新名称:

    $connectionString= 'DefaultEndpointsProtocol=https;AccountName....'
    $storageContext = New-AzureStorageContext -ConnectionString $connectionString
    
    Get-AzureStorageBlob -Container 'MyContainer' -Context $storageContext -Blob 'myBlob.txt'|
        Rename-AzureStorageBlob -NewName 'MyNewBlob.txt'
    

    要将日期附加到现有文件名,您可以使用以下内容:

    Get-AzureStorageBlob -Container 'MyContainer' -Context $storageContext -Blob 'myBlob.txt' | ForEach-Object { 
    $_ | Rename-AzureStorageBlob -NewName "$($_.Name)$(Get-Date -f "FileDateTime")" }
    

    延伸阅读:Rename Azure Storage Blob using PowerShell

    【讨论】:

    • 感谢您回来,我确实看到了这个,但我不知道在哪里运行它?我的意思是,把函数放在哪里?在 Azure 函数中?我查看了这些,但似乎只接受了 C#,我没有看到使用 PowerShell 的选项,或者我是否将该函数放在自动化运行手册中?还是在数据工厂自定义活动中使用?感谢您的帮助。
    • 您可以使用支持 PowerShell(预览版)的 Azure Function,也可以使用 Automation Runbook。
    猜你喜欢
    • 1970-01-01
    • 2010-11-19
    • 2011-07-31
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-27
    • 2015-11-26
    相关资源
    最近更新 更多