[PowerShell] CSV から XML への変換+漢字コード変換

[4/13 ??: PowerShell 1.0 ?????????????????????????????????????????????]

??????????PowerShell ???????????PowerShell ???????????????????????????????? PowerShell ???????????????????????????????

??????????????

  1. CSV ????????????? UTF-8?
  2. CSV ??????????XML ????
  3. UTF-16 ?????????

????????? CSV ???? stock-utf8.csv ???????(??????????????????????????????????????)

???,??,??
???,1000,?
???,500,?
???,100,?
??,20,?
???,3,?

1?????????????????????? PowerShell ???????????

$csv = Import-CSV f:\stock-utf8.csv

???Shift JIS ? CSV ????? Import-CSV ??????????????????? Unicode ?????????????PowerShell ??

type stock-sjis.csv > stock-unicode.csv

?????Unicode (UTF-16) ?????????????

CSV ????????????XML ????????????????????????????????CSV ?????????? XML ??????????????????????????????(?????)

$label = @{ DisplayName="???";
                   Quantity="??"; Unit="??"}

???????????????NoteProperty ?????????????????

$label = $csv | Get-Member -MemberType NoteProperty
| Select-Object Name

?????? XML ????????????????????????System.Xml.XmlDocument ??????????

$xml = New-Object xml

????XmlDeclaration ????????????????????????????????????? UTF-16 ?????????

$decl = $xml.CreateXmlDeclaration("1.0","UTF-16",$null)
[void]$xml.AppendChild($decl)

???root ??????????????Stock ????????????

$root = $xml.CreateElement("Stock")
[void]$xml.AppendChild($root)

???? Stock ?????Product ??????????

foreach ($prod in $csv){
$product = $xml.CreateElement("Product")
[void]$root.AppendChild($product)

  $label.keys | foreach {
$prop = $xml.CreateElement($_)
$prop.PSBase.InnerText = $prod.($label[$_])
[void]$product.AppendChild($prop)
}
}

????????CSV ??????? <Product></Product> ????????????????????????????????????????

??????? $label.keys ?????????$label.keys ??XML ????????????? CSV ???? $label[$_] ??????????

??????????????????XmlDocument.Save ????????????????????????????????????? XmlDocument ??????? XmlDeclaration ?????????????????????????XmlDeclaration.Encoding ???????????????????????????????????Encoding ?????????????

$xml.Save("f:\stock.xml")

??????? $xml.Save([Console]::Out) ?????????????????????????? encoding ? shift_jis ??????

?????????UTF-16 ???????????????????

image

??????PowerShell ?????????????????????????? XML ??????? .NET Framework ? XML ????????????????????????????????????????????????????????????