Skip to content

Instantly share code, notes, and snippets.

@rjygraham
Created June 1, 2023 18:58
Show Gist options
  • Save rjygraham/bf631c2cc034ff944ebc4a20d022449a to your computer and use it in GitHub Desktop.
Save rjygraham/bf631c2cc034ff944ebc4a20d022449a to your computer and use it in GitHub Desktop.
Check Movable Azure Resources
[CmdletBinding()]
param (
[Parameter(Mandatory = $True)]
[string]
$TargetSubscriptionId,
[Parameter(Mandatory = $True)]
[string]
$TargetResourceGroup,
[string]
$SourceSubscriptionId,
[string]
$SourceResourceGroup
)
$DestinationResourceGroup = "/subscriptions/$TargetSubscriptionId/resourceGroups/$TargetResourceGroup"
$SubscriptionCount = 0
$ResourceGroupCount = 0
$ResourceCount = 0
$Output = [System.Collections.ArrayList]@()
$Subscriptions = Get-AzSubscription -WarningAction SilentlyContinue
# Target single subscription if SourceSubscriptionId is specified.
if ($SourceSubscriptionId) {
$Subscriptions = $Subscriptions | Where-Object { $_.SubscriptionId -eq $SourceSubscriptionId}
}
Write-Host "Found $($Subscriptions.Count) subscriptions..."
$Subscriptions | ForEach-Object {
$SubscriptionCount++
$SubscriptionId = $_.Id
$ResourceGroupCount = 0
Write-Host "Subscription $SubscriptionCount of $($Subscriptions.Count): ($($_.Name))"
$_ | Select-AzSubscription -WarningAction SilentlyContinue
$ResourceGroups = Get-AzResourceGroup
# Target single resource group if SourceResourceGroup is specified.
if ($SourceResourceGroup) {
$ResourceGroups = $ResourceGroups | Where-Object { $_.ResourceGroupName -eq $SourceResourceGroup}
}
Write-Host "Found $($ResourceGroups.Count) Resource Groups..."
$ResourceGroups | ForEach-Object {
$ResourceGroupCount++
$ResourceGroupName = $_.ResourceGroupName
$ResourceCount = 0
Write-Host "Resource Group $ResourceGroupCount of $($ResourceGroups.Count): ($($_.ResourceGroupName))"
$Resources = Get-AzResource -ResourceGroupName $ResourceGroupName
Write-Host "Found $($Resources.Count) Resources..."
$Resources | ForEach-Object {
$ResourceCount++
$IsMovable = $True
$Reason = ""
Write-Host "Resource $ResourceCount of $($Resources.Count): ($($_.ResourceName))"
try {
Invoke-AzResourceAction -Action validateMoveResources `
-ResourceId "/subscriptions/$SubscriptionId/resourceGroups/$ResourceGroupName" `
-Parameters @{ resources=@($_.ResourceId);targetResourceGroup = $DestinationResourceGroup } `
-Force `
-ErrorAction Stop
}
catch {
$IsMovable = $False
$Reason = $_.Message
}
finally {
$Output.Add(@{SubscriptionId=$SubscriptionId;ResourceGroup=$_.ResourceGroupName;ResourceId=$_.ResourceId;IsMovable=$IsMovable;Reason=$Reason})
}
}
}
}
Write-Host $Output
Export-Csv -InputObject $Output.GetEnumerator() -Path movable-resources.csv
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment