I am attempting to query the Azure tenant for any newly created resources in the last 2 days, I am using the query below and its coming up blank, I would also like to alter the query to create a version that only returns virtual machines created in the last 48 hours.
# Connect to Azure
Connect-AzAccount
# Define the time range (last 48 hours)
$startTime = (Get-Date).AddHours(-48).ToString("yyyy-MM-ddTHH:mm:ssZ")
# Corrected Azure Resource Graph Query
$query = @"
Resources
| extend createdTime = coalesce(todatetime(properties.createdTime), todatetime(properties.createdOn))
| where isnotnull(createdTime) and createdTime > datetime($startTime)
| project name, type, location, resourceGroup, subscriptionId, createdTime
| order by createdTime desc
"@
# Execute the query
$resources = Search-AzGraph -Query $query
Your query and the question aren't really related, to answer the question, how to get Virtual Machines created in the last 48hs you first need to filter by resources of type microsoft.compute/virtualmachines
and from there, you can find the date those resources were created in properties.timeCreated
.
You should also be aware that Search-AzGraph
can output paginated responses, so you need to handle that case if there could be more than 100 VMs as a result of your query.
In summary, the logic for pagination and the query can be:
# Always use UTC DateTime for KQL queries to Resource Manager
$startTime = [datetime]::UtcNow.AddDays(-2).ToString('o')
$searchAzGraphSplat = @{
Query = "
resources
| where ['type'] == 'microsoft.compute/virtualmachines'
| extend timeCreated = todatetime(properties.timeCreated)
| where timeCreated > todatetime('$startTime')
| project name, type, location, resourceGroup, subscriptionId, timeCreated
"
}
$result = do {
$response = Search-AzGraph @searchAzGraphSplat
$searchAzGraphSplat['SkipToken'] = $response.SkipToken
if ($response.Data) {
$response.Data
}
}
while ($response.SkipToken)