"select-string"
greps
过滤文本。有没有办法与PowerShell实现相同的事情或类似的方法?这是我根据要求使用的文件:
<?xml version="1.0" encoding="UTF-8"?>
<CustomObject xmlns="http://soap.force.com/2006/04/metadata">
<actionOverrides>
<actionName>Accept</actionName>
<type>Default</type>
</actionOverrides>
<actionOverrides>
<actionName>CancelEdit</actionName>
<type>Default</type>
</actionOverrides>
<actionOverrides>
<actionName>Today</actionName>
<type>Default</type>
</actionOverrides>
<actionOverrides>
<actionName>View</actionName>
<type>Default</type>
</actionOverrides>
<compactLayoutAssignment>SYSTEM</compactLayoutAssignment>
<enableFeeds>false</enableFeeds>
<fields>
<fullName>ActivityDate</fullName>
</fields>
<fields>
<fullName>ActivityDateTime</fullName>
</fields>
<fields>
<fullName>Guid</fullName>
</fields>
<fields>
<fullName>Description</fullName>
</fields>
</CustomObject>
,我只想要
<fullName>
描述符之间的文本,到目前为止,我有以下内容:get-content "txtfile.txt" | select-string -Pattern '<fields>' -Context 1
这将为我提供
<fields>
描述符之间的所有内容,但是我从本质上需要<fullName>
线,而无需XML标签。
最简单的
PSV3+解决方案是touse powerShell的内置XML DOM支持,它使XML文档的nodes可以作为对象的nodes of对象的范围访问,并具有
::::
PS> ([xml] (Get-Content -Raw txtfile.txt)).CustomObject.fields.fullName
ActivityDate
ActivityDateTime
Guid
Description
注:即使解析XML文档的方法是concenient,但在字符编码方面,它并不完全可靠;请参阅this Answer.
[xml] (Get-Content -Raw ...)
是
array-代表顶级元素的所有子元
.fields
-<fields>
-<CustomObject>
直接应用于它并返回了子元素的值.fullName
所有数组元素(
<fullName>
元素)作为array。
能够访问汇总的属性并将其隐式应用于该集合的
元的能力,结果被收集在
array中,是一个通用的psv3+功能,称为Member-access-access enumumeration。 作为As Antertantive,请考虑使用
<field>
cmdlet(也可以在psv2中使用),它通常允许使用更复杂的提取逻辑logic(尽管在这里并不严格需要) ; Select-Xml
是围绕Select-Xml
.NET类型的高级包装器
[xml]
以下是上述解决方案的等效物:
.SelectNodes()
注:
$namespaces = @{ ns="http://soap.force.com/2006/04/metadata" }
$xpathQuery = '/ns:CustomObject/ns:fields/ns:fullName'
(Select-Xml -LiteralPath txtfile.txt $xpathQuery -Namespace $namespaces).Node.InnerText
时必须考虑xmlnamesp,如下:
civen,所有的后代都处于命名空间Select-Xml
,通过uri
<CustomObject>
确定,您必须:在hashtable中定义此命名空间您通过
xmlns
:默认名称空间是特殊的,因为它可以用作Hashtable中的密钥;取而代之的是,选择一个arbitrary关键名称,例如http://soap.force.com/2006/04/metadata
,但请确保将所选的密钥名称用作node-name前缀(请参阅下一点)。theprefix xpath查询中的所有节点名称带有名称名称,然后是
-Namespace
;例如,
xmlns
ns
,我们可以再次将其传递给:
。 这一切都可以在一行上完成,但我使用一个变量来使其更可读。
ns:CustomObject
Select-String
到Out-String -Stream
,我们会发现一些有趣的属性。
Select-String
这将显示所有实例$Match = Get-Content "atxtfile.txt" | Select-String -Pattern '<fields>' -Context 1
$Match | Out-String -Stream | Select-String -Pattern "Guid"
(模式匹配)。
$match
Get-Member
$Match.Matches.Value