2010-03-22 149 views
4

我需要一些PowerShell帮助。它应该很容易:Powershell:从xml文件读取值

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

我已经得到的文件列表:获得项目** \ * .csproj的

我该如何继续?

回答

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文件。
(有关XML和XPath在PowerShell中的详细信息请参见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...] }