【问题标题】:add archive bit on files older than 14 days via PowerShell通过 PowerShell 在超过 14 天的文件上添加存档位
【发布时间】:2017-12-30 21:13:30
【问题描述】:

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

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

attrib +A C:\temp\*.*

【问题讨论】:

  • 对不起,我刚刚把它改成了+A :)

标签: powershell


【解决方案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)
    }
}

希望对你有帮助。

【讨论】:

  • ((Get-ItemProperty $file.fullname).attributes -BXOR $attrib) 如果存档标志已经设置,这不会取消设置吗?我的意思是,我知道你有 if 语句,但从逻辑上讲,我认为你想使用 -bor 运算符。
  • @BaconBits 否。它会切换属性,但不会就地更新文件上的值。要更改文件的属性,您需要将值分配回Attributes 属性。仅当属性一开始不存在时,代码才会这样做。
  • @BaconBits:是的,Ansgar 对此进行了正确解释。只有当第一个为空时才会切换。
  • @AnsgarWiechers 是的,正如我所说,我知道有一个 if 语句。我的观点是,就其本身而言,我从不想切换属性,因此就代码重用而言,它没有那么有价值。我想 set 位 ($_.Attributes -bor [System.IO.FileAttributes]::Archive) 或 unset 位 ($_.Attributes -band (-bnot [System.IO.FileAttributes]::Archive))。如果我的 if 语句有错误,则切换将很难检测到,因为它的行为会发生变化。这就是为什么我希望调用始终执行我想要的确切操作,例如 chmodattrib 要求。
  • @user2602460:接受答案将是可观的。
【解决方案2】:

仅过滤 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'
}

【讨论】:

  • 如果存档已设置,您确定$_.Attributes += 'Archive' 有效吗? FileAttributes.Archive + FileAttributes.Archive = FileAttributes.Device。当我测试它时,它似乎将属性设置为FileAttributes.Normal(即未设置的存档)。我更喜欢$_.Attributes = $_.Attributes -bor [System.IO.FileAttributes]::Archive
  • @BaconBits 啊,废话。我以为会,但显然+= 切换了标志。好吧,通过在Where-Object 过滤器中添加对该属性是否存在的检查,这很容易解决。感谢您的提醒。
猜你喜欢
  • 2022-08-03
  • 1970-01-01
  • 2014-09-24
  • 1970-01-01
  • 2013-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多