首页 > 解决方案 > 在 Powershell 中使用 Select-String 方法获取字符串

问题描述

我有很多这样的文本文件,下面是一个此类文件的示例。这是文件 File_Content12 的一部分。

name:duplicate1-content:philips -sequence:primary...........
name:guard1-content:sony -sequence:primary...........
name:Linux-content:sony -sequence:third...........
name:Windows-content:IPS -sequence:secondary...........
name:Notebook-content:Mark -sequence:fourth...........
name:duplicate1-content:Tony -sequence:primary...........

当内容是索尼时,我正在编写一个 powershell 代码来获取名称 duplicate1。

我编写了下面的代码,它会获取有关文件中存在哪些内容、行号以及行的信息。

$contents = 'sony','Philips'
ForEach ($ct in $contents)
{
    Get-Childitem -Path "D:\Input\Files\" | Select-String -Pattern "$ct" | Select Filename,LineNumber,Line,@{n='Content';e={$ct}}
}

当内容是索尼时,我被困在这部分以获得名称 duplicate1。我是否需要使用 IndexOf 和 Substring 来获取值,或者是否有任何其他方式来获取此名称。

标签: powershellselect-string

解决方案


Select-String使用正则表达式,所以duplicate.*sony应该做你需要的

$contents = 'duplicate.*sony','Philips'
ForEach ($ct in $contents)
{
    Get-Childitem -Path "D:\Input\Files\" | Select-String -Pattern "$ct" | Select Filename,LineNumber,Line,@{n='Content';e={$ct}}
}

运行Get-Help about_Regular_Expressions以获取更多详细信息


推荐阅读