使用Select-String搜索文字字符串并提取部分字符串

时间:2019-05-29 11:53:06

标签: powershell select-string

$DeviceID的值为:"PCI\VEN_8086&DEV_9D3A&SUBSYS_225617AA&REV_21\3&11583659&1&B0"

我正在尝试使用“ Select-String”在.INF文件中搜索该字符串:

 Select-String -Path C:\file.inf -Pattern "$DeviceID"

但是它不会按原样使用字符串,它的“ \ V”有问题:

Select-String : La chaîne PCI\VEN_8086&DEV_9D3A&SUBSYS_225617AA&REV_21\
3&11583659&1&B0 n’est pas une expression régulière valide: analyse de
"PCI\VEN_8086&DEV_9D3A&SUBSYS_225617AA&REV_21\3&11583659&1&B0" - Séquence
d'échappement \V non reconnue.
Au caractère Ligne:15 : 5
+     Select-String -Path $($_.FullName) -pattern "$($erreur.DeviceID)"
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument : (:) [Select-String], ArgumentException
    + FullyQualifiedErrorId : InvalidRegex,Microsoft.PowerShell.Commands.SelectStringCommand

对不起法语,但它基本上说“字符串不是有效的正则表达式。转义序列\ V无法识别”。

3 个答案:

答案 0 :(得分:1)

Select-String默认情况下使用.NET正则表达式引擎。要进行简单的字符串匹配,请使用-SimpleMatch开关参数:

Select-String -Path C:\file.inf -pattern "$DeviceID" -SimpleMatch

答案 1 :(得分:1)

PowerShell尝试进行正则表达式匹配。添加 -SimpleMatch 开关,以在$ DeviceID中查找不带正则表达式的文字字符串。

Select-String -Path C:\file.inf -Pattern $DeviceID -SimpleMatch

答案 2 :(得分:1)

我看到您已经有了答案,但是还有另一个开关也可以做到这一点。

为了进行比较...

-列表

select-string -path "$TargeUNC\*.ps1" -Pattern 'Get-WmiObject' -list | 
Select-Object -First 3

# Results

2018-01-15 Enable the Disk Cleanup tool on Windows Server.ps1:45:$wmiOS = Get-WmiObject -Class Win32_OperatingSystem
3D_chart.ps1:1:get-wmiobject win32_perfformatteddata_perfdisk_logicaldisk
7 cmdlet Hyper-V Tips.ps1:15:$vm = Get-WmiObject -Namespace root\virtualization\v2 -Class 

-vs -SimpleMatch

select-string -path "$TargeUNC\*.ps1" -Pattern 'Get-WmiObject' -SimpleMatch | 
Select-Object -First 3

# Results

2018-01-15 Enable the Disk Cleanup tool on Windows Server.ps1:45:$wmiOS = Get-WmiObject -Class Win32_OperatingSystem
3D_chart.ps1:1:get-wmiobject win32_perfformatteddata_perfdisk_logicaldisk
7 cmdlet Hyper-V Tips.ps1:15:$vm = Get-WmiObject -Namespace root\virtualization\v2 -Class