Forum Discussion
svhelden
Oct 31, 2023Brass Contributor
How to get the REAL hostname with Powershell (or Graph API)
Not sure if this question belongs here. I want to retrieve a list of Azure VMs and their real host name (not the VM name). Azure portal shows this name just fine: Per documentation, I sh...
- Nov 03, 2023
samy_vanderspikken
Nov 02, 2023Brass Contributor
Hi svhelden
You can list the Azure VM's with their corresponding hostname via the following procedure.
Create the following Powershell script (yes only the 'hostname' command) on your computer and save it as 'hostname.ps1'
Hostname
Then create the 'list-hostname.ps1' Powershell script (Make sure to edit the X):
# #Azure Subscription I want to use
$subscriptionId = "XXXXXX-XXX-XXXX-XXXX-XXXXXXXXXXXX"
#Resource Group my VMs are in
$resourceGroup = "XXXX"
#Select the right Azure subscription
Set-AzContext -Subscription $subscriptionId
#Get all Azure VMs which are in running state and are running Windows
$myAzureVMs = Get-AzVM -ResourceGroupName $resourceGroup -status | Where-Object {$_.PowerState -eq "VM running" -and $_.StorageProfile.OSDisk.OSType -eq "Windows"}
#Run the scirpt again all VMs in parallel
$myAzureVMs | ForEach-Object -Parallel {
$out = Invoke-AzVMRunCommand `
-ResourceGroupName $_.ResourceGroupName `
-Name $_.Name `
-CommandId 'RunPowerShellScript' `
-ScriptPath .\hostname.ps1
#Formating the Output with the VM name
$output = $_.Name + " " + $out.Value[0].Message
$output
}
After creating the scripts upload them to the Azure Cloud Shell.
Then execute the following command in the Cloud Shell:
.\hostname.ps1
.\list-hostname.ps1
And that's it! Now you have a list if VM names with their corresponding hostnames.
Please let me know if you run into any other issues.
- svheldenNov 02, 2023Brass ContributorLooks like it would work, but isn't that a bit overkill effort? Wondering where Azure portal takes the hostname from ...
- samy_vanderspikkenNov 03, 2023Brass ContributorHi svhelden,
Communication to VM's in the Cloud Shell only happens to the Azure VM resource itself and unfortunately not within the VM unless u use a command that invokes a script within the VM.
I hope you can go further with this info!- svheldenNov 03, 2023Brass Contributor