繁体   English   中英

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

[英]Search directory for unique path and patterns

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

  1. PowerShell脚本-Get-ChildItem
  2. 搜索列表中的独特图案
  3. 在目录和子目录中搜索文件中的模式
  4. 使用Easy PowerShell命令在文件中搜索信息
  5. 在PowerShell中获取文件的完整路径

这是我用来在文件夹结构中重新使用的代码:

#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行:char: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

您是否有更好的方法进行相同的操作?

取代这个

$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")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM