如何将列添加到PowerShell表达式的对象/结果中?

时间:2016-07-26 13:58:24

标签: xml powershell

我有以下PowerShell命令:

dir -r packages.config | % { ([xml](Get-Content $_.FullName)).packages.package; $_.DirectoryName }

解析XML文件packages.config并为3个元素属性生成以下输出:

id                                 version        targetFramework
--                                 -------        ---------------
log4net                            2.0.0          net45          
Newtonsoft.Json                    8.0.3          net45          
protobuf-net                       2.0.0.621      net45          
C:\code\Services\TestProfile
EntityFramework                    6.1.1          net45          
log4net                            2.0.0          net45          
Newtonsoft.Json                    8.0.3          net45          
protobuf-net                       2.0.0.621      net45          
C:\code\Services\Tests

请注意,在表格输出后附加目录名称(即不是新行中的id)。

如何让目录名显示为每行的第4列,而不是每个XML表后的附加行?

像这样:

id                                 version        targetFramework  Path
--                                 -------        ---------------  ----
log4net                            2.0.0          net45            C:\code\Services\TestProfile
Newtonsoft.Json                    8.0.3          net45            C:\code\Services\TestProfile
protobuf-net                       2.0.0.621      net45            C:\code\Services\TestProfile
EntityFramework                    6.1.1          net45            C:\code\Services\Tests
log4net                            2.0.0          net45            C:\code\Services\Tests
Newtonsoft.Json                    8.0.3          net45            C:\code\Services\Tests
protobuf-net                       2.0.0.621      net45            C:\code\Services\Tests
来自packages.config的

片段,用于说明XML结构:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="log4net" version="2.0.0" targetFramework="net45" />
</packages>

1 个答案:

答案 0 :(得分:2)

Select-Object与计算属性一起使用!

Get-ChildItem -Recurse packages.config |ForEach-Object {
    $Path = $_.DirectoryName
    ([xml](Get-Content $_.FullName)).packages.package |Select-Object *,@{L='Path';E={$Path}}
}