powershell 选择字符串无法正常工作

标签 powershell select-string

我是 PowerShell 的初学者,我怀疑这将是一个简单的问题。我正在尝试执行以下命令,但结果没有返回任何内容,我不明白为什么。

我正在尝试获取 bcdedit 当前部分的描述。如果我做:

bcdedit /enum | select-string "identifier.*current" -context 0,3  

它返回以下内容:
> identifier {current}  
device partition=C:  
path \WINDOWS\system32\winload.exe  
description Windows 8.1  

那么为什么以下不返回 description Windows 8.1 ?

bcdedit /enum | select-string "identifier.*current" -context 0,3 | select-string "description"  

相反,它根本不返回任何内容。

任何有关这方面的信息将不胜感激。

最佳答案

你没有得到你期望的结果,因为 Select-String不输出字符串,但 MatchInfo 对象。如果您通过管道传输第一个 Select-String 的输出进Get-MemberFormat-List cmdlet,你会得到这样的东西:

PS C:\> bcdedit /enum | Select-String "identifier.*current" -Context 0,3 | Get-Member

   TypeName: Microsoft.PowerShell.Commands.MatchInfo

Name         MemberType Definition
----         ---------- ----------
Equals       Method     bool Equals(System.Object obj)
GetHashCode  Method     int GetHashCode()
GetType      Method     type GetType()
RelativePath Method     string RelativePath(string directory)
ToString     Method     string ToString(), string ToString(string directory)
Context      Property   Microsoft.PowerShell.Commands.MatchInfoContext Context {get;set;}
Filename     Property   string Filename {get;}
IgnoreCase   Property   bool IgnoreCase {get;set;}
Line         Property   string Line {get;set;}
LineNumber   Property   int LineNumber {get;set;}
Matches      Property   System.Text.RegularExpressions.Match[] Matches {get;set;}
Path         Property   string Path {get;set;}
Pattern      Property   string Pattern {get;set;}

PS C:\> bcdedit /enum | Select-String "identifier.*current" -Context 0,3 | Format-List *

IgnoreCase : True
LineNumber : 17
Line       : identifier              {current}
Filename   : InputStream
Path       : InputStream
Pattern    : identifier.*current
Context    : Microsoft.PowerShell.Commands.MatchInfoContext
Matches    : {identifier              {current}

The Line property contains the actual matching line, and the Context property contains child properties with the pre- and post-context. Since the description line you're looking for is in the PostContext child property, you need something like this for extracting that line:

bcdedit /enum | Select-String "identifier.*current" -Context 0,3 |
  Select-Object -Expand Context |
  Select-Object -Expand PostContext |
  Select-String 'description'

底线:Select-String确实工作正常。它只是不像你期望的那样工作。

关于powershell 选择字符串无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21944643/

相关文章:

c# - .NET Framework x509Certificate2 类,HasPrivateKey == true && PrivateKey == null?

c# - 通过代码(C# 或 PowerShell)获取有关进程(如 Sysinternals Process Explorer)的 .NET 程序集信息

Powershell 脚本在写入 AWS Cloudwatch 时抛出错误 - Write-CWMetricData :

c# - 相当于 LINQ 的 Select 命令的 Powershell?

powershell - 将索引号添加到 `Select-String`的结果列表中

powershell - 将选择对象的管道对象显示为空

windows - Powershell glob 模式匹配

string - Powershell在找到另一个字符串后提取字符串

regex - 将文件中的关键字(模式)与多个文件进行匹配