Azure文件共享无法列出目录内容,请求调整PowerShell脚本
修正后的Azure文件共享递归列表脚本
问题根源
- 未初始化存储账户对象:原脚本直接使用
$storageAccount.Context但未通过Get-AzStorageAccount获取存储账户实例,会导致操作上下文无效。 - 错误获取目录内容:
Get-AzStorageFile -Path $path仅返回指定路径的目录对象本身,而非其下的子文件/文件夹,导致循环仅处理目标目录。 - 不必要的递归条件:
if ($item.Path -like "$directoryPath\\*")限制了递归范围,实际需要递归所有子目录。
修正后的脚本
$resourceGroupName = "xbackbonektadevmc-rg" $storageAccName = "xfssaktamc601" $fileShareName = "imagingcenter" $directoryPath = "Software\KTA OPMT\KofaxTotalAgility-7.11 Software\KofaxTotalAgility-7.11.0.11_OPMT" # 获取存储账户实例(关键缺失步骤) $storageAccount = Get-AzStorageAccount -ResourceGroupName $resourceGroupName -Name $storageAccName $ctx = $storageAccount.Context # 定义递归列出文件和文件夹的函数 Function GetFiles { param ( [string]$path ) Write-Host -ForegroundColor Green "正在列出 $path 下的文件和文件夹.." # 获取指定路径下的所有子文件和子文件夹(修正内容获取方式) $targetDirectory = Get-AzStorageFile -Context $ctx -ShareName $fileShareName -Path $path $filesAndFolders = $targetDirectory | Get-AzStorageFile foreach($item in $filesAndFolders) { # 更可靠的目录类型检查 if ($item -is [Microsoft.WindowsAzure.Commands.Storage.Model.ResourceModel.AzureStorageFileDirectory]) { Write-Host -ForegroundColor Red "文件夹: " $item.Name # 递归遍历子文件夹(移除不必要的路径限制) GetFiles -path $item.Path } else { Write-Host -ForegroundColor Yellow "文件: " $item.Name } } } # 启动递归列表 GetFiles -path $directoryPath
关键修正说明
- 添加
Get-AzStorageAccount获取存储账户实例,确保操作上下文有效。 - 先获取目标目录对象,再通过管道
Get-AzStorageFile获取其下的子内容,这是正确获取目录内项的方式。 - 移除递归路径限制,确保所有子目录都被递归遍历。
- 使用类型检查
$item -is [AzureStorageFileDirectory]替代GetType().Name,避免类型名称变化导致的判断失效。
内容的提问来源于stack exchange,提问作者Guttala VamC
相关产品推荐
相关产品推荐

