使用Azure CLI删除资源组内资源但保留组时遇命令执行错误
删除Azure资源组内所有资源但保留资源组的问题解决
之前尝试用Azure CLI删除资源组内所有资源但保留资源组,参考的方案在Azure Cloud Shell中执行时出现以下错误:
错误情况1
执行命令:
az resource list --resource-group senthil-b-rg ConvertFrom-Json Foreach-Object {az resource delete --resource-group senthil-b-rg --ids $_.id --verbose}
报错:
unrecognized arguments: ConvertFron-Json Foreach-Object {az resource delete --ids /usr/bin/cloudshellhelp.id --verbose
错误情况2
加入管道符后执行:
az resource list --resource-group senthil-b-rg \ | ConvertFrom-Json | Foreach-Object {az resource delete --resource-group senthil-b-rg --ids $_.id --verbose}
报错:
bash:ConvertFrom-Json: command not found bash: Foreach-Object: command not found Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'> BrokenPipleError: [Errno 32] Broken pipe
问题原因
出现这些错误是因为命令混用了PowerShell语法和Bash环境:
- 第一个错误是没加管道符,Azure CLI把
ConvertFrom-Json等内容当成了az resource list的参数,自然无法识别。 - 第二个错误是Azure Cloud Shell默认是Bash环境,而
ConvertFrom-Json、Foreach-Object是PowerShell的专属命令,Bash中没有这些命令,所以提示找不到。
解决方案
方案1:在Bash环境下执行(默认环境)
Bash中可以用jq工具解析JSON输出,或者直接用Azure CLI的--query参数输出资源ID列表,再循环删除:
方法A(用--query简化输出)
az resource list --resource-group senthil-b-rg --query "[].id" -o tsv | while read resource_id; do az resource delete --ids "$resource_id" --verbose done
方法B(用jq解析JSON)
az resource list --resource-group senthil-b-rg -o json | jq -r '.[].id' | while read resource_id; do az resource delete --ids "$resource_id" --verbose done
方案2:切换到PowerShell环境执行
如果想使用原参考方案的PowerShell语法,需要先在Azure Cloud Shell界面顶部切换到PowerShell环境,再执行以下命令:
az resource list --resource-group senthil-b-rg | ConvertFrom-Json | ForEach-Object { az resource delete --resource-group senthil-b-rg --ids $_.id --verbose }
内容的提问来源于stack exchange,提问作者anon
相关产品推荐
相关产品推荐

