【发布时间】:2021-09-13 23:39:48
【问题描述】:
我还有一个问题,我在 PowerShell 方面缺乏经验,这让我很困惑。我想知道是否可以调整我的脚本以允许从不同的源文件夹多次运行命令。
例如,我希望它在 C:\temp\test 和 C:\temp\test2 中运行。我已经尝试将它写成以 $path= C:\temp\test','C:\temp\test2' 运行,但这只是返回了不稳定的假设删除结果(一个文件夹内容被完全删除,但其他人没有)。
如果有人能解释如何在同一个脚本中的多个不同文件夹中运行此命令,那将非常感激,因为我即将把头发拉出来,说明它是多么简单,但它是多么困难;P
有效但只有一个目的地的脚本:
$path = "C:\temp\test"
$files = Get-ChildItem -Path $path
$keep = 2
if ($files.Count -gt $keep) {
$files | Sort-Object CreationTime |
Select-Object -First ($files.Count - $keep) |
Remove-Item -Force -Recurse -WhatIf
}
我尝试使用多个文件夹但结果不佳的脚本:
$path = "C:\temp\test","C:\temp\test2","C:\temp\test3"
$files = Get-ChildItem -Path $path
$keep = 2
if ($files.Count -gt $keep) {
$files | Sort-Object CreationTime |
Select-Object -First ($files.Count - $keep) |
Remove-Item -Force -Recurse -WhatIf
}
【问题讨论】:
标签: powershell directory