【问题标题】:Powershell get files that meet certain conditionsPowershell获取满足一定条件的文件
【发布时间】:2018-11-16 02:09:52
【问题描述】:

我正在尝试编写一个 PowerShell 脚本,如果文件包含字符串“字符串 1”并且它包含“字符串 2”,它将检索文件。我编写了以下脚本,但是它正在检索包含这两个字符串的文件。

get-childitem  -recurse -file  D:\Folder | 
where { 
Get-Content $_.FullName | Where-Object { $_ -match "string 1" -and  $_-notmatch "string 2"}
}

我怎样才能得到满足这个条件的文件?

【问题讨论】:

    标签: powershell scripting


    【解决方案1】:

    第一个解决方案(通过更改您的代码):

    (Get-ChildItem "D:\Folder\*.*") |  Where-Object {(Get-Content $_.FullName) -match "string 1" -and  (Get-Content $_.FullName) -notmatch "string 2" } | select FullName
    

    第二个解决方案(使用 Select-String):

    (Get-ChildItem "D:\Folder\*.*") | Where-Object {(Select-String -Path $_.FullName -Pattern "string 1") -and -not(Select-String -Path $_.FullName -Pattern "string 2") }| select FullName
    

    【讨论】:

      【解决方案2】:

      您需要立即对整个文件进行第二次比较。我会使用Select-String:

      Get-ChildItem -Recurse -File -Path D:\Folder | Where-Object { 
          (Select-String -Path $_.FullName "string1") -and -not(Select-String -Path $_.FullName "string2")
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-09-06
        • 1970-01-01
        • 1970-01-01
        • 2018-06-12
        • 2019-05-13
        • 2018-08-24
        • 1970-01-01
        相关资源
        最近更新 更多