powershell - 如何使命令在同一个脚本中多次运行
问题描述
我还有一个问题,我缺乏 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
}
解决方案
您只需要稍微调整您的处理,即可按目录而不是一次全部收集和处理您的文件。
$path = "C:\temp\test","C:\temp\test2","C:\temp\test3"
$keep = 2
ForEach ($Dir in $Path) {
#*** Get files for current Path, i.e. $Dir ***
$files = Get-ChildItem -Path $path -File
#*** Process the files found ***
if ($files.Count -gt $keep) {
$files | Sort-Object CreationTime |
Select-Object -First ($files.Count - $keep) |
Remove-Item -Force -Recurse -WhatIf
}
} #End ForEach
推荐阅读
- java - 客户端查找服务器时出现 NotBoundException
- sql - 需要在 SQL Server 2016 中创建周期性问题报告
- xcode - 创建应该在真实设备和模拟器上都可以使用的 .ipa 文件
- javascript - 当我点击 npm run dev 和 npm run serve 命令时遇到问题
- google-cloud-platform - 在 GCP 上使用 SSH 访问 JupyterLab 还不起作用
- python - 按特定顺序从目录打开文件
- javascript - 从 TypeScript 操作 JSON
- web-scraping - 如何以外部用户身份从应用 PowerBI 获取数据
- wordpress - 如何将存储在数据库中的联系表格 7 值链接到特定用户 - Wordpress
- mysql - 你如何改变mysql中的哈希算法?