繁体   English   中英

如何使用 Az PowerShell 命令在多个订阅上运行 Powershell 脚本

[英]How to run Powershell script on multiple Subscriptions Using Az PowerShell Command

我有多个 azure 租户,每个租户都有多个订阅,我必须为我的所有订阅运行一个 PowerShell 脚本。

这可以使用Azure CLI来实现,并且效果很好。

我使用Azure CLI如下;

$az_account = (az account list --query "[].[name]" -o tsv)
foreach ($account in $az_account) {
    az account set --name $account
    #<RUN SCRIPTS HERE>#
}

但在某些情况下,我必须使用Az PowerShell命令而不是Azure CLI

所以任何人都可以帮助我

  1. 如何为多个订阅运行Az PowerShell命令
  2. Or the Az PowerShell profile file path ( same as Azure CLI which is C:\Users\%USER\.Azure\azureProfile.json ).
  1. 如何为多个订阅运行Az PowerShell命令

您可以使用以下 PowerShell 脚本来运行多个订阅 PowerShell 命令。

# Get the Subscription Details using Get-AzSubscription Command
Get-AzSubscription | ForEach-Object {
    # Set the context Details using Set-AzContext Command which is equalent to the az account set CLI Command
    $_ | Set-AzContext
    $subscriptionName = $_.Name
      #<RUN YOUR SCRIPTS HERE>#

}

在此处输入图像描述

  1. Az PowerShell配置文件路径(与Azure CLI相同,即C:\Users\%USER\.Azure\azureProfile.json )。

请参阅此处了解配置文件路径位置

解析度

经过几次尝试,终于找到了一些方法来解决我的问题。 在此处发布相同内容可能对某人有所帮助。

您可以使用以下命令连接所有订阅

Connect-AzAccount -Tenant "xxxx-xxxxx-xxxx-xxx" -Subscription "xxxx-xxxxx-xxxx-xxx"

列出所有连接的订阅

Get-AzContext -ListAvailable | Select-Object Name, Subscription, Tenant

在此处输入图像描述

如果要重命名为友好名称,

Rename-AzContext -SourceName "Azure subscription 1 (xxxxx-xxxx-xxxx-xxxx-xxxx) - xxxxx-xxxx-xxx-xxxx-xxxx-xxx - jawad@xyz.com" -TargetName "MySubscription"

要将这些配置文件保存到文件中,

Save-AzContext -Path "C:\Users\jawad\Downloads\AzpwshProfile.json"

您可以随时使用以下命令导入这些配置文件,(首先测试清除配置文件Clear-AzContext -Force

Import-AzContext -Path "C:\Users\jawad\Downloads\AzpwshProfile.json"

现在您可以轻松地使用for循环来设置订阅,例如

$acc = (Get-AzContext -ListAvailable | Select-Object Name)
foreach ($account in $acc) {
>> Select-AzContext $account.Name
>> Get-AzVM | Export-Csv -Path "inventory.csv"
>> }

谢谢

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM