Hi Oleg Aronov,
Thanks for reaching out to Microsoft Q&A.
To find all Azure resources created in the last 7 days and their associated costs using PowerShell, you can try the folowing steps:
To retrieve resources created in the Last 7 days
You can use the Get-AzResource
cmdlet to list all resources in your subscription. However, since you're interested in the creation date, you will need to use the Azure REST API to get the createdTime
property for each resource.
Here’s a PowerShell script to help you achieve this:
# Set the subscription ID
$subscriptionId = "<YourSubscriptionId>"
# Get the current date and the date 7 days ago
$currentDate = Get-Date
$sevenDaysAgo = $currentDate.AddDays(-7)
# Get all resources in the subscription
$resources = Invoke-AzRestMethod -Uri "https://management.azure.com/subscriptions/$subscriptionId/resources?api-version=2021-04-01&`$expand=createdTime" -Method GET
# Filter resources created in the last 7 days
$newResources = $resources.Content.value | Where-Object {
[datetime]::Parse($_.createdTime) -ge $sevenDaysAgo
}
# Output the new resources
$newResources | Select-Object name, type, createdTime
To retrieve cost information
To retrieve cost information for the resources, you can utilize the Azure Cost Management APIs. However, this requires setting up an application in Azure AD and obtaining the necessary permissions.
Here’s a simplified example of how you might retrieve costs:
# Set the cost management API endpoint
$costManagementApiUrl = "https://management.azure.com/subscriptions/$subscriptionId/providers/Microsoft.CostManagement/query?api-version=2021-10-01"
# Define the request body for the cost query
$requestBody = @{
type = "Usage"
timeframe = "Custom"
timePeriod = @{
from = $sevenDaysAgo.ToString("yyyy-MM-dd")
to = $currentDate.ToString("yyyy-MM-dd")
}
dataset = @{
granularity = "Daily"
aggregation = @{
totalCost = @{
name = "Cost"
function = "Sum"
}
}
}
}
# Convert to JSON
$jsonBody = $requestBody | ConvertTo-Json
# Call the Cost Management API
$response = Invoke-AzRestMethod -Uri $costManagementApiUrl -Method POST -Body $jsonBody -ContentType "application/json"
# Output the cost information
$response.Content
Ensure that the account running these scripts has the necessary permissions to access resource and cost management data.
NOTE:
The cost retrieval may not directly correlate with the resources created in the last 7 days, as costs are typically calculated based on usage over a billing period.
Please 'Upvote'(Thumbs-up) and 'Accept' as an answer if the reply was helpful. This will benefit other community members who face the same issue.