【问题标题】:How to search a word in a file using PowerShell script如何使用 PowerShell 脚本在文件中搜索单词
【发布时间】:2016-02-20 18:38:28
【问题描述】:

我有一个包含 350 个文件夹的列表,每个文件夹都有一个文件访问日志。我需要在所有 350 个文件夹下的所有 350 个文件中搜索名称“Hound”,并在其访问日志文件中显示包含名称“Hound”的文件夹的名称。 下面是我的代码,有人可以帮我在这里添加什么以获得所需的输出吗?

   #List all the folders in C:\testfolder
   $folders = (Get-ChildItem -Path "C:\testfolder" | Where-Object{$_.Attributes -eq "Directory"} | Select Fullname)

   #looping all folders
   Foreach ($folder in $folders)
   {

   #Here I need to look for the word "Hound" inside the Access.log file and if the word is there, it should display the name of the $folder which has the word
   }

【问题讨论】:

    标签: full-text-search powershell-2.0 powershell-4.0


    【解决方案1】:

    这是一个相当基本的方法:

    Get-ChildItem -Path d:\testfolder -Recurse | Select-String -Pattern "Hound"
    

    如果您需要确保只搜索名为 access.log 的文件,请指定过滤器:

    Get-ChildItem -Path d:\testfolder -Include "access.log" -Recurse | Select-String -Pattern "Hound"
    

    【讨论】:

    • @CodeX = 您知道您可以将解决方案标记为正确(请参阅此答案左侧的勾选按钮)然后投票?这就是我们网站的运作方式,如果人们看到将答案标记为已接受的记录,他们更有可能为您提供帮助。
    • 我这样做了,但它说一旦我获得 15 个声望,那么只有我公开标记答案。
    • @CodeX - 现在试试...我给了你一个 +1
    • 完成@kev :) 非常感谢 :)
    • @Fandango68 - 不,它实际上是在文件内部搜索。文件的内容从Get-ChildItem 传送到Select-String。只是理智检查一下,因为你让我担心:)
    猜你喜欢
    • 1970-01-01
    • 2014-03-10
    • 1970-01-01
    • 1970-01-01
    • 2012-08-05
    • 2015-12-07
    • 1970-01-01
    • 1970-01-01
    • 2016-06-04
    相关资源
    最近更新 更多