xlogI125’s blog

パソコン作業を効率化したい

PowerShell練習 CSVの作成

メモ

  • multidimensional array の内容を Add-Member で PSCustomObject に写して PSCustomObject の配列を ConvertTo-Csv に渡す

使い捨てスクリプト

# PowerShell 5.1, Windows 10
Set-StrictMode -Version Latest

$rowsCount = 2
$columnsCount = 3

$cells = [Object[, ]]::new($rowsCount, $columnsCount)

$cells[0, 0] = "1行1列"
$cells[0, 1] = "1行2列"
$cells[0, 2] = "1行3列"

$cells[1, 0] = "2行1列"
$cells[1, 1] = "2行2列"
$cells[1, 2] = "2行3列"

$colNames = [string[]]::new($columnsCount)

for ($i = 0; $i -lt $columnsCount; $i++) {
    $colNames[$i] = "col" + $($i + 1).ToString()
}

Write-Host $colNames
#=> col1 col2 col3

$pscObjs = [PSCustomObject[]]::new($rowsCount)

for ($i = 0; $i -lt $rowsCount; $i++) {
    $pscObjs[$i] = New-Object -TypeName PSObject

    for ($j = 0; $j -lt $columnsCount; $j++) {
        $pscObjs[$i] | Add-Member -MemberType NoteProperty -Name $colNames[$j] -Value $cells[$i, $j]
    }
}

$pscObjs | ConvertTo-Csv -NoTypeInformation | Set-Clipboard

# クリップボードの内容
# "col1","col2","col3"
# "1行1列","1行2列","1行3列"
# "2行1列","2行2列","2行3列"