Powershell:从xml文件中读取值

时间:2010-03-22 14:59:52

标签: powershell

我需要一些有关PowerShell的帮助。这应该很简单:

我有一个子目录列表,每个子目录都有一个xml文件。我想打开每个xml文件并打印一个节点的值。节点始终相同,因为xml文件实际上是Visual Studio中的项目文件(* .csproj)。

我已经获得了文件列表:get-item ** \ * .csproj

我该如何处理?

1 个答案:

答案 0 :(得分:6)

要获取csproj文件,请使用Get-ChildItem

Get-ChildItem c:\myProjects *.csproj -recurse

然后你可以使用例如Select-Xml喜欢这样:

$ns = @{ defaultNamespace = "http://schemas.microsoft.com/developer/msbuild/2003" }
Get-ChildItem c:\myProjects *.csproj -recurse | 
   Select-Xml -xpath '//defaultNamespace:PropertyGroup[1]' -namespace $ns | 
   Select-Object -expand Node

您必须更正默认命名空间。我现在手边没有csproj文件。
(有关PowerShell中xml和xpath的详细信息,请参阅http://huddledmasses.org/xpath-and-namespaces-in-powershell/

扩展实际节点属性需要Select-Object

如果你想像对象一样使用xml,你可以使用它:

Get-ChildItem c:\myProjects *.csproj -recurse | 
   % { $content = [xml](gc $_.FullName); $content.Project.PropertyGroup[someindex...] }