我是 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-Member
或 Format-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/