Powershell - Azure 存储帐户 - 获取上次身份验证时间/日期

时间:2021-03-23 12:39:11

标签: azure powershell azure-storage-account

尝试获取未使用的存储帐户列表。我试图沿着 LastModified 路线走,但有几个问题,首先这只适用于 Blob 存储,其次如果容器是一个带有美元符号的命名(例如 $web)Get-AzStorageBlob 错误。

有没有人知道实现这一目标的更好方法?我在想是否可以列出存储帐户上次对其进行身份验证的时间,这可以为我提供所需的信息,但在尝试时却是一片空白。

1 个答案:

答案 0 :(得分:0)

我一直在使用下面的逻辑并且成功地满足了类似的要求。

逻辑:

您基本上可以遍历每个存储帐户,找到其中的每个容器,根据上次修改日期(降序)对它们进行排序 - 选择最上面的 - 检查它是否超过 90(根据您的要求任意天数) ) 天。如果是,请继续删除它们。

代码段:

#Setting the AzContext for the required subscription
Set-AzContext -SubscriptionId "<YOUR SUBSCRIPTION ID>"

#Going through every storage account in the mentioned Subscription
foreach ($storageAccount in Get-AzStorageAccount) 
{

#Storing the Account Name and Resource Group name which will be used in the below steps
$storageAccountName = $storageAccount.StorageAccountName
$resourceGroupName = $storageAccount.ResourceGroupName


# Getting the storage Account Key - it could be any 1 of the key. Taken the first key for instance. 
$storageAccountKey = (Get-AzStorageAccountKey -Name $storageAccountName -ResourceGroupName $resourceGroupName).Value[0]

# Create storage account context using above key
$storagecontext = New-AzStorageContext -StorageAccountName $storageAccountName -StorageAccountKey $storageAccountKey

#Gets  all the Storage Container within the Storage Account
#Sorts them in descending order based on the LastModified
#Picks the Topmost or most recently modified date
$lastModified = Get-AzStorageContainer -Context $storagecontext | Sort-Object -Property @{Expression = {$_.LastModified.DateTime}} | Select-Object -Last 1 -ExpandProperty LastModified

# Remove storage account if it is has not been in past 90 days

    if ($lastModified.DateTime -lt (Get-Date).AddDays(-90)) 
    {
        Remove-AzStorageAccount -Name $storageAccountName -ResourceGroupName $resourceGroupName -Force
    }
}

此代码引用自此 thread

注意:

Get-AzStorageContainer - 不仅特定于 blob 存储。

回到你的另一个问题: -

第二个如果容器是一个带有美元符号的命名(例如 $web)Get-AzStorageBlob 错误。

这已在 Az.Storage 的更高版本中处理。我建议您升级模块并试一试。这已在此 thread 中讨论。Az.Storage 的更高版本应该能够处理名为“$web”的容器

enter image description here

相关问题