【问题标题】:Powershell to search for files based on words / phrase but also Zip files and within zip filesPowershell 根据单词/短语搜索文件,还可以搜索 Zip 文件和 zip 文件中的文件
【发布时间】:2014-02-18 03:41:05
【问题描述】:

我有这个脚本...

查看给定的网络位置,然后遍历所有文件夹/子文件夹以搜索特定的单词/短语。希望修改以能够对 ZIP 文件执行相同的操作。以相同的方式工作,报告包含所列出的单词的所有 ZIP 文件以及 ZIP 中的任何文件...

有什么帮助吗?

"`n" 
write-Host "Search Running" -ForegroundColor Red
$filePath = "\\fileserver\mydepts\IT"
"`n" 

Get-ChildItem -Recurse -Force $filePath -ErrorAction SilentlyContinue | Where-Object { ($_.PSIsContainer -eq $false) -and  ( $_.Name -like "*test*" -or $_.Name -like "*bingo*" -or $_.Name -like "*false*" -or $_.Name -like "*one two*" -or $_.Name -like "*england*") } | Select-Object Name,Directory,CreationTime,LastAccessTime,LastWriteTime | Export-Csv "C:\scripts\searches\csv\results.csv" -notype

write-Host "------------END of Result--------------------" -ForegroundColor Green

【问题讨论】:

    标签: powershell scripting


    【解决方案1】:

    您无法扫描 zip 文件的内容,因为它已被压缩并且会以垃圾的形式出现。您必须解压缩文件然后搜索它。

    按照以下说明操作:http://www.howtogeek.com/tips/how-to-extract-zip-files-using-powershell/

    复制到本地,然后在那里搜索,然后删除副本,重复。

    【讨论】:

      【解决方案2】:

      如果您安装了 .Net 4.5,您可以使用 System.IO.Compression.FileSystem 库来创建一个函数,该函数将打开和遍历 zip 文件的内容

      $searchTerms = @( "test","bingo","false","one two","england")
      function openZip($zipFile){
          try{
              [Reflection.Assembly]::LoadWithPartialName( "System.IO.Compression.FileSystem" ) | Out-Null;
              $zipContens = [System.IO.Compression.ZipFile]::OpenRead($zipFile);  
              $zipContens.Entries | % {
                  foreach($searchTerm in $searchTerms){
                      if ($_.Name -imatch $searchTerm){
                          Write-Output ($_.Name + "," + $_.FullName + "," + $_.CompressedLength + "," + $_.LastWriteTime + "," + $_.Length);
                      }
                  }               
              }
          }
          catch{
              Write-Output ("There was an error:" + $_.Exception.Message);
          }
      }  
      

      然后你可以运行这样的东西来获取文件名、zip 中的完整路径、压缩大小等。

      Get-ChildItem -Path -$filePath *.zip -Recurse -ErrorAction SilentlyContinue | %  {
          openZip $_.FullName  >> c:\path\to\report.csv
          }
      

      【讨论】:

      • 我可以将它添加到我上面的脚本中吗?我还是个PS菜鸟!看起来不错,谢谢你的帮助。
      • 没问题,只需将 c:\path\to\report.csv 修改为您想要输出的位置即可。
      • 很乐意提供帮助,如果我的解决方案对您有用,请确保您接受答案;)
      猜你喜欢
      • 2011-11-14
      • 1970-01-01
      • 1970-01-01
      • 2020-03-22
      • 1970-01-01
      • 2011-05-15
      • 2014-11-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多