【问题标题】:How to make a command run multiple times in same script如何使命令在同一个脚本中多次运行
【发布时间】: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


    【解决方案1】:

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

    $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
    

    【讨论】:

      猜你喜欢
      • 2015-10-03
      • 2012-09-16
      • 2020-05-10
      • 2023-01-12
      • 2017-08-16
      • 2018-12-14
      • 1970-01-01
      • 2011-10-04
      • 1970-01-01
      相关资源
      最近更新 更多