首页 > 解决方案 > 如何使命令在同一个脚本中多次运行

问题描述

我还有一个问题,我缺乏 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
}

标签: powershelldirectory

解决方案


您只需要稍微调整您的处理,即可按目录而不是一次全部收集和处理您的文件。

$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

推荐阅读