The code snippet below shows how to run Resource Graph queries with PowerShell. The example uses a custom PowerShell class that may be used for streaming objects back to a Log Analytics workspace.
This example uses a custom authentication module that I've written (that's available here: https://github.com/LaurieRhodes/AZRest/tree/main) although tokens could also be obtained by using ADAL libraries or Microsoft's Az cmdlets.
$subscriptionID = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx"
# Get an authorised Azure Header
$authHeader = Get-Header -scope "azure" -Tenant "laurierhodes.info" -AppId "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx" `
-secret 'xxxxxxxxxxxxxxxxxxxxxxxxx
# Example Kusto Query
$KustoQuery = "resources | where type == 'microsoft.compute/virtualmachines' | project properties['osProfile']['adminUsername'] , properties['hardwareProfile']['vmSize'] , properties['osProfile']['windowsConfiguration']['patchSettings']['patchMode'] "
#The REST body for a POST Request specifies the query to be made and the subscription used as scope.
$body = @"
{
"subscriptions": [
"$($subscriptionID)"
],
"query": "$($KustoQuery )"
}
"@
$result = $null
$result = invoke-RestMethod -method POST `
-uri "https://management.azure.com/providers/Microsoft.ResourceGraph/resources?api-version=2019-04-01" `
-Headers $authHeader `
-Body $body
# Dynamically create a new class from the returned headers
Invoke-Expression @"
Class responseObj {
$(($result.data.columns ).ForEach({"[$( if($_.type -eq 'object'){ 'psobject' }else{ $_.type } )] `${$($_.name)}`n "}))
}
"@
$responsearray=@()
foreach ( $row in $result.data.rows){
$response = $null
# create a new object for the record details
$response = New-Object -TypeName responseObj
# Populate each class property with column data
For ($i=0; $i -le ($row.Count-1); $i++) {
$response.$($result.data.columns[$i].name) = $($row[$i])
}
}
# Print data
$responsearray
- Log in to post comments