PowerShell Script to Get all Azure VM Extensions

·

2 min read

Remote Software Deployment on multiple Azure Linux and Windows VMs. -  Beyond the Horizon...

The SecOps team had an audit request which required them to check the extensions of all the VMs in an Azure estate. In our case, the SecOps teams wanted to check if we had correctly installed the Splunk agents in the 100+ VMs that we have.

I figured the quickest way to obtain this information would be via a PowerShell script, which would also ensure that future requests from SecOps can be met quickly.

This Script collects Azure Virtual Machine Operating system type and Extension information and exports CSVs per subscription, the CSV includes VM Name, Resource Group, OS Type and Extensions installed. The script also zips the files into one zip folder.

Function Get-VMInfo {
$Subscriptions = Get-AzSubscription -Tenant ""

foreach ($sub in $Subscriptions) {
    #Setting context so the script will be executed within the subscription's scope
    Get-AzSubscription -SubscriptionId $sub.Id -TenantId (Get-AzContext).Tenant | Set-AzContext 
    $SubName  = $sub.Name
    $AllAzVMs = Get-AzVM 
    $Csvfile  = "<path>temp/VM/$subname.csv"

        $All = @()
        foreach ($AllAzVM in $AllAzVMs){
            # $Location = $AllAzVM.location
            $RG = $AllAzVM.ResourceGroupName
            $Name = $AllAzVM.Name
            $Extension = Get-AzVMExtension  -ResourceGroupName $RG  -VMName $Name -Status
            $OutputObj  = New-Object -Type PSObject
            $OutputObj | Add-Member -MemberType NoteProperty -Name VMName -Value $Name
            $OutputObj | Add-Member -MemberType NoteProperty -Name ResourceGroup -Value $RG
            $OutputObj | Add-Member -MemberType NoteProperty -Name OSType -Value $AllAzVM.StorageProfile.OsDisk.OsType
            $OutputObj | Add-Member -MemberType NoteProperty -Name Extension -Value ($Extension.Name | Out-String).Trim()
            $All += $OutputObj

            $All | Format-Table
            Write-Output "Writing CSV file for $subname"
            $All | Export-Csv -Path $Csvfile -NoTypeInformation -Delimiter ";" 
    }
}
}

Function Set-Zip {
    $LogSource="<path>"
    $ZipFileName="VMExtensionInfo.zip"
    New-Item -Force -ItemType directory -Path $LogSource/temp
    Get-ChildItem $LogSource\* -Include *.csv | ForEach-Object {Copy-Item $_ $LogSource/temp}

    if (Test-Path -path $LogSource$ZipFileName)
    {
        Remove-Item -Force $LogSource$ZipFileName
    }

    Add-Type -AssemblyName "System.IO.Compression.FileSystem"
    [System.IO.Compression.ZipFile]::CreateFromDirectory($LogSource+’temp/’, $LogSource+$ZipFileName)

    Remove-Item -Force -Recurse $LogSource\temp
    }

Get-VMInfo
Set-Zip

You can also find it as a Github gist in the link below

https://gist.github.com/taherkhan30/14a5aa7c3f3315055217acd6efb9e99d

I hope you found the script useful

Thankyou for reading