使用PowerShell读写非常见文件类型的Windows自定义文件属性
用PowerShell读写Windows文件的自定义属性
可以实现,以下是针对非Office、媒体等特殊格式文件的现代读写方案,对应你提到的文件属性GUI中「自定义」标签页的可配置属性(支持文本、日期、数字、是/否类型):
获取自定义属性
方法1:使用Windows.Storage API(现代推荐)
基于.NET Windows Runtime API,无需依赖COM对象,兼容性更好:
$filePath = "C:\mypath\myfile.uncommonfileextension" # 获取文件对象 $file = [Windows.Storage.StorageFile]::GetFileFromPathAsync($filePath).GetAwaiter().GetResult() # 检索所有自定义属性 $customProperties = $file.Properties.RetrievePropertiesAsync(@("System.CustomProperties")).GetAwaiter().GetResult() # 遍历输出属性名和值 foreach ($propName in $customProperties.Keys) { Write-Host "$propName = $($customProperties[$propName])" }
方法2:改进Shell COM代码
针对你提供的原有代码,调整为直接读取自定义属性集合(而非遍历预定义属性ID):
$filePath = "C:\mypath\myfile.uncommonfileextension" $shell = New-Object -ComObject Shell.Application $folder = $shell.Namespace([System.IO.Path]::GetDirectoryName($filePath)) $file = $folder.ParseName([System.IO.Path]::GetFileName($filePath)) # 获取自定义属性集合 $customProps = $file.ExtendedProperty("System.CustomProperties") if ($customProps) { foreach ($prop in $customProps) { Write-Host "$($prop.Name) = $($prop.Value)" } }
设置自定义属性
使用Windows.Storage API(现代推荐)
设置时需严格匹配属性类型(文本/日期/数字/布尔),否则无法在GUI中正确显示:
$filePath = "C:\mypath\myfile.uncommonfileextension" $file = [Windows.Storage.StorageFile]::GetFileFromPathAsync($filePath).GetAwaiter().GetResult() # 定义要设置的自定义属性(示例覆盖四种类型) $propertiesToSet = @{ "自定义文本" = "测试文本内容" "自定义日期" = [DateTimeOffset]"2024-05-20" "自定义数字" = 456 "自定义开关" = $false } # 转换为Windows Runtime兼容的属性集合 $propertySet = New-Object Windows.Foundation.Collections.PropertySet foreach ($key in $propertiesToSet.Keys) { $propertySet[$key] = $propertiesToSet[$key] } # 保存属性到文件 $file.Properties.SavePropertiesAsync($propertySet).GetAwaiter().GetResult() Write-Host "自定义属性已成功设置"
注意事项
- 仅支持NTFS文件系统,FAT32等不支持自定义属性存储
- 需要文件的写入权限,非管理员用户可能需调整文件权限
- 网络共享文件需确保共享目录支持NTFS属性传递
内容的提问来源于stack exchange,提问作者HummEl
相关产品推荐
相关产品推荐

