【问题标题】:ForEach-Object return all objects three times in powershell (Azure VM)ForEach-Object 在powershell(Azure VM)中返回所有对象三次
【发布时间】:2020-03-27 01:44:39
【问题描述】:

我有这个 Powershell 行,它应该列出所选订阅中的所有虚拟机,我总共有 3 个订阅。

$azureSubscriptionID = "xxxxx-xxxxx-xxxxx-xxxx"
foreach ($subs in $azureSubscriptionID)
    {
        Write-Output "Collecting VM facts from subscription $subs"

         $vms += Get-AzureRMSubscription | ForEach-Object {Select-AzureRMSubscription $_ | Out-Null; Get-AzureRmVM -WarningAction SilentlyContinue} 
    }

问题是在运行脚本并使用 $vms 时,它会连续 3 次列出所有可用的 vms 订阅,如下所示:

VM A     VM B     VM C
虚拟机 A     虚拟机 B     虚拟机 C
虚拟机 A     虚拟机 B     虚拟机 C

我做错了什么以及如何解决?还是有其他方法可以在几行中从 X 订阅中获取所有虚拟机?在 Azure Runbook 中使用它。

【问题讨论】:

  • 您的代码在foreach ($subs in $azureSubscriptionID) 循环中仅显示一项。所以我会首先检查代码每一步的值。
  • 是的,我知道,但将来可能会有不止一个订阅作为参数,这就是我需要循环它们的原因。
  • 感谢您的“为什么”。 [grin] 我看到AdminOfThings 提供了解决方案 - 很高兴知道您有解决方案。

标签: azure powershell foreach virtual-machine


【解决方案1】:

如果您只想循环浏览所有订阅并列出所有虚拟机,您可以执行以下操作:

Get-AzureRMSubscription | ForEach-Object {
    $sub = Select-AzureRMSubscription $_
    Write-Output "Collecting VM facts from subscription $($sub.Subscription.Id)"
    Get-AzureRmVM
}

您尝试的问题是,无论$azureSubscriptionID 中包含的值如何,您都会在每次循环迭代期间获得所有订阅 (Get-AzureRmSubscription)。要修复您的代码,您需要运行 Get-AzureRMSubscription -SubscriptionId $subsSelect-AzureRMSubscription -SubscriptionId $subs


如果您想对收集的数据进行进一步处理,当您明确针对已知订阅时,我会考虑一些替代方法。

$azureSubscriptionIDs = "xxxxx-xxxxx-xxxxx-xxxx","yyyyy-yyyyy-yyyyy-yyyy","zzzzz-zzzzz-zzzzz-zzzz"
# $vms is an array of custom objects
# each custom object contains a subscription ID and the associated VMs Names
$vms = foreach ($sub in $azureSubscriptionIDs) {
    $null = Select-AzureRMSubscription -SubscriptionId $sub
    $subvms = Get-AzureRmVM | Select -Expand Name
    $sub | Select @{n='Subscription';e={$_}},@{n='VMs';e={$subvms}}
}
# You can access the subscription ID now with the Subscription property
# You can access the VMs Names with the VMs property
# List all vms under subscription 'xxxxx-xxxxx-xxxxx-xxxx'
$vms | Where Subscription -eq 'xxxxx-xxxxx-xxxxx-xxxx' | Select -Expand VMs
# List all vms for each subscription with a custom console message
foreach ($sub in $vms) {
    Write-Output "Here are all the VMs for subscription $($sub.Subscription)"
    $sub.VMs
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-14
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 2019-02-21
    • 2017-12-30
    相关资源
    最近更新 更多