The last post got me thinking about hidden files and file attributes and how we can manipulate them in PowerShell. Lets start by creating a PowerShell script.
PS> "'hello world'" > test.ps1
PS> ./test.ps1
We can see the file in a directory listing
PS> Get-ChildItem test.ps1
Directory: C:\scripts
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 30/05/2009 13:57 32 test.ps1
We can view the file attributes
PS> Get-ItemProperty -Path test.ps1 -Name Attributes
PSPath : Microsoft.PowerShell.Core\FileSystem::C:\scripts\test.ps1
PSParentPath : Microsoft.PowerShell.Core\FileSystem::C:\scripts
PSChildName : test.ps1
PSDrive : C
PSProvider : Microsoft.PowerShell.Core\FileSystem
Attributes : Archive
We can set the attributes so the file becomes hidden using the Fileattributes enumeration
PS> Set-ItemProperty -Path test.ps1 -Name Attributes -Value ([System.IO.FileAttributes]::Hidden)
as shown previously we have to use the force to get a listing
PS> Get-ChildItem test.ps1 -Force
Directory: C:\scripts
Mode LastWriteTime Length Name
---- ------------- ------ ----
---h- 30/05/2009 13:57 32 test.ps1
But we have over written the existing attributes – oops. Need to recreate the file and try again. This time we will add the attribute.
PS> Set-ItemProperty -Path test.ps1 -Name Attributes -Value ((Get-ItemProperty -Path test.ps1).Attributes -bxor [System.IO.FileAttributes]::Hidden)
and we now see the existing attributes are preserved
PS> Get-ChildItem test.ps1 -Force
Directory: C:\scripts
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a-h- 30/05/2009 14:11 32 test.ps1
We can clear all the attributes or just rest to those we require
PS> Set-ItemProperty -Path test.ps1 -Name Attributes -Value ([System.IO.FileAttributes]::Normal) -Force
PS> Get-ChildItem test.ps1 -Force
Directory: C:\scripts
Mode LastWriteTime Length Name
---- ------------- ------ ----
----- 30/05/2009 14:11 32 test.ps1
The full range of attributes can be seen
PS> [enum]::GetNames([System.IO.FileAttributes])
ReadOnly
Hidden
System
Directory
Archive
Device
Normal
Temporary
SparseFile
ReparsePoint
Compressed
Offline
NotContentIndexed
Encrypted
Normal rules still apply so we can’t compress an encrypted file