首页 > 解决方案 > Powershell - Azure 存储帐户 - 获取上次身份验证时间/日期

问题描述

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

有人知道实现这一目标的更好方法吗?我在想,如果我可以列出上次对存储帐户进行身份验证的时间,可以给我我想要的东西,但是在尝试时我会画一个空白。

标签: azurepowershellazure-storage-account

解决方案


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

逻辑:

您基本上可以遍历每个存储帐户,找到其中的每个容器,根据上次修改日期(降序)对它们进行排序 - 选择最上面的 - 检查它是否超过 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
    }
}

该代码是从此 线程中引用的。

笔记 :

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

回到你的另一个问题: -

第二,如果容器是带有美元符号的命名(例如 $web),则 Get-AzStorageBlob 会出错。

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

在此处输入图像描述


推荐阅读