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

3

这似乎是一个非常简单的问题,但谷歌搜索没有给我任何结果。 以下是错误信息(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之外,还有其他设置这些扩展文件属性的[更简单]方法吗?
PS。除了[System.IO.FileAttributes] :: Temporary之外,我还想设置[System.IO.FileAttributes] :: NotContentIndexed
1个回答

6

您可以直接编辑 [FileInfo] 对象的属性。例如,如果您想要将 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)
}

在Windows Server 2012R2上,我只收到了错误消息: [System.IO.FileAttributes]不包含名为'op_Addition'的方法。 - grunge
要获取值,请使用:[system.io.fileattributes] :: Temporary.Value__ - not2qubit
当我尝试设置属性为已损坏的文件时,4227088,什么都没有改变,也没有显示错误。例如 (Get-Item -path BadAttrs.txt).Attributes=0 然后跟着 (Get-Item -path BadAttrs.txt).Attributes 显示原始值。 - User5910
关于我之前评论中提到不更改损坏属性的更新:我使用Win32 API SetFileAttributesW 时也遇到了相同的静默失败。 - User5910
如果您担心属性损坏,可以在脚本中添加检查来记录旧值,并将新值与其进行比对以确保更改。 - TheMadTechnician
这对于像加密这样的东西不起作用,因为它们似乎是由某些其他机制设置的真正只读标志。 - darda

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接