Fetching owner details in Azure resources created an year ago

97 Views Asked by At

I tried to fetch details of resource owners created an year ago using powershell script but iam getting errors. Is it possible to create one?

This is the code I used:

foreach ($resource in $resources) { 
    $createdBy = $resource.Properties.createdBy 
    if ($createdBy -and $createdBy.userPrincipalName) { 
        $ownerDetails = Get-AzADUser -UserPrincipalName $createdBy.userPrincipalName 
        Write-Host "Resource: $($resource.Name), Created by: $($ownerDetails.DisplayName) - $($ownerDetails.UserPrincipalName)" 
    }
}
1

There are 1 best solutions below

6
Jahnavi On

The PowerShell script you used is looking good to me to achieve your requirement. But it might not work as expected if the creationdate/time doesn't contain the proper information about the owner identity.

Instead use createdby to retrieve the exact requirement as shown below.

Efficient script:

$date = (Get-Date).AddYears(-1)
$resource = Get-AzResource | Where-Object { $_.Properties.createdTime -lt $date }

foreach ($res in $resource) {
    Write-Output "ResourceID: $($res.ResourceId), Createdby: $($res.Properties.CreatedBy)"
}

enter image description here

Alternatively, you can also use the Get-AzLog command to get the above needed information which is detailed below.

$startTime = (Get-Date).AddYears(-1)
$endTime = Get-Date
$logs = Get-AzLog -StartTime $startTime -EndTime $endTime -Status "Started" -Resourceprovider "Microsoft.Resources/deployments"
foreach ($log in $logs) {
    $user = $log.Claims["http://schemas.microsoft.com/identity/claims/objectidentifier"]
    if ($user) {
        $info = Get-AzADUser -ObjectId $user
        Write-Host "Resourceinfo:$($log.ResourceId), Created by: $($info.DisplayName) - $(info.UserPrincipalName)"
    }
}