【发布时间】:2017-12-30 21:13:30
【问题描述】:
我正在尝试设置一个 PowerShell 脚本,该脚本将为特定文件夹中所有早于 +14 天的文件添加一个存档位,例如 C:\Temp。
这可以通过 CMD 实现,但我如何设法仅将 +a 位添加到超过 +14 天的文件?
attrib +A C:\temp\*.*
【问题讨论】:
-
对不起,我刚刚把它改成了+A :)
标签: powershell
我正在尝试设置一个 PowerShell 脚本,该脚本将为特定文件夹中所有早于 +14 天的文件添加一个存档位,例如 C:\Temp。
这可以通过 CMD 实现,但我如何设法仅将 +a 位添加到超过 +14 天的文件?
attrib +A C:\temp\*.*
【问题讨论】:
标签: powershell
首先检查该属性是否存在,然后您可以根据条件进行设置。 要切换存档位,您可以使用 按位异或 (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 运算符。
Attributes 属性。仅当属性一开始不存在时,代码才会这样做。
$_.Attributes -bor [System.IO.FileAttributes]::Archive) 或 unset 位 ($_.Attributes -band (-bnot [System.IO.FileAttributes]::Archive))。如果我的 if 语句有错误,则切换将很难检测到,因为它的行为会发生变化。这就是为什么我希望调用始终执行我想要的确切操作,例如 chmod 和 attrib 要求。
仅过滤 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。
+= 切换了标志。好吧,通过在Where-Object 过滤器中添加对该属性是否存在的检查,这很容易解决。感谢您的提醒。