LoginSignup
6
12

More than 5 years have passed since last update.

PowerShellの多次元配列

Posted at

PowerShellの多次元配列の要素数を可変で使えないか試してみました。

処理対象ファイル

file1.txt
a1
a2
a3
a4
file2.txt
b1
b2
b3
b4

目標とする結果

console
a1,b1
a2,b2
a3,b3
a4,b4

実際に書いたコード

ファイル読み込みやループ処理を省略してます。

sample.ps1
# 変数宣言
[string[][]]$columns = @()
[string[]]$column = @()

# file1.txtの内容を$columnに要素を追加して代入
$column += "a1"
$column += "a2"
$column += "a3"
$column += "a4"

# $columnを配列として$columnsを代入
$columns += ,@($column)

# $columnを空にする
[string[]]$column = @()

$column += "b1"
$column += "b2"
$column += "b3"
$column += "b4"

# 再度$columnを配列として$columnsを代入
$columns += ,@($column)

# 以降ファイル数分を繰り返す。

Write-Host ($columns[0][0] + "," + $columns[1][0])
Write-Host ($columns[0][1] + "," + $columns[1][1])
Write-Host ($columns[0][2] + "," + $columns[1][2])
Write-Host ($columns[0][3] + "," + $columns[1][3])

出力結果

console
a1,b1
a2,b2
a3,b3
a4,b4

ポイント

配列を代入する時はこんな書き方するみたいです。

point
$columns += ,@($column)
6
12
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
12