2009-01-21 22 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 
相關問題