搜索目录中的唯一路径和模式

时间:2017-03-21 21:03:46

标签: powershell

我正在尝试搜索目录结构,以及存在模式的所有实例的文件。我希望该文件位置记录在日志文件中,我可以查看后者。我查看了各种帖子,但我没有找到类似的例子。已审核的帖子包括:

  1. PowerShell Scripting - Get-ChildItem
  2. Search List for unique pattern
  3. Search directory and sub-directories for pattern in a file
  4. Use an Easy PowerShell Command to Search Files for Information
  5. Get full path of the files in PowerShell
  6. 以下是我用来回避文件夹结构的代码:

    #Set variables for paths
    $Results = "C:\Results"
    $Source = "C:\Test\*"
    $Destination = "C:\MyTest\"
    
    #Create file name for each report with date and time of run
    $ReportDate = (Get-Date).ToString("dd-MM-yyyy-hh-mm-ss")
    
    $CustomPattern = Read-Host 'What pattern are you looing for?'
    $CustomPatternLog = New-Item -itemType File -Path C:\Results -Name $("CustomerPattern_" + $ReportDate + ".txt")
    $CustomPattern = foreach ($file in Get-ChildItem -Path $Destination -Recurse | Select-String -pattern $CustomPattern | Select-Object -Unique Path) {$file.path}
    $CustomPattern > "$($Results)\$($CustomPatternLog)"
    

    但是,此代码返回以下错误:

      

    Get-ChildItem:指定的路径,文件名或两者都太长。   完全限定的文件名必须少于260个字符,并且   目录名称必须少于248个字符。在线:19   焦炭:36   + $ CustomPattern = foreach(Get-ChildItem中的$ file -Path $ Destination -Recurse | S ...   + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~       + CategoryInfo:ReadError:(C:\ Test \ Mor ... ofiles \ Customer:St ring)[Get-ChildItem],   PathTooLongException       + FullyQualifiedErrorId:DirIOError,Microsoft.PowerShell.Commands.GetChil dItemCommand

    你有更好的方法做同样的操作吗?

1 个答案:

答案 0 :(得分:2)

替换此

$CustomPatternLog = New-Item -itemType File -Path C:\Results -Name $("CustomerPattern_" + $ReportDate + ".txt")
$CustomPattern = foreach ($file in Get-ChildItem -Path $Destination -Recurse | Select-String -pattern $CustomPattern | Select-Object -Unique Path) {$file.path}
$CustomPattern > "$($Results)\$($CustomPatternLog)"

用这个

$files = Get-ChildItem -Path $Destination -Recurse

#in case you would need the path replace FullName with PsParentPath
$result = ($files | ?{$_.name -like "*$CustomPattern*"}).FullName 
$result | out-file ($CustomPattern + "_" + $ReportDate + ".txt")

并且因为它的外壳你可以用一个衬垫

做同样的事情
(Get-ChildItem -Path $Destination -Recurse | ?{$_.name -like "*$CustomPattern*"}).FullName | out-file ($CustomPattern + "_" + $ReportDate + ".txt")