# 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 选项用于通过 ID 指定虚拟机,--time 和 --auto-start- 选项分别用于设置自动关闭和自动启动属性。
这两个脚本还会提示你选择是自动重新启动计算机还是将其关闭直至手动重新启动。 该选项用于设置 VM 的 --auto-shutdown-enabled 属性。