如何限制Get-ChildItem搜索的文件(或限制递归深度)?

时间:2013-02-07 00:15:39

标签: powershell filter powershell-v1.0 get-childitem

背景

有一个目录全天自动填充MSI文件。我计划利用任务计划程序每15分钟运行下面显示的脚本。该脚本将搜索目录并将过去15分钟内创建的所有新MSI复制到网络共享。

在此文件夹C:\ProgramData\flx\Output\<APP-NAME>\_<TIME_STAMP>\<APP-NAME>\中,还有另外两个文件夹:RepackagedMSI Package。不需要搜索Repackaged文件夹,因为它不包含任何MSI。此外,我发现需要以某种方式排除它以防止此错误:

Get-ChildItem : The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.
At line:14 char:32
+$listofFiles=(Get-ChildItem <<<< -Recurse -Path $outputPath -Include "*.msi" -Exclude "*.Context.msi" | where {$_.LastAccessTime -gt $time.AddMinutes($minutes)})
+ CategoryInfo : ReadError: C:\ProgramData\...xcellence\Leg 1:String) [Get-ChildItem], PathTooLongException
+ FullyQualifiedErrorId : DirIOError,Microsoft.PowerShell.Commands.GetChildItemCommand

限制

  • 我被困在使用Powershell v1.0
  • 我无法控制源位置的目录结构

更新

  • 我不知道应用名称或时间戳是什么。这是我无法控制的其他事情。

当前计划

我已经阅读了有关使用-Filter的内容,并且我知道过滤器与功能类似,但我无法提出任何有关如何使用它们的想法。我现在唯一的想法就是做一些事情:

$searchList=Get-ChildItem "all instances of the MSI Package folder"

foreach($folder in $searchList){
    $listofFiles=Get-ChildItem "search for *.msi"

    foreach($file in $listofFiles){"Logic to copy MSI from source to destination"}
}

然而......我认为可能有更有效的方法来做到这一点。

问题

  1. 如何限制Get-ChildItem搜索的深度?
  2. 如何将Get-ChildItem搜索限制为C:\ProgramData\flx\Output\<APP-NAME>_<TIME_STAMP>\<APP-NAME>\MSI Package
  3. 如何搜索过去15分钟内访问过的文件夹?当我知道MSI已被复制时,我不想浪费时间钻进文件夹。
  4. 关于如何使这个脚本更有效率的任何其他建议也将非常感激。

    脚本

    我的当前脚本可以找到here。我一直得到:“您的帖子似乎包含未正确格式化为代码的代码”,并在第四次尝试重新格式化后放弃了。

3 个答案:

答案 0 :(得分:1)

你可以试试这个

dir C:\ProgramData\flx\Output\*\*\*\*\* -filter *.msi 

此搜索此级别的所有.msi个文件

C:\ProgramData\flx\Output\<APP-NAME>\_<TIME_STAMP>\<APP-NAME>\Repackaged or 'MSI Package' or whatever else present folder

没有递归,这避免了太深的文件夹,导致错误。

将结果传递给:

Where {$_.LastAccessTime -gt (Get-Date).AddMinutes(-15)} #be sure no action on file is taken before the dir command

Where {$_.LastWriteTime -gt (Get-Date).AddMinutes(-15)} #some file can be re-copied maybe

答案 1 :(得分:1)

在C.B.的帮助下,这是我的新搜索,它消除了我遇到的问题。

  • -Path更改为C:\ProgramData\flx\Output\*\*\*\*以帮助限制搜索到的深度。
  • 使用-Filter代替-Include并将-Exclude逻辑放入where子句。

Get-ChildItem -Path C:\ProgramData\flx\Output\*\*\*\* -Filter "*.msi" | where {$_.Name -notlike "*.Context.msi" -and $_.LastAccessTime -gt (Get-Date).AddMinutes(-15)}

答案 2 :(得分:0)

除了不使用-Recurse,Get-ChildItem深度= 0或N.

为应用名称和时间戳设置变量,例如:

$appName = "foo" 
$timestamp = Get-date -Format HHmmss
Get-ChildItem "C:\ProgramData\flx\Output\${appName}_$timestamp\$appName\MSI Package" -force -r

您可以像这样过滤结果:

Get-ChildItem <path> -R | Where {$_.LastWriteTime -gt (Get-Date).AddMinutes(-15)}