powershell - 如何在不使用 attrib.exe 的情况下通过 Powershell 更改扩展的 Windows 文件属性?

标签 powershell winapi filesystems

这似乎是一个非常简单的问题,但谷歌搜索没有给我任何结果。 这是错误(PS 5.1,win 10.0.14393 x64):

Set-ItemProperty $myFileInfo -Name Attributes -Value ([System.IO.FileAttributes]::Temporary)
The attribute cannot be set because attributes are not supported. Only the following attributes can be set: Archive, Hidden, Normal, ReadOnly, or System.

attrib.exe 似乎支持大部分 System.IO.FileAttributes。不幸的是,它似乎不适用于使用 FileSystem PSDrives 引用的文件。这就是我广泛使用的。

SetFileAttributes 制作包装器内核 API 调用将是最后的手段。

我是否缺少设置这些扩展文件属性的任何其他[更简单]方法?

附言。除了 [System.IO.FileAttributes]::Temporary 我对设置 [System.IO.FileAttributes]::NotContentIndexed 很感兴趣。

最佳答案

您可以直接编辑[FileInfo] 对象的Attributes 属性。例如,如果您想将 C:\Temp 文件夹中的所有文件排除在内容索引之外,您可以这样做:

Get-ChildItem C:\Temp | ForEach{
    $_.Attributes = $_.Attributes + [System.IO.FileAttributes]::NotContentIndexed
}

这将获取每个文件,然后将 [System.IO.FileAttributes]::NotContentIndexed 属性添加到现有属性。您可能会过滤文件以确保该属性在尝试添加之前不存在,因为这可能会引发错误(我不知道,我没试过)。

编辑:如@grunge 所述,这在 Windows Server 2012 R2 中不起作用。相反,您需要做的是引用 value__ 属性,这是按位标志值,并为 NotContentIndexed 添加按位标志。这应该适用于任何 Windows 操作系统:

Get-ChildItem C:\Temp | ForEach{
    $_.Attributes = [System.IO.FileAttributes]($_.Attributes.value__ + 8192)
}

关于powershell - 如何在不使用 attrib.exe 的情况下通过 Powershell 更改扩展的 Windows 文件属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42028926/

相关文章:

powershell - PowerShell Get-Help无法识别参数注释

arrays - 无法索引到数组以将其转换为哈希表

c - 线程同步和设置线程的优先级

c - 等待单个对象 : do not lock a mutex but check the current state?

c++ - 作为服务运行时,获取 C++ 中的当前登录用户名不显示任何内容

powershell - 如何在powershell中处理失败的变量分配?

powershell - Powershell自定义对象困惑

C++目录树数据转化为 vector

php - 读取文件的元数据

linux - 完全缺少 FSTAB