2009-01-21 25 views
19

我有一个Powershell脚本将文件从一个位置复制到另一个位置。复制完成后,我想清除源位置中已复制的文件上的归档属性。如何使用Powershell更改文件属性?

如何使用Powershell清除文件的存档属性?

+0

这也可能有帮助:http://cmschill.net/stringtheory/2008/04/bitwise-操作员/ **编辑**:现在链接正在返回404的可能来自archive.org的答案: https://web.archive.org/web/20100105052819/http://cmschill.net/stringtheory/2008/ 04 /按位运算符/。 – 2009-01-22 00:00:04

回答

11

here

function Get-FileAttribute{ 
    param($file,$attribute) 
    $val = [System.IO.FileAttributes]$attribute; 
    if((gci $file -force).Attributes -band $val -eq $val){$true;} else { $false; } 
} 


function Set-FileAttribute{ 
    param($file,$attribute) 
    $file =(gci $file -force); 
    $file.Attributes = $file.Attributes -bor ([System.IO.FileAttributes]$attribute).value__; 
    if($?){$true;} else {$false;} 
} 
26

您可以使用像这样的好老的DOS ATTRIB命令:

attrib -a *.* 

还是做它使用PowerShell,你可以做这样的事情:

$a = get-item myfile.txt 
$a.attributes = 'Normal' 
7

由于属性基本上是一个位掩码字段,您需要确保清除存档字段同时保留其余:

 
PS C:\> $f = get-item C:\Archives.pst 
PS C:\> $f.Attributes 
Archive, NotContentIndexed 
PS C:\> $f.Attributes = $f.Attributes -band (-bnot [System.IO.FileAttributes]::Archive) 
PS C:\> $f.Attributes 
NotContentIndexed 
PS H:\> 
0

您可以使用下面的命令来切换行为

$file = (gci e:\temp\test.txt) 
$file.attributes 
Archive 

$file.attributes = $file.Attributes -bxor ([System.IO.FileAttributes]::Archive) 
$file.attributes 
Normal 

$file.attributes = $file.Attributes -bxor ([System.IO.FileAttributes]::Archive) 
$file.attributes 
Archive 
1
$attr = [System.IO.FileAttributes]$attrString 
$prop = Get-ItemProperty -Path $pathString 
# SetAttr 
$prop.Attributes = $prop.Attributes -bor $attr 
# ToggleAttr 
$prop.Attributes = $prop.Attributes -bxor $attr 
# HasAttr 
$hasAttr = ($prop.Attributes -band $attr) -eq $attr 
# ClearAttr 
if ($hasAttr) { $prop.Attributes -bxor $attr } 
1

米奇的答案适用于大多数的属性,但对于will not work“压缩”。如果你想使用PowerShell来设置文件夹的压缩属性,你必须使用命令行工具compact

compact /C /S c:\MyDirectory 
相关问题