Skip to content

Commit

Permalink
Update 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 4263fb9 commit d5c850e
Showing 1 changed file with 25 additions and 6 deletions.
31 changes: 25 additions & 6 deletions Invoke-DeallocateVm.ps1
Original file line number Diff line number Diff line change
@@ -1,15 +1,34 @@
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[string]
$SubscriptionId,

[Parameter()]
[string]
$ResourceGroupName = ''
)

# 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
try {
"Logging in to Azure..."
Connect-AzAccount -Identity
} catch {
Write-Error -Message $_.Exception
throw $_.Exception
}


# Define the resource group and the list of VMs
$resourceGroupName = "YourResourceGroupName"
$vmNames = @("VM1", "VM2", "VM3", ...) # Add all your VM names here
if ([string]::IsNullOrEmpty($ResourceGroupName)) {
Get-AzVM | Where-Object {$_.tags.EnablePrivateNetworkGC -eq "TRUE"}
} else {
Get-AzVM -ResourceGroupName $ResourceGroupName | Where-Object {$_.tags.EnablePrivateNetworkGC -eq "TRUE"}
}

# Function to get the last logon time of a VM
function Get-LastLogonTime {
Expand Down Expand Up @@ -45,6 +64,6 @@ if ($idleTime -gt $idleTimeThreshold) {
Write-Output "VM $vmName is not running. No action required."
}
} catch {
Write-Error "An error occurred while processing VM $vmName: $_"
Write-Error "An error occurred while processing VM $($vmName): $_"
}
}

0 comments on commit d5c850e

Please sign in to comment.