Forum Discussion

svhelden's avatar
svhelden
Brass Contributor
Oct 31, 2023
Solved

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 should get the same name from OsProfile property through Get-AzVM or Graph API. But this returns the instance name, or part of that, not the host name:


How can I get the real host name? Obviously Azure knows it because it is displayed fine in the portal.

5 Replies

  • 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. 

    • svhelden's avatar
      svhelden
      Brass Contributor
      Looks like it would work, but isn't that a bit overkill effort? Wondering where Azure portal takes the hostname from ...
      • samy_vanderspikken's avatar
        samy_vanderspikken
        Brass Contributor
        Hi 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!



Resources