【问题标题】:PowerShell - Export to Excel - How to Add Column for File NamePowerShell - 导出到 Excel - 如何为文件名添加列
【发布时间】:2022-10-24 14:11:23
【问题描述】:

我的代码当前通过文件夹/子目录列表查找“.csproj”文件。属性“包含”和“版本”取自找到的 .csproj 文件并导出到 Excel 工作表。虽然这可行,并且我确实为每个属性获得了两列,但我还需要显示每个 excel 行条目所属的文件的名称。我一直无法找到解决此问题的方法。所以在我最后的 Excel 表中,我需要 3 行:Include、Version、NameOfTheFile。

通过故障排除,我在“Select-Object -Property Include, Version”行之后添加了“$xml.name”,这在每批属性之间的 Excel 表中添加了空格。这有点帮助,但文件的名称就足够了。

$Directory = Get-ChildItem C:\Repos\Common\Caching\src -Directory
$ErrorFiles = [System.Collections.Generic.List[string]]::new()

$result = foreach ($d in $Directory) {
    Write-Host "Working on directory $($d.FullName)..."
    $folders = Get-ChildItem -Path $d.FullName -File -Recurse -Filter *.csproj
    foreach($folder in $folders) {
        try {
            $xml = [xml](Get-Content $folder.FullName -Raw)
            $xml.SelectNodes("/Project/ItemGroup/PackageReference") |
            Select-Object -Property Include, Version
            $xml.Name
            
        }
        catch {
            Write-Warning $_.Exception.Message
            $ErrorFiles.Add($folder.FullName)
        }
    }
}

$result | Export-Excel -Path C:\Temp\ExampleExcel.xlsx -AutoSize -AutoFilter

【问题讨论】:

    标签: excel xml powershell xml-attribute


    【解决方案1】:

    您可以将计算属性与 Select-Object 一起使用,您需要做的唯一更改是:

    $xml.SelectNodes("/Project/ItemGroup/PackageReference") |
    Select-Object -Property Include, Version
    $xml.Name
    

    为了这:

    $xml.SelectNodes("/Project/ItemGroup/PackageReference") |
    Select-Object -Property Include, Version, @{
        Name = 'NameOfTheFile'
        Expression = { $folder.Name } # => this is a file though
    }
    

    【讨论】:

      猜你喜欢
      • 2016-03-29
      • 2021-10-02
      • 1970-01-01
      • 2021-07-21
      • 2021-09-13
      • 2023-04-05
      • 1970-01-01
      • 2017-03-08
      相关资源
      最近更新 更多