如何为PowerShell中Get-AzStorageBlob命令的输出追加文本?
解决PowerShell中为Storage Blob名称追加文本的问题
问题场景
你需要给Get-AzStorageBlob返回的Blob名称追加固定注释,原命令如下:
Get-AzStorageBlob -Container 'MyContainer' -Context $context | Where-Object {$_.Name -like "*LOG_0206*"} | Select-Object -Property Name
当前输出为表格格式的Blob名称:
Name ---- tlog/MyServer/CW_ata_LOG_02062023_100000.TRN tlog/MyServer/CW_ata_LOG_02062023_120000.TRN
期望输出为每个名称后追加注释:
Name ---- tlog/MyServer/CW_ata_LOG_02062023_100000.TRN -> current log file tlog/MyServer/CW_ata_LOG_02062023_120000.TRN -> current log file
错误原因
你尝试用Select-Object -Property Name + '-> current log file'会报错:
Select-Object: A positional parameter cannot be found that accepts argument '+'
这是因为Select-Object的-Property参数不支持直接的字符串拼接语法,它仅接受属性名或计算属性哈希表。
正确解法
方法1:使用计算属性(保留表格格式)
通过定义计算属性,自定义Name列的输出内容,同时保留原表格结构:
Get-AzStorageBlob -Container 'MyContainer' -Context $context | Where-Object {$_.Name -like "*LOG_0206*"} | Select-Object -Property @{ Name = 'Name' Expression = { $_.Name + ' -> current log file' } }
Name字段指定输出的列名(保持为Name)Expression脚本块中实现字符串拼接逻辑,生成最终的列值
方法2:直接输出拼接后的字符串(无表格格式)
如果不需要表格结构,仅需输出带注释的文件名,可使用ForEach-Object直接处理:
Get-AzStorageBlob -Container 'MyContainer' -Context $context | Where-Object {$_.Name -like "*LOG_0206*"} | ForEach-Object { "$($_.Name) -> current log file" }
输出结果为:
tlog/MyServer/CW_ata_LOG_02062023_100000.TRN -> current log file tlog/MyServer/CW_ata_LOG_02062023_120000.TRN -> current log file
内容的提问来源于stack exchange,提问作者sydney
相关产品推荐
相关产品推荐

