通过PowerShell在14天以上的文件中添加存档位

时间:2017-12-30 21:13:30

标签: powershell

我正在尝试设置PowerShell脚本,该脚本会将存档位添加到特定文件夹中超过+14天的所有文件,例如C:\Temp

这可以通过CMD实现,但如何设法仅将+a位添加到超过+14天的文件中?

attrib +A C:\temp\*.*

2 个答案:

答案 0 :(得分:1)

首先检查属性是否存在,然后根据条件设置。 要切换存档位,可以使用按位独占或(BXOR)运算符。

您可以这样做:

$path = "C:\foldername"
$files = Get-ChildItem -Path "C:\folderpath" -Recurse -force | where {($_.LastwriteTime -lt  (Get-Date).AddDays(-14) ) -and (! $_.PSIsContainer)} 
$attrib = [io.fileattributes]::archive
Foreach($file in $files)
{
    If((Get-ItemProperty -Path $file.fullname).attributes -band $attrib)
    {
    "Attribute is present"
    }
    else
    {
    Set-ItemProperty -Path $file.fullname -Name attributes -Value ((Get-ItemProperty $file.fullname).attributes -BXOR $attrib)
    }
}

希望它有所帮助。

答案 1 :(得分:-1)

只需过滤14天以上的文件,然后将“存档”添加到其属性中:

$threshold = (Get-Date).Date.AddDays(-14)

Get-ChildItem 'C:\Temp' | Where-Object {
    -not $_.PSIsContainer -and
    $_.LastWriteTime -lt $threshold -and
    -not ($_.Attributes -band [IO.FileAttributes]::Archive)
} | ForEach-Object {
    $_.Attributes += 'Archive'
}