This script deletes old computer accounts if the Azure virtual machine was deleted. Current script is triggered by Azure Automation webhook and uses Azure Automation credential with a Hybrid Worker.
#Triggered by Webhook from GitActions on a Schedule.
#Remove Stale AD Computer Accounts
# Payload Azure Automation parameters.
param (
[Parameter(Mandatory=$false)]
[object] $WebhookData,
[Parameter(Mandatory=$false)]
[array] $DeleteStaleADComputerAccounts,
[Parameter(Mandatory=$false)]
[string] $SNOW_TICKET
)
if ($WebhookData.RequestBody) {
$payload = $WebhookData.RequestBody | ConvertFrom-Json
if ($payload.DeleteStaleADComputerAccounts) {
$DeleteStaleADComputerAccounts += $payload.DeleteStaleADComputerAccounts
}
if ($payload.SNOW_TICKET) {
$SNOW_TICKET = $payload.SNOW_TICKET
}
}
# Get Credentials from Azure Automation and Use to Run script
$creds = Get-AutomationPSCredential -Name "<Account>"
# Create a new PowerShell session with the specified credentials
$session = New-PSSession -Credential $creds
# Import the Active Directory module
Import-Module ActiveDirectory
# Define an array to store all computer accounts
$computerAccounts = @()
# Define an array to store all virtual machine names
$virtualMachineNames = @()
$BaseOUs = @("OU=MultiSession,OU=AVD,DC=domain,DC=com",
"OU=Personal,OU=AVD,DC=domain,DC=com")
$allComputers = @()
$deleteCountPooled = 0
$deleteCountDedicated = 0
foreach ($baseOu in $BaseOUs) {
# Get all direct sub OUs of the base OU
$OUs = Get-ADOrganizationalUnit -Filter 'Name -like "*"' -SearchBase $baseOu -SearchScope OneLevel | Select-Object -ExpandProperty DistinguishedName
foreach ($Ou in $OUs) {
$computers = Get-ADComputer -Filter * -SearchBase $Ou
$allComputers += $computers
}
}
# Get all Azure VMs only once
$allAzureVMs = Get-AzVM
$allComputers | ForEach-Object {
$computerName = $_.Name
$azureVm = $allAzureVMs | Where-Object { $_.Name -eq $computerName }
if (!$azureVm) {
Write-Output "Computer account '$computerName' does not have a corresponding Azure Virtual Machine. Deleting the account..."
############Change Confirm to False to skip the confirmation prompt############
Get-ADComputer -Filter { Name -eq $computerName } -Credential $creds | Remove-ADObject -Recursive -Confirm:$True -Credential $creds
Write-Output "Deleted computer account: $computerName"
if ($_.DistinguishedName -like '*OU=MultiSession*') {
$deleteCountPooled++
}
elseif ($_.DistinguishedName -like '*OU=Personal*') {
$deleteCountDedicated++
}
}
}
Write-Output "Total computer accounts to be deleted in Pooled OU: $deleteCountPooled"
Write-Output "Total computer accounts to be deleted in Dedicated OU: $deleteCountDedicated"