将Powershell对象CSV字符串作为文件保存到Azure Blob存储

时间:2019-10-23 13:15:10

标签: azure azure-powershell azure-blob-storage

我们正在通过Azure Runbook生成Powershell对象,并将其基本上转换为CSV字符串。

我们要将此生成的CSV字符串(从Azure Powershell Runbook生成)存储为CSV文件到Azure Blob存储中。 有人可以帮助我,如何使用powershell命令将CSV字符串作为文件保存到Azure Blob存储中? 我试图四处查看并遇到了Push-OutputBindings函数,但不确定如何在Azure Powershell Runbook中使用该函数导入哪个模块,并且不确定它是否是Azure Functions V2的一部分,但是关于如何使用它的任何基本知识会帮助我的。

谢谢

1 个答案:

答案 0 :(得分:1)

尝试以下代码-进行一些修改。本质上,想法是将CSV文件存储在本地,然后将其上传到Blob存储(我在本地进行了测试,但没有从Runbook进行过测试,但它也应该在那里运行):

#file name will be a guid string to avoid overlapping     
$guid = New-Guid
$guidString =$guid.ToString()

# store csv string to random file with random name (guid) 
$LogFull = "$guidString.csv" 
$LogItem = New-Item -ItemType File -Name $LogFull

#ignore next two lines as you already have csv string
$Date = Get-Date
$csvstring = ConvertTo-Csv -InputObject $Date -Delimiter ';' -NoTypeInformation

#save csv string locally 
$csvstring | Out-File -FilePath $LogFull -Append

#and then upload it to blob storage

#Get key to storage account
$acctKey = (Get-AzureRmStorageAccountKey -Name storage_acc_name -ResourceGroupName EastUS-TestRG).Value[0]

#Map to the reports BLOB context
$storageContext = New-AzureStorageContext -StorageAccountName "StorageAccName" -StorageAccountKey "acc_key"

#Copy the file to the storage account
Set-AzureStorageBlobContent -File $LogFull -Container "your_container" -BlobType "Block" -Context $storageContext -Verbose

具有Azure功能的替代解决方案

尝试让Runbook调用Http触发Azure函数,然后将字符串作为参数传递或传递给正文。这只是一个简单的REST API调用。

在Azure函数中,您可以具有Python,NodeJS或C#代码,这些代码会将您的字符串放入Blob存储中的CSV文件中。有很多关于该主题的教程,但是首先,您需要将字符串传递给AF :)

请看下面的示例,然后尝试类似的操作(我尚未测试过)。本质上,该想法是调用简单的REST API调用并在请求正文中传递有效负载:

[string]$Endpoint= "https://myfunction.azurewebsites.net/api/HttpTrigger?code=my_code_I_get_from_Azure_portal"
. . .
$payload =@" your payload "@
$Header = @{
   "Content-Type" = "text/plain";
}
$Result = Invoke-RestMethod -Uri $Endpoint -Method Post -body $Payload Headers $Header

从Azure门户获取的Azure函数URL +代码,如果单击Azure Function,将看到“获取函数网址”按钮。

相关问题