Skip to content

Commit

Permalink
Create Invoke-DeallocateVm.ps1
Browse files Browse the repository at this point in the history
  • Loading branch information
Dylan-Prins authored Dec 6, 2024
1 parent 79eb051 commit 4263fb9
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions Invoke-DeallocateVm.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Import the required modules
Import-Module Az.Compute
Import-Module Az.Accounts

# Authenticate to Azure
# This script assumes you have set up a Run As account in your Azure Automation account
$Connection = Get-AutomationConnection -Name "AzureRunAsConnection"
Connect-AzAccount -ServicePrincipal -TenantId $Connection.TenantId -ApplicationId $Connection.ApplicationId -CertificateThumbprint $Connection.CertificateThumbprint

# Define the resource group and the list of VMs
$resourceGroupName = "YourResourceGroupName"
$vmNames = @("VM1", "VM2", "VM3", ...) # Add all your VM names here

# Function to get the last logon time of a VM
function Get-LastLogonTime {
param (
[string]$vmName
)
# Get the diagnostics logs or performance metrics to determine the last logon time
# For simplicity, this example uses a placeholder value
# Replace this with the actual logic to get the last logon time
$lastLogonTime = (Get-Date).AddHours(-($RANDOM % 24)) # Placeholder logic
return $lastLogonTime
}

# Define the idle time threshold (8 hours)
$idleTimeThreshold = 8

foreach ($vmName in $vmNames) {
try {
$vm = Get-AzVM -ResourceGroupName $resourceGroupName -Name $vmName -Status
$lastLogonTime = Get-LastLogonTime -vmName $vmName

if ($vm.Statuses[1].Code -eq "PowerState/running") {
$currentTime = Get-Date
$idleTime = ($currentTime - $lastLogonTime).TotalHours

if ($idleTime -gt $idleTimeThreshold) {
Write-Output "VM $vmName has been idle for $idleTime hours. Shutting down..."
Stop-AzVM -ResourceGroupName $resourceGroupName -Name $vmName -Force
} else {
Write-Output "VM $vmName has been idle for $idleTime hours. No action required."
}
} else {
Write-Output "VM $vmName is not running. No action required."
}
} catch {
Write-Error "An error occurred while processing VM $vmName: $_"
}
}

0 comments on commit 4263fb9

Please sign in to comment.