清单循环中的斑点未显示

时间:2018-11-29 08:49:36

标签: azure powershell azure-storage

我创建了一个脚本,该脚本删除了早于设置日期的Blob,我尝试使用自动化帐户运行该脚本,但是当我使用“测试窗格”对其进行测试时,它会提供所需的输出,是要删除的Blob的列表,但是当它实际使用自动化帐户运行时,它不会显示要删除的Blob的列表。

代码如下:

### delete blobs older than 30 days 
param(
    [parameter(mandatory=$true)]
    [int32]$daysToKeep, 
    [parameter(mandatory=$true)]
    [string]$storageAccount,
    [parameter(mandatory=$true)]
    [string]$storageContainer,
    [parameter(mandatory=$true)]
    [string]$storageAccessKey
)

    $connectionName = "AzureRunAsConnection"

        # Get the connection "AzureRunAsConnection "
        $servicePrincipalConnection = Get-AutomationConnection -Name $connectionName         
        "Logging in to Azure..."
        Add-AzureRmAccount `
            -ServicePrincipal `
            -TenantId $servicePrincipalConnection.TenantId `
            -ApplicationId $servicePrincipalConnection.ApplicationId `
            -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint 
         Write-Host "logged into Azure"        

$context = New-AzureStorageContext -StorageAccountName $storageAccount -StorageAccountKey $storageAccessKey 
New-AzureStorageContainer -Name $storageContainer -Context $context -Permission Blob -ErrorAction SilentlyContinue
$EGBlobs = Get-AzureStorageBlob -Container $storageContainer -Context $context | sort-object LastModified | select lastmodified, name
foreach($blob in $EGBlobs) 
{ 
    if($blob.lastmodified -lt (get-date).AddDays($daysToKeep*-1))
        {
        $blob_date = [datetime]$blob.LastModified.UtcDateTime
        Write-Output "-----------------------------------" 
        write-output "Purging blob from Storage: " $blob.name 
        write-output "----------------------------------- " 
        write-output "Last Modified Date of the Blob: " $blob_date 
        Write-Output "-----------------------------------" 
        Remove-AzureStorageBlob -Blob $blob.name -Container $storageContainer -Context $context 

        } 
}

看不到我要去哪里,这是Azure自动化帐户中的设置。

预先感谢

1 个答案:

答案 0 :(得分:1)

不知道为什么,但实际上是。

只需将Remove-AzureStorageBlob -Blob $blob.name -Container $storageContainer -Context $context行移动到循环的顶部,它将正常工作。

应该是:

foreach($blob in $EGBlobs) 
{ 
    if($blob.lastmodified -lt (get-date).AddDays(2))
        {
        Remove-AzureStorageBlob -Blob $blob.name -Container $storageContainer -Context $context 
        $blob_date = [datetime]$blob.LastModified.UtcDateTime
        Write-Output "-----------------------------------" 
        write-output "Purging blob from Storage: " $blob.name 
        write-output "----------------------------------- " 
        write-output "Last Modified Date of the Blob: " $blob_date 
        Write-Output "-----------------------------------" 

        } 
}

enter image description here