# Set the resource group name, VM name, and shutdown time
RESOURCE_GROUP_NAME="myResourceGroup"
VM_NAME="myVM" # Add your VM's name here
SHUTDOWN_TIME="18:00"
# Prompt the user to choose whether to auto-restart or leave the machines off
echo "Do you want to auto-restart the machine? (y/n)"
read RESTART_OPTION
# Set the auto-shutdown and auto-start properties based on the user's choice
if [ "$RESTART_OPTION" == "y" ]; then
AUTO_SHUTDOWN="true"
AUTO_START="true"
else
AUTO_SHUTDOWN="true"
AUTO_START="false"
fi
# Set the auto-shutdown and auto-start properties for the VM
az vm auto-shutdown -g $RESOURCE_GROUP_NAME -n $VM_NAME --time $SHUTDOWN_TIME
if [ "$AUTO_START" == "true" ]; then
az vm restart -g $RESOURCE_GROUP_NAME -n $VM_NAME --no-wait
fi
若要使用 Azure CLI 設定多部虛擬機器的自動關機,您可以使用下列指令碼:
# Set the resource group name and shutdown time
RESOURCE_GROUP_NAME="myResourceGroup"
SHUTDOWN_TIME="18:00"
# Prompt the user to choose whether to auto-restart or leave the machines off
echo "Do you want to auto-restart the machines? (y/n)"
read RESTART_OPTION
# Set the auto-shutdown and auto-start properties based on the user's choice
if [ "$RESTART_OPTION" == "y" ]; then
AUTO_SHUTDOWN="true"
AUTO_START="true"
else
AUTO_SHUTDOWN="true"
AUTO_START="false"
fi
# Loop through all VMs in the resource group and set the auto-shutdown and auto-start properties
for VM_ID in $(az vm list -g $RESOURCE_GROUP_NAME --query "[].id" -o tsv); do
az vm auto-shutdown --ids $VM_ID --time $SHUTDOWN_TIME
az vm restart --ids $VM_ID --no-wait
done
上述指令碼使用 az vm auto-shutdown 和 az vm restart 命令來設定指定資源群組中所有 VM 的 auto-shutdown 和 restart 屬性。 --ids 選項可用來依其識別碼指定 VM,而 --time 和 --auto-start- 啟用選項則分別用來設定自動關機和自動啟動屬性。
這兩個指令碼也會提示選擇是否要自動重新啟動機器,或將其關閉,直到手動重新啟動為止。 此選擇用於設定 VM 的 -auto-shutdown-enabled 屬性。