azureazure-virtual-machine

Azure VM get Value of Files


Is there a way to get the value in this case xml of a file in a specific path? I want to get this information for every VM i have to know on which version my software is running.

I want to get this information by using the Azure portal


Solution

  • Azure VM get Value of Files

    Note: Make sure to assign the azure virtual machine administrator role at the subscription level

    PowerShell code

    Connect-AzAccount -Identity
    Set-AzContext -Subscription "Subscription_ID"
    
    # Path of the XML file on each VM
    $xmlFilePath = "C:\file.xml"
    
    # Define the PowerShell script that will run on each VM
    $script = @"
    param (
        [string]`$xmlFilePath
    )
    [xml]`$xmlContent = Get-Content -Path `"$xmlFilePath`"
    `$appName = `$xmlContent.SoftwareInfo.Application.Name
    `$appVersion = `$xmlContent.SoftwareInfo.Application.Version
    Write-Output "Application Name: `$appName"
    Write-Output "Application Version: `$appVersion"
    "@
    
    $vms = Get-AzVM
    
    # Loop through each VM and execute the script
    foreach ($vm in $vms) {
        try {
            # Run the command on the VM
            $result = Invoke-AzVMRunCommand -ResourceGroupName $vm.ResourceGroupName -VMName $vm.Name -CommandId 'RunPowerShellScript' -ScriptString $script -Parameter @{"xmlFilePath" = $xmlFilePath}
    
            # Display the VM name along with application information
            Write-Output "VM Name: $($vm.Name)"
            Write-Output "Output from VM:"
            $result.Value | ForEach-Object {
                Write-Output $_.Message
            }
            Write-Output "-----------------------------------"
        }
        catch {
            Write-Output "Failed to run command on VM $($vm.Name): $_"
        }
    }
    

    Here is xml file which in azure VM.

    enter image description here

    For the single VM , you can use run command from azure portal by navigating to VM > Run command.

    enter image description here

    For the multiple VM's, you can use automation account with PowerShell script.

    Output:

    enter image description here