framework/Resources/Scripts/list_vms_in_environment.ps1

Param(
    [Parameter(Mandatory)]
    $ResourceName
)


function GetNetworkInterface {
    param(
        [string]$ResourceGroup,
        [PSCustomObject[]]$VmCustomObject
    )
    foreach ($vmObject in $VmCustomObject) {
        $nic = Get-AzNetworkInterface -Name $vmObject.NIC -ResourceGroupName $ResourceGroup
        $publicIp = $nic | Select-Object -ExpandProperty IpConfigurations
        $vmObject | Add-Member NoteProperty -Name "PublicIpResource" -Value $publicIp[0].PublicIpAddress.Id.Split('/')[-1]
    }
}

function GetPublicIps {
    param(
        [Parameter(Mandatory)]
        [string]$ResourceGroupName,
        [Parameter(Mandatory)]
        [PSCustomObject[]]$VmCustomObject
    )
    $publicIpsMap = @{}
    foreach ($vmObject in $VmCustomObject) {
        $publicIp = Get-AzPublicIpAddress -Name $($vmObject.PublicIpResource) `
            -ResourceGroupName $ResourceGroupName `
        | Select-Object -ExpandProperty IpAddress
        $vmObject | Add-Member NoteProperty -Name "PublicIpAddress" -Value $publicIp
    }
    return $publicIpsMap
}



function GetVmsNamesMap {
    param(
        [string]$ResourceGroupName
    )
    $vmsObject = @(Get-AzVM -ResourceGroupName $ResourceGroupName |
        Where-Object { $_.Tags.ContainsKey("ServerType") -and $_.Tags["ServerType"] -eq "NCache" } | ForEach-Object {
            
            $nicId = $_.NetworkProfile.NetworkInterfaces[0].Id
            $nicName = ($nicId -split "/")[-1]
            
            $nic = Get-AzNetworkInterface -ResourceGroupName $ResourceGroupName -Name $nicName
            
            $privateIp = $nic.IpConfigurations[0].PrivateIpAddress

            [PSCustomObject]@{
                Name            = $_.Name
                Location        = $_.Location
                NIC             = $nicName
                PrivateIp       = $privateIp
            }
        } -ErrorAction Stop)
    return $vmsObject
}

function ShowVms {
    Write-Host "Fetching Servers..."
    $resourceGroupName = Get-AzResourceGroup -ErrorAction Stop | Where-Object { $_.Tags -and $_.Tags.Contains("EnvironmentName") -and $_.Tags["EnvironmentName"] -eq $ResourceName } | Select-Object -ExpandProperty ResourceGroupName 
    if (-not $resourceGroupName) {
        throw "No such environment exists"
    }
    $vmsObject = GetVmsNamesMap -ResourceGroupName $resourceGroupName
    Write-Output $vmsObject
}

if (-not (Get-AzContext)) {
    Connect-AzAccount
    if (Get-AzContext) {
        ShowVms
    }
}
else {
    ShowVms
}