Self-deallocation of an Azure Windows VM on shutdown.🔗︎
I've used this Gist and adapted it for Windows.
One's first thought on getting this to work on Windows might be to use Task Scheduler, but there is no "Begin the task" on shutdown option. One can use on event, and interrogate the event logs, but this seems to be hit and miss. Probably because the order in which services shutdown. In this solution, I use local group policy to configure a shutdown script. I'm using Windows 11, Enterprise (24H2), but be aware that not all editions of Windows have local group policy, although the same should be achievable via the registry.
There are other ways to achieve the same goal. Policy, Automation Accounts, etc, but this solution lives on the VM to be deallocated. What happens when there is an update, remains to be seen...
Steps🔗︎
- Follow Gist to set up System Assigned Identity.
- Install AzCli (
winget install Microsoft.AzureCLI
). - Launch Local Group Policy editor (Start > Run >
gpedit.msc
). - Navigate to Computer Configuration -> Policies -> Windows Settings -> Scripts (Startup / Shutdown).
- Double-click Shutdown.
- Click Show Files... button
The Shutdown directory will open with the path:C:\Windows\System32\GroupPolicy\Machine\Scripts\Shutdown
- Create a new text file named:
self-deallocate.ps1
. - Open the file in a text editor and paste in the code provided below.
- Replace
<virtual_machine_name>
and<resource_group>
with your values. - Save and close the script.
- Ensure you're on the Scripts tab (not PowerShell Scripts).
- Click the Add... button.
-
Provide the following:
Property Value Script Name "%ProgramFiles%\PowerShell\7\pwsh.exe"
Script Parameters -Noninteractive -ExecutionPolicy Bypass -Noprofile -File self-deallocate.ps1
Note
Here, I am using PowerShell Core. When %ProgramFiles%
expands, it contains a space, so it most be wrapped in single of double speech marks.
You can alternatively use Windows PowerShell with:
%windir%\System32\WindowsPowerShell\v1.0\powershell.exe
Which doesn't need quotes as the expanded form doesn't contain a space.
self-deallocate.ps1 | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|