【问题标题】:powershell failing to list AzResourceGroup name in scriptpowershell 未能在脚本中列出 AzResourceGroup 名称
【发布时间】:2022-01-07 16:39:18
【问题描述】:

这个 powershell 的东西相当绿色,但我有一个脚本我正在尝试重写(出于教育目的),它需要手动将 AZ 中的资源组输入到一个变量中,然后循环(它删除所述资源组)。

$_names = 'dmz-dev-mgmt', 'dmz-dev-container','dmz-dev-governance', 'dmz-dev-global-dns','dmz-dev-automation','dmz-dev-consumption','dmz-dev-network','NetworkWatcherRG'

到目前为止,我有以下内容

az login

Connect-AzAccount -Subscription "DEV Data Platform"

Get-AzResourceGroup |select ResourceGroupName

如果我在 powershell 中单独运行这些命令,它们都运行良好,如果我在执行 Connect-AzAccount 之后运行脚本本身,则无法返回 Get-AzResourceGroup

我希望通过脚本将此列表返回到$_names 变量

这可能吗?

【问题讨论】:

    标签: powershell azure-powershell


    【解决方案1】:

    您可以使用以下内容获取所有资源组名称,然后将其作为变量传递给其他脚本并根据您的要求使用它:

    getresources.ps1

    function ResourceGroups
    {
    $rgs=Get-AzResourceGroup 
    return $rgs.ResourceGroupName
    }
    ##to display the result if required
    foreach ($x in ResourceGroups){
    $x
    }
    

    deletegroup.ps1

    Write-Host ("The acquired list of resource group names is as below:")
    . .\getresources.ps1;$_names=ResourceGroups
    Write-Host ("Starting the Delete operation on the above aquired Resource Groups!!")
    foreach($_name in $_names){
    $delete= az group delete --name $_name
    Write-Host "Resource Group $_name Deleted Successfully!!!"
    }
    

    注意:我将两个脚本都保存在一个位置,这就是为什么在第二个脚本中使用这一行 . .\getresources.ps1;$_names=ResourceGroups 如果您将它们保存在不同的位置,那么您必须使用 @987654332 加载它@

    输出:

    在完成az loginconnect-azaccount 之后,我运行了如下脚本:


    单一脚本:

    Write-Host ("The acquired list of resource group names is as below:")
    $rgs=Get-AzResourceGroup 
    $rgs.ResourceGroupName
    Write-Host ("Starting the Delete operation on the above aquired Resource Groups!!")
    foreach($_name in $rgs.ResourceGroupName){
    $delete= az group delete --name $_name
    Write-Host "Resource Group $_name Deleted Successfully!!!"
    }
    

    【讨论】:

    • 嗨,这是 2 个单独的脚本而不是一个完整的脚本,这是有原因的吗?我还假设您在登录 Azure 后单独调用脚本的原因是因为没有办法让它以编程方式登录到 Azure 并一次性将资源组全部放在一起?
    • 没有说明为什么要使用两个脚本的具体原因。就像您想先将它存储在一个脚本中的变量中,然后考虑是否要在第二个脚本中使用这样的方法来删除资源组。
    • 嗨 Ansuman,我认为是这样,所以您必须在运行脚本之外执行 AZ Connect 和 Login?
    • 你能放弃我作为一个单一的脚本,这样我就可以通过它来看看它是如何工作的吗?教育练习:)
    • @Lynchie,在答案中添加了单个脚本下的脚本
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2018-04-28
    • 1970-01-01
    • 1970-01-01
    • 2014-10-22
    相关资源
    最近更新 更多