将标签分隔的数据输出到文本文件

时间:2014-03-12 13:00:40

标签: powershell format output

我有一堆xml文件,在每个文件中都可能有多个变种(不同的语言区域代码en-us,en-ca,en-gb等)我是PowerShell的新手,所以我很可能不了解几个概念。

我能够提取所有这些信息,但我无法以我想要的格式输出它。我尝试使用Out-File并调查Export-Csv,但我无法让它按照我的意愿行事。任何帮助将不胜感激。

这是我想要的格式(内容将被复制到Excel中)

File Path  |  ar-ae  |  ar-sa  |  cs-cz  |  da-dk
File 1         X        X                 X
File 2         X        X        X        X
File 3                  X         

所以基本上我想要一个表格,其中标题是文件路径和每个语言代码。然后,我想列出所有文件,并在文件中存在的每个区域设置下放置一个X.

这是我的代码

if (Test-Path ".\siteIA.txt") {
Clear-Content ".\siteIA.txt"
}

$locales = @(
"ar-ae"
"ar-sa"
"cs-cz"
"da-dk"
"de-at"
"de-ch"
"de-de"
"el-gr"
"en-au"
"en-ca"
"en-gb"
"en-hk"
"en-ie"
"en-in"
"en-nz"
"en-sg"
"en-us"
"en-za"
"es-ar"
"es-cl"
"es-co"
"es-es"
"es-mx"
"fi-fi"
"fr-be"
"fr-ca"
"fr-ch"
"fr-fr"
"he-il"
"hu-hu"
"it-it"
"ja-jp"
"ko-kr"
"nb-no"
"nl-be"
"nl-nl"
"pl-pl"
"pt-br"
"pt-pt"
"ru-ru"
"sk-sk"
"sv-se"
"tr-tr"
"zh-hk"
"zh-tw"
)

$locales = $locales | sort

$header = "Path`t" + $locales

Get-ChildItem C:\Users\tests *.xml -recurse | 
% { 
    $outArray = @()
    $file = [xml](Get-Content $_.fullname)

    $path = $file.ExportedContentItem.path
    $name = $file.ExportedContentItem.name
    $availableLocales=@()

    $out = $path + "/" + $name + "`t"

    $file.ExportedContentItem.ContentItem.Variant | % { 
        $availableLocales += $_.variantCulture
    }

    $availableLocales = $availableLocales | sort

    foreach ($locale in $locales){
        if ($availableLocales -contains $locale){
            $out = "X"
            Add-Content ".\siteIA.txt" "X`t"
        } else {
            $out = ""
            Add-Content ".\siteIA.txt" "`t"
        }       
    }

    Add-Content ".\siteIA.txt" "T"
    Add-Content ".\siteIA.txt" "E"
    Add-Content ".\siteIA.txt" "S"

}

1 个答案:

答案 0 :(得分:1)

如果您想稍后将输出导入Excel,最好只创建一个TSV(制表符分隔值)文件。 Export-Csv cmdlet可以为您执行此操作。

使用File Path创建自定义对象并将locales作为属性,并将名称在Variant节点中列出的所有属性设置为X。然后使用制表符作为分隔符导出对象:

Get-ChildItem C:\Users\tests *.xml -recurse | % {
  $contentItem = [xml](Get-Content $_.FullName).ExportedContentItem

  $o = New-Object -Type PSObject -Property @{
    'File Path' = Join-Path $contentItem.Path $contentItem.Name
    'ar-ae'     = ''
    'ar-sa'     = ''
    ...
    'zh-hk'     = ''
    'zh-tw'     = ''
  }

  $contentItem.ContentItem.Variant | % {
    $o."$($_.variantCulture)" = "X"
  }

  $o
} | Export-Csv 'C:\path\to\output.txt' -NoType -Delimiter "`t"