Я пытаюсь написать сценарий в Powershell для учетной записи автоматизации Azure. Он должен иметь возможность:
Вот что я получил на данный момент:
# Import the required Azure modules
Import-Module Az.Accounts
Import-Module Az.Storage
Import-Module Az.Resources
# # Authenticate to Azure
# $connectionName = "AzureRunAsConnection"
# $servicePrincipalConnection = Get-AutomationConnection -Name $connectionName
# Connect-AzAccount -ServicePrincipal -Tenant $servicePrincipalConnection.TenantId -ApplicationId $servicePrincipalConnection.ApplicationId -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
# Variables
$env:AZURE_STORAGE_CONNECTION_STRING = "zzzzzzz"
$resourceGroupName = "vvvvv"
$storageAccountName = "bbbbb"
$subscriptionId = "mmmm"
$resourceGroupName = "nnnn"
$storageAccountName = "iiiii"
$storageAccountKey = "wwwwww"
# Manage identity check
$connectionString = "DefaultEndpointsProtocol=https;AccountName=$storageAccountName;AccountKey=$storageAccountKey;EndpointSuffix=core.windows.net"
# Get the storage account context
$storageAccount = New-AzStorageContext -StorageAccountName $storageAccountName -StorageAccountKey $storageAccountKey
# $storageAccount = Get-AzStorageAccount -ResourceGroupName $resourceGroupName -Name $storageAccountName
$storageContext = $storageAccount.Context
# Get the list of file shares
$fileShares = az storage share list --account-name $storageAccountName --query "[].name" -o tsv
# Loop through each file share and retrieve quota and usage
foreach ($shareName in $fileShares) {
# Get the file share properties using Azure CLI
$shareProperties = az storage share show --name $shareName --account-name $storageAccountName --query "{quota:properties.quota, usage:properties.usage}" -o json | ConvertFrom-Json
$quotaGB = $shareProperties.quota
$usedCapacityBytes = $shareProperties.usage
$usedCapacityGB = [math]::Round($usedCapacityBytes / 1GB, 2)
# Output the results
Write-Output "File Share: $shareName"
Write-Output "Quota (GB): $quotaGB"
Write-Output "Used Capacity (GB): $usedCapacityGB"
Write-Output "-----------------------------"
}
Проблема в том, что я не могу отобразить использованную емкость для просмотра. Там всегда написано: 0.
В ходе расследования я выяснил следующее:
Модули Azure CLI и Azure Storage PowerShell напрямую не предоставляют использованная емкость для общих файловых ресурсов посредством простого вызова API.
Чтобы добиться этого, вам может потребоваться:
Перечислите файлы и каталоги в общей папке. Рассчитайте общую сумму размер всех файлов и каталогов.
Пара вопросов:
ок, это нормально, но преобразовать его в файлообменник? будет ли это работать так же?
Да, подождите, иногда это сработает.
еще один момент: если я использую управляемую идентификацию Azure, нужно ли мне еще проверять ее область действия в отношении этого файлового ресурса?
Найдено решение: этот кусок кода подойдет. # Проходим по каждому общему файловому ресурсу и получаем квоту и использование foreach ($shareName в $fileShares) { $usage = Get-AzRmStorageShare -ResourceGroupName $resourceGroupName -StorageAccountName $storageAccountName -Name $shareName -GetShareUsage Write-Output $usage Write-Output "- ----------------------------" } ССЫЛКА: Learn.microsoft.com/en-us/powershell/module/az. хранилище/…
Я даю ответ с новым пакетом
Проверьте ответ ниже. @Михал Пичета
- Получение списков общих файловых ресурсов в учетной записи хранения.
- Получить общую квоту, использованную для каждого общего доступа к файлам
- Получите использованную емкость и отобразите все эти данные на экране.
Вы можете использовать приведенный ниже скрипт, чтобы получить список общих файловых ресурсов с их общей квотой и используемой емкостью.
Скрипт:
# Define the storage account details
$accountName = "venkat891"
$accountKey = "xxxxxx"
# Create the storage context
$ctx = New-AzStorageContext -StorageAccountName $accountName -StorageAccountKey $accountKey
# Get the list of file shares
$fileShares = Get-AzStorageShare -Context $ctx
# Iterate through each file share and get statistics
foreach ($share in $fileShares) {
# Get the ShareClient for the current share
$client = $share.ShareClient
try {
# Get share properties
$properties = $client.GetProperties()
$shareUsageInBytes = $client.GetStatistics().Value.ShareUsageInBytes
$quotaGB = $properties.Value.QuotaInGB
# Output the share details
Write-Output "File Share: $($share.Name)"
Write-Output "Quota (GB): $quotaGB"
Write-Output "Used Capcity (bytes):$shareUsageInBytes"
Write-Output "-----------------------------"
} catch {
Write-Output "Failed to get statistics for share: $($share.Name). Error: $_"
}
}
Выход:
File Share: share1
Quota (GB): 102400
Used Capcity (bytes):42787
-----------------------------
File Share: share2
Quota (GB): 102400
Used Capcity (bytes):18690
-----------------------------
Ссылка:
Получите размер общего файлового ресурса Azure с помощью PowerShell — Stack Overflow от Gaurav Mantri.
ЕСЛИ я использую ваш скрипт, я получаю: «Не удалось получить статистику для общего ресурса. Ошибка: вы не можете вызвать метод для выражения без значения.:
Вы пробовали тот же сценарий?
скопируйте-вставьте свой скрипт.
Какова версия powershell в Azure Runbook?
7.2 последняя версия
Я создал этот скрипт:
# Import the required Azure modules
Import-Module Az.Accounts
Import-Module Az.Storage
Import-Module Az.Resources
# # Authenticate to Azure
Connect-AzAccount -Identity
# Variables
$env:""
$storageAccountName = ""
$subscriptionId = ""
$storageAccountKey = ""
$resourceGroupName = ""
# Manage identity check
$connectionString = "DefaultEndpointsProtocol=https;AccountName=$storageAccountName;AccountKey=$storageAccountKey;EndpointSuffix=core.windows.net"
# Get the storage account context
$storageAccount = New-AzStorageContext -StorageAccountName $storageAccountName -StorageAccountKey $storageAccountKey
$ctx = $storageAccount.Context
# Get the list of file shares
$fileShares = az storage share list --account-name $storageAccountName --query "[].name" -o tsv
# Loop through each file share and retrieve quota and usage
foreach ($shareName in $fileShares) {
$usage = Get-AzRmStorageShare -ResourceGroupName $resourceGroupName -StorageAccountName $storageAccountName -Name $shareName -GetShareUsage
Write-Output $usage
Write-Output "-----------------------------"
# Check if usage data is returned
if ($usage -ne $null) {
# Extract the ShareUsageBytes property (update the property name if necessary)
$usageInBytes = $usage.ShareUsageBytes # Adjust property name as needed
# Convert bytes to gigabytes
$usageInGB = $usageInBytes / 1GB
# Format and output the result
Write-Output "File Share: $shareName"
Write-Output "Usage: $([math]::Round($usageInGB, 2)) GB"
Write-Output "-----------------------------"
} else {
Write-Output "No usage data found for file share: $shareName"
}
}
Рад узнать, что ваша проблема решена. Вы можете принять его как ответ (нажмите на галочку рядом с ответом, чтобы переключить его с серого цвета на заполненный). Это может быть полезно другим членам сообщества. Спасибо @Михал Пичета
Перейдите по этой ссылке stackoverflow.com/questions/77905303/…