Search code examples
powershellwebhooksazure-virtual-machineazure-automation

Is there a Way to stop an Azure virtual Machine after two hours?


I already have written a PowerShell Script, which starts an Azure Virtual Machine over a POST request to Azure Automation. For cost reasons, those Machines should automatically stop after two hours.

Is there a Way/Function to do this easily?


Solution

  • For your requirement, you need to calculate the duration that the VM running yourself. You can get the event time that the last start time when the VM is in the running time. It's the UTC time. Then calculate the duration up to now yourself. Here is the Azure CLI command to get the event time:

    az vm get-instance-view -g yourResourceGroup -n yourVM --query instanceView.statuses
    

    The screenshot of the result here:

    enter image description here

    Or you can filter the activity log to get the last event "Start Virtual Machine" time. Below is the Azure CLI command:

    az monitor activity-log list --resource-id yourVM_resourceId --query "[?operationName.localizedValue == 'Start Virtual Machine'].eventTimestamp" --max-events 1
    

    I think it should be an interval query task to last for two hours as you need. In my own opinion, it should run in the script that starts the VM.