Working with file attributes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$Path = 'C:\TEMP\TEST1' | |
$Filter = '*.pdf' | |
$Attribute = [System.IO.FileAttributes]::Archive | |
# Get all files in $Path matching $Filter | |
Get-ChildItem -Path $Path -Filter $Filter -Recurse | |
# Get all files in $Path matching $Filter where $Attribute is set | |
Get-ChildItem -Path $Path -Filter $Filter -Recurse | Where-Object { $_.Attributes -band $Attribute } | |
# Get all files in $Path matching $Filter where $Attribute is NOT set | |
Get-ChildItem -Path $Path -Filter $Filter -Recurse | Where-Object { ($_.Attributes -band $Attribute) -ne $Attribute } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$Path = 'C:\TEMP\TEST1' | |
$Filter = '*.pdf' | |
$Attribute = [System.IO.FileAttributes]::Archive | |
function Set-FileAttribute { | |
[CmdletBinding()] | |
Param( | |
[Parameter(Mandatory = $true, ValueFromPipeline = $true)] | |
[System.IO.FileInfo[]] | |
$InputObject | |
, | |
[Parameter(Mandatory = $true)] | |
[ValidateNotNullOrEmpty()] | |
[ValidateSet('Archive', 'Hidden', 'Normal', 'ReadOnly', 'System')] | |
[System.String[]] | |
$Attribute | |
, | |
[Parameter(Mandatory = $true)] | |
[ValidateSet('Disable','Enable','Toggle')] | |
[System.String] | |
$Action | |
, | |
[Switch] | |
$PassThru = $false | |
) | |
process { | |
foreach ($Object in $InputObject) | |
{ | |
foreach ($Attrib in $Attribute) { | |
$FileAttribute = [System.IO.FileAttributes]::$Attrib | |
Switch ($Action) { | |
'Disable' { $ScriptBlock = { ($Object.Attributes -band (0xffffffff -bxor $FileAttribute)) } } | |
'Enable' { $ScriptBlock = { ($Object.Attributes -bor $FileAttribute) } } | |
'Toggle' { $ScriptBlock = { ($Object.Attributes -bxor $FileAttribute) } } | |
} | |
$Object.Attributes = &$ScriptBlock | |
} | |
if ($PassThru) { | |
return $Object | |
} | |
} | |
} | |
} | |
# Set attribute | |
Get-ChildItem -Path $Path -Filter $Filter | Set-FileAttribute -Attribute $Attribute -Action Enable -PassThru | |
# Remove attribute | |
Get-ChildItem -Path $Path -Filter $Filter | Set-FileAttribute -Attribute $Attribute -Action Disable -PassThru | |
# Toggle attribute | |
Get-ChildItem -Path $Path -Filter $Filter | Set-FileAttribute -Attribute $Attribute -Action Toggle -PassThru |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment