在兩個存儲賬戶之間進行blob拷貝,在客戶端,使用Azue PowerShell腳本, 用存儲賬戶上下文(New-AzureStorageContext)來獲取某個StorageAccount中的Container。進而,咱們想使用Azure Portal的自動化(Automation), 在Runbook中運行一樣的腳本,就出現了以下的錯誤:windows
5/25/2015 9:49:19 AM, Error: Get-AzureStorageContainer : Cannot bind parameter 'Context'. Cannot convert the
"Microsoft.WindowsAzure.Commands.Common.Storage.AzureStorageContext" value of type
"Deserialized.Microsoft.WindowsAzure.Commands.Common.Storage.AzureStorageContext" to type
"Microsoft.WindowsAzure.Commands.Common.Storage.AzureStorageContext".
At storageAccountCopy:28 char:28this
從網上查詢問題緣由,有人說是這樣的,即Automation中運行的是PowerShell Workflow,其中返回的類型是deserialized, 而在PowerShell中返回的類型是非deserialized,因此你不能將Deserialized類型的AzueStorageContext轉換爲AzureStorageContext:解決方法是在腳本中使用關鍵字InlineScript包裹這些代碼,使得他們仍然返回AzureStorageContext,而不是PowerShell Workflow中默認的Deserialized AzureStorageContext.spa
原話以下:code
This is due to PowerShell Workflow returning values in deserialized form. See http://social.msdn.microsoft.com/Forums/windowsazure/en-US/1adec597-964c-402e-b1f1-b195d00a20be/exception-calling-azureprovisioningconfig?forum=azureautomation for more details.orm
The workaround is to just use an InlineScript within the workflow to run these commands in the PowerShell context instead of the PowerShell Workflow context.blog
示例代碼以下:(這段代碼所實現的是在同一個Subscription中,將源存儲賬戶中的blob文件拷貝到目標存儲賬戶中)ip
workflow storageAccountCopy { #Script by LeX (Qijie Xue) #sign in Azure Subscription $Credential = Get-AutomationPSCredential -Name "PSCredential" $SubscriptionName = Get-AutomationVariable -Name "SubscriptionName" #connect to Azure using PowerShell Credential Add-AzureAccount -Credential $Credential #Select the Azure subscription to use in this workflow Select-AzureSubscription -SubscriptionName $SubscriptionName inlinescript{ #source Storage Account $srcStorageAccountName = "" $srcStorageKey="" #target Storage Account $trgStorageAccountName="" $trgStorageKey ="" # storage context, source and target $srcContext = New-AzureStorageContext -StorageAccountName $srcStorageAccountName -StorageAccountKey $srcStorageKey $trgContext = New-AzureStorageContext -StorageAccountName $trgStorageAccountName -StorageAccountKey $trgStorageKey # all containers in source Storage Account $containers = Get-AzureStorageContainer -Context $srcContext ForEach($container in $containers) { $trgContainers = Get-AzureStorageContainer -Context $trgContext $exists=0 ForEach($item in $trgContainers) { if($item.Name -eq $container.Name) { $exists=1 } } if($exists -eq 0) { New-AzureStorageContainer $container.Name -Permission Container -Context $trgContext } # do the copy blob for the current container $blobs = Get-AzureStorageBlob -Container $container.Name -Context $srcContext $blobs | Start-AzureStorageBlobCopy -DestContainer $container.Name -DestContext $trgContext -Force } } }