Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating AutoShutdown Policy with Azure VM with Powershell

I am trying to create an auto shutdown policy with Powershell for my Azure VM, but keep running into this error:

New-AzureRmResource : MissingRequiredProperty : Missing required property TargetResourceId. At C:\Users\home\Documents\CreateAzureVM.ps1:167 char:1 + New-AzureRmResource -Location $Loc -ResourceId $ScheduledShutdownReso ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : CloseError: (:) [New-AzureRmResource], ErrorResponseMessageException + FullyQualifiedErrorId : MissingRequiredProperty,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.NewAzureResourceCmdlet

I am at a lost on how to fix this error, this is my script piece so far:

 $SubscriptionId = $AzContext.Context.Subscription.Id;  
$VMResourceId = (Get-AzureRmVM).id
$ScheduledShutdownResourceId = "/subscriptions/$SubscriptionId/resourceGroups/$RSGName/providers/microsoft.devtestlab/schedules/shutdown-computevm-$VMName"

$Properties = @{}
$Properties.Add('status', 'Enabled')
$Properties.Add('taskType', 'ComputeVmShutdownTask')
$Properties.Add('dailyRecurrence', @{'time'= 1159})
$Properties.Add('timeZoneId', "Eastern Standard Time")
$Properties.Add('notificationSettings', @{status='Disabled'; timeInMinutes=15})
$Properties.Add('targetResourceId', $VMResourceId)

#Error
New-AzureRmResource -Location $Loc -ResourceId $ScheduledShutdownResourceId -Properties $Properties -Force
like image 205
neoncolors Avatar asked Sep 17 '25 11:09

neoncolors


1 Answers

The cause:

This script $VMResourceId = (Get-AzureRmVM).id is not for a specific VM. You should get a specific VM.

Try to use following Powershell scripts:

$SubscriptionId = $AzContext.Context.Subscription.Id
$VM = Get-AzureRmVM -ResourceGroupName $RGName -Name VMName
$VMResourceId = $VM.Id
$ScheduledShutdownResourceId = "/subscriptions/$SubscriptionId/resourceGroups/wayneVMRG/providers/microsoft.devtestlab/schedules/shutdown-computevm-$VMName"

$Properties = @{}
$Properties.Add('status', 'Enabled')
$Properties.Add('taskType', 'ComputeVmShutdownTask')
$Properties.Add('dailyRecurrence', @{'time'= 1159})
$Properties.Add('timeZoneId', "Eastern Standard Time")
$Properties.Add('notificationSettings', @{status='Disabled'; timeInMinutes=15})
$Properties.Add('targetResourceId', $VMResourceId)

#Error
New-AzureRmResource -Location eastus -ResourceId $ScheduledShutdownResourceId  -Properties $Properties  -Force

Here is the result:

enter image description here

like image 185
Wayne Yang Avatar answered Sep 21 '25 13:09

Wayne Yang