【问题标题】:Searching for literal string with Select-String and extracting part of string使用 Select-String 搜索文字字符串并提取部分字符串
【发布时间】:2019-05-29 11:53:05
【问题描述】:

$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”有问题:

选择字符串:链式 PCI\VEN_8086&DEV_9D3A&SUBSYS_225617AA&REV_21\ 3&11583659&1&B0 n'est pas une expression régulière valide: analyze de “PCI\VEN_8086&DEV_9D3A&SUBSYS_225617AA&REV_21\3&11583659&1&B0” - 序列 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 无法识别”。

【问题讨论】:

    标签: powershell select-string


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢,忘记那个开关了!如果您也可以加入,请添加有关正则表达式的进一步问题。
    • @Rakha $null = $id -match "VEN_\w{4}&DEV_\w{4}"(如果您有更多/新的/跟进/不同的问题,请发布新问题而不是更新现有问题)
    【解决方案2】:

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

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

    【讨论】:

    • 谢谢,忘记那个开关了!如果您也可以加入,请添加有关正则表达式的进一步问题。
    【解决方案3】:

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

    比较...

    -列表

    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 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-04
      • 2021-02-21
      • 2011-07-27
      相关资源
      最近更新 更多