如何使用CLI删除Azure Fileshare中的文件夹
Azure 文件共享删除文件夹可落地解决方案
az storage file delete 仅支持删除单个文件,无法直接删除非空文件夹,以下是三种实测有效的脚本方案,可按需选择:
方案1:纯Azure CLI递归删除(无需额外安装工具)
适合已配置Azure CLI的运行环境,先删除目录下所有文件,再逐层删除文件夹,多层嵌套场景可把遍历逻辑封装为递归函数使用:
# 替换为实际参数 accountName="存储账户名" accountKey="存储账户密钥" myshare="文件共享名" targetFolder="待删除的文件夹路径" # 第一步:删除目标文件夹下所有文件 az storage file list -s $myshare -p $targetFolder --account-name $accountName --account-key $accountKey --query "[].name" -o tsv | while read fileName; do az storage file delete -s $myshare -p "$targetFolder/$fileName" --account-name $accountName --account-key $accountKey done # 第二步:逐层删除子目录及子目录内文件 az storage directory list -s $myshare -p $targetFolder --account-name $accountName --account-key $accountKey --query "[].name" -o tsv | while read dirName; do subDir="$targetFolder/$dirName" # 删除子目录下所有文件 az storage file list -s $myshare -p $subDir --account-name $accountName --account-key $accountKey --query "[].name" -o tsv | while read subFileName; do az storage file delete -s $myshare -p "$subDir/$subFileName" --account-name $accountName --account-key $accountKey done # 删除空的子目录 az storage directory delete -s $myshare -p $subDir --account-name $accountName --account-key $accountKey done # 第三步:删除顶层目标文件夹 az storage directory delete -s $myshare -p $targetFolder --account-name $accountName --account-key $accountKey
方案2:AzCopy批量删除(大文件/多文件场景效率更高)
之前操作失效大概率是版本或参数配置错误,使用AzCopy v10及以上版本执行以下命令即可直接递归删除非空文件夹:
azcopy rm "https://$accountName.file.core.windows.net/$myshare/$targetFolder?$accountKey" --recursive=true
如果不使用账户密钥认证,也可以先执行azcopy login完成Azure身份认证后再运行删除命令。
方案3:PowerShell方案(Windows环境首选)
提前安装Az.Storage模块:Install-Module -Name Az.Storage -Force,之后执行以下脚本即可直接删除非空文件夹:
$accountName = "存储账户名" $accountKey = "存储账户密钥" $myshare = "文件共享名" $targetFolder = "待删除的文件夹路径" $context = New-AzStorageContext -StorageAccountName $accountName -StorageAccountKey $accountKey Remove-AzStorageDirectory -ShareName $myshare -Path $targetFolder -Context $context -Recurse -Force
内容的提问来源于stack exchange,提问作者Demiurge
相关产品推荐
相关产品推荐

