PowerShell如何获取文件的Tags和Comment属性
Get-MetaData并非PowerShell内置命令,大概率是第三方模块(且这类模块通常没有官方分发渠道,很难找到),直接用Windows自带的COM对象或内置命令就能实现需求,以下是两种可靠方法:
方法1:使用Shell.Application COM对象(推荐,适配绝大多数文件类型)
该方法直接调用Windows资源管理器的底层接口,能获取「文件属性>详细信息」里的所有属性,包括Tags和Comment。
基础脚本(适配英文系统)
function Get-FileTagsAndComment { param( [Parameter(Mandatory=$true)] [string]$FilePath ) # 初始化Shell对象 $shell = New-Object -ComObject Shell.Application $folder = $shell.Namespace((Split-Path $FilePath)) $fileItem = $folder.ParseName((Split-Path $FilePath -Leaf)) # 属性对应的固定索引(英文系统) $propertyMap = @{ Tags = 18 Comment = 14 } # 提取属性值 $result = [PSCustomObject]@{ FilePath = $FilePath Tags = $folder.GetDetailsOf($fileItem, $propertyMap.Tags) Comment = $folder.GetDetailsOf($fileItem, $propertyMap.Comment) } # 清理COM对象,避免内存泄漏 [System.Runtime.Interopservices.Marshal]::ReleaseComObject($fileItem) | Out-Null [System.Runtime.Interopservices.Marshal]::ReleaseComObject($folder) | Out-Null [System.Runtime.Interopservices.Marshal]::ReleaseComObject($shell) | Out-Null return $result } # 使用示例 Get-FileTagsAndComment -FilePath "D:\Documents\report.pdf"
适配中文系统的动态索引查找
如果是中文系统,属性索引会不同,可先动态找到对应属性的索引值:
function Get-PropertyIndex { param( [Parameter(Mandatory=$true)] [string]$PropertyName, [string]$SampleFolder = "C:\" ) $shell = New-Object -ComObject Shell.Application $folder = $shell.Namespace($SampleFolder) # 遍历0-300的索引范围,查找目标属性名 for ($i = 0; $i -lt 300; $i++) { $currentProp = $folder.GetDetailsOf($folder.Items, $i) if ($currentProp -eq $PropertyName) { return $i } } # 清理对象 [System.Runtime.Interopservices.Marshal]::ReleaseComObject($folder) | Out-Null [System.Runtime.Interopservices.Marshal]::ReleaseComObject($shell) | Out-Null return $null } # 获取中文系统下的属性索引 $tagsIndex = Get-PropertyIndex -PropertyName "标记" $commentIndex = Get-PropertyIndex -PropertyName "备注"
将上述获取到的索引替换到基础脚本的propertyMap中即可。
方法2:使用Get-ItemProperty(仅适配部分文件类型)
对于EXE、DLL等具有版本信息的文件,可直接读取Comment属性,但Tags属性无法通过此方法获取:
$file = Get-Item "C:\Windows\notepad.exe" # 读取Comment属性 $file.VersionInfo.Comments
内容的提问来源于stack exchange,提问作者Boucourt
相关产品推荐
相关产品推荐

