Skip to content

Instantly share code, notes, and snippets.

@csandfeld
Last active May 2, 2016 10:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save csandfeld/42f4ca41773cae4575ab5d41b0457ac2 to your computer and use it in GitHub Desktop.
Save csandfeld/42f4ca41773cae4575ab5d41b0457ac2 to your computer and use it in GitHub Desktop.
Working with file attributes
$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 }
$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