Thursday, March 24, 2011

How do I change a file's attribute using Powershell?

I have a Powershell script that copies files from one location to another. Once the copy is complete I want to clear the Archive attribute on the files in the source location that have been copied.

How do I clear the Archive attribute of a file using Powershell?

From stackoverflow
  • You can use the good old dos attrib command like this:

    attrib -a *.*
    

    Or to do it using Powershell you can do something like this:

    $a = get-item myfile.txt
    $a.attributes = 'Normal'
    
  • From 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;}
    }
    
  • As the Attributes is basically a bitmask field, you need to be sure clear the archive field while leaving the rest alone:

    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:\>
    
  • This might also help: http://cmschill.net/stringtheory/2008/04/bitwise-operators/

  • you may use the following command to toggel the behaviour

    PS E:\temp> $file = (gci e:\temp\test.txt) PS E:\temp> $file.attributes Archive PS E:\temp> $file.attributes = $file.Attributes -bxor ([System.IO.FileAttributes]::Archive) PS E:\temp> $file.attributes Normal PS E:\temp> $file.attributes = $file.Attributes -bxor ([System.IO.FileAttributes]::Archive) PS E:\temp> $file.attributes Archive

0 comments:

Post a Comment