【发布时间】:2017-12-29 15:03:49
【问题描述】:
此代码在 Powershell 5+ 中运行良好,但在 Powershell 4.0 和 2.0 中无法运行:
$DaysToDelete = 2
$targets = "profile/Default",
"profile/Profile 1",
"profile/Profile 2",
"profile/Profile 3",
"profile/Profile 4"
$special = @("chromium", "64")
$profiles = Get-ChildItem "C:\" -Directory -Force |
Where-Object Name -In $special |
Select-Object -ExpandProperty FullName
$chromeDir = "C:\Users\*\AppData\Local\Google\Chrome\User Data\Default"
$chromeSetDir = "C:\Users\*\Local Settings\Application Data\Google\Chrome\User Data\Default"
$Items = @("*Archived History*",
"*Cache*",
"*Cookies*",
"*History*",
"*Top Sites*",
"*Visited Links*",
"*Web Data*")
$profiles | ForEach-Object {
foreach($target in $targets) {
$profile = Join-Path $_ $target
$items | ForEach-Object {
$item = $_
Get-ChildItem $profile, $chromeDir, $chromeSetDir -Recurse -Force -ErrorAction SilentlyContinue |
Where-Object { ($_.CreationTime -lt $(Get-Date).AddDays(-$DaysToDelete)) -and $_.Directory -like $item} | ForEach-Object {
$path = Join-Path $_.DirectoryName $_
Remove-Item $path -force -Verbose -recurse -ErrorAction SilentlyContinue }
}
}
}
我透露破坏执行的部分是
-and $_.Directory -like $item
它在 PS 5+ (Windows 10) 上运行良好,但在 PS 4 (Windows 7) 上找不到类似的模式。两台机器上的 Chrome 版本及其目录层次结构相同:59.0.3071.115 (Official Build) (64-bit).
Win10上的启动脚本,版本规范类似
powershell.exe -Version 4.0
什么也没给,它运行得很好。 我对 Powershell 版本的细节不是很流利,所以欢迎高手提出任何建议。 如何使脚本版本独立?
更新: Here is 完整代码,但它没有提供任何有价值的信息。我验证了所有的地方,并准确地定位了上面的问题线。
另一个有趣的时刻:我发现问题不在于like 子句本身,而在于like 和$_.CreationTime 的组合 检查:
$_.CreationTime -lt $(Get-Date).AddDays(-$DaysToDelete) -and $_.Directory -like $item
如果我单独设置这两个条件中的任何一个,一切正常,但如果我将它们组合成单个复合条件,则不会返回任何内容,尽管 有文件夹同时满足这两个条件。
我无法以任何方式解释这一点。
【问题讨论】:
-
要检查正在运行的 PowerShell 引擎的版本,check out this post。我怀疑你在 Windows 7 机器上运行
2.0。 -
@gms0ulman,不,在控制台中它报告
4 0 -1 -1就像在那些帖子中一样。 PS 引擎版本能否在终端和在 ISE/任务调度程序中运行脚本时有所不同? -
感谢有用的提示。是的,此添加仅适用于第二版。是的,上面的代码在 Win10 中也不适用于
-version 2.0。 -
我很难过。 AFAICS 您的代码在
4.0和5.0之间不应有所不同;$_.Directory是FileInfo的属性。不是特定于 PS 版本的。它不是DirectoryInfo的一部分;$_.Parent.Name是要走的路。抱歉,如果这是您已经知道的内容。建议:用更多描述更新您的问题/逐步查看其他地方是否存在问题。注册2.0:不支持-Directory、-in或Where的缩写形式
标签: powershell powershell-2.0 powershell-4.0 powershell-5.0