10

我是 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"  

相反,它什么也不返回。

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

4

2 回答 2

12

你不会得到你期望的结果,因为Select-String输出的不是字符串,而是MatchInfo对象。如果您将第一个输出通过管道传输Select-StringGet-Memberor Format-Listcmdlet,您将得到如下内容:

PS C:\> bcdedit /枚举 | 选择字符串“标识符。*当前”-上下文 0,3 | 获取会员

   类型名称:Microsoft.PowerShell.Commands.MatchInfo

名称 MemberType 定义
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode 方法 int GetHashCode()
GetType 方法类型 GetType()
RelativePath 方法 string RelativePath(string directory)
ToString Method string ToString(), string ToString(string directory)
上下文属性 Microsoft.PowerShell.Commands.MatchInfoContext 上下文 {get;set;}
文件名 属性字符串 文件名 {get;}
IgnoreCase 属性 bool IgnoreCase {get;set;}
Line 属性字符串 Line {get;set;}
LineNumber 属性 int LineNumber {get;set;}
匹配属性 System.Text.RegularExpressions.Match[] 匹配 {get;set;}
路径属性字符串路径 {get;set;}
Pattern 属性字符串 Pattern {get;set;}

PS C:\> bcdedit /枚举 | 选择字符串“标识符。*当前”-上下文 0,3 | 格式列表 *

忽略大小写:真
行号:17
行:标识符 {current}
文件名:输入流
路径:输入流
模式:标识符。*当前
上下文:Microsoft.PowerShell.Commands.MatchInfoContext
匹配项:{标识符 {当前}

Line属性包含实际匹配的行,并且该Context属性包含具有前后上下文的子属性。由于description您要查找的行位于PostContext子属性中,因此您需要这样的东西来提取该行:

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

底线:Select-String确实工作正常。它只是不按您期望的方式工作。

于 2014-02-21T20:57:24.853 回答
4

Select-String返回MatchInfo对象,而不仅仅是显示的字符串数据。该数据取自对象的LineContext属性MatchInfo

尝试这个:

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

您将看到对象的各种属性MatchInfo

请注意,该Context属性显示为 Microsoft.PowerShell.Commands.MatchInfoContext 您需要进一步深入了解此对象以获取更多信息:

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

在那里,您将看到该context属性是另一个具有PreContextPostContext属性的对象,实际的 Pre 和 PostContext 行在其中。

所以:

(bcdedit /enum | select-string "identifier.*current" -context 0,3).Context.PostContext | Select-String 'description'

将从 postcontext 匹配中获取描述行。

或者你可以这样做:

[string](bcdedit /enum | select-string "identifier.*current" -context 0,3) -split "`n" -match 'description'
于 2014-02-21T20:59:50.993 回答