frameworkResources/Scripts/list_vms_in_environment.ps1
|
Param( [Parameter(Mandatory)] $ResourceName, [string]$ScriptsFolderPath = ".\Resources\Scripts" ) . "$ScriptsFolderPath\common.ps1" 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 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 = GetVmsWithPublicIp -ResourceGroupName $resourceGroupName Write-Output $vmsObject } ShowExecutingCommand if (-not (Get-AzContext)) { NoContext Connect-AzAccount if (Get-AzContext) { ShowVms } } else { ShowVms } |