Powershell脚本在文件中查找确切的字符串

时间:2019-01-31 08:52:09

标签: powershell

我要寻找的是有文字下面我的部署文件。任何帮助将不胜感激。

“E:\ abc.net - 分批\ TEST2”

我已经尝试过了,但是到目前为止还没有运气。

$Path = "\\servername\Test"
$Text = "E:\abc.net-Batch\test2"
$PathArray = @()
$Results = "C:\powershellscripts\test.txt"


# This code snippet gets all the files in $Path that end in ".txt".
Get-ChildItem $Path -Filter "*.bat" |
Where-Object { $_.Attributes -ne "Directory"} |
ForEach-Object {
If (Get-Content $_.FullName | Select-String -Pattern $Text) {
$PathArray += $_.FullName
$PathArray += $_.FullName
}
}
Write-Host "Contents of ArrayPath:"
$PathArray | ForEach-Object {$_}

Read-Host -Prompt "Press enter to exit"

1 个答案:

答案 0 :(得分:0)

Select-String默认返回属性Path:LineNumber:Line
因此请使用Select-Object仅使用路径,并附加-Unique参数以排除重复项。
您可以直接将Get-ChildItem的输出传递给Select-StringSelect-Object

## Q:\Test\2019\01\31\SO_54456644.ps1
$Path = "\\servername\Test"
$Text = [RegEx]::Escape("E:\abc.net-Batch\test2")
$Results = "C:\powershellscripts\test.txt"

$PathArray = Get-ChildItem $Path -Filter "*.bat" -File |
               Select-String -Pattern $Text -SimpleMatch |
                 Select-Object -Property Path -Unique

$PathArray

Read-Host -Prompt "Press enter to exit"

您必须选择以下选项之一 转义使用-SimpleMatch
 并非与上述脚本同时出现。