0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

powershellで配列を拡張していくときの注意点

Posted at

powershellで配列に要素を追加していくとき、以下のような書き方があります。

$array += $newitem

これは実際のところ、値渡しではなく参照渡しで要素を追加しているようです。そのため、以下のようなループで要素を追加すると想定しない結果が得られます。

ng.ps1
$data=@("hoge","fuga")
$body=@()
$item = @{}
foreach($d in $data){
    $item["data"] = $d
    $body += $item
}

$body
PS > ./ng.ps1

Name                           Value
----                           -----
data                           fuga
data                           fuga

PS >

配列body内のdataが全てfugaになっています。一つ目のdataはhogeが代入されたはずでしたが、最終的には全てfugaになりました。おそらく、キーdataにfugaが代入されたitemを二つとも参照しているものと思われます。
これを防ぐには、foreach内で都度itemを初期化する必要があります。

ok.ps1
$data=@("hoge","fuga")
$body=@()

foreach($d in $data){
    $item = @{}
    $item["data"] = $d
    $body += $item
}

$body
> ./ok.ps1

Name                           Value
----                           -----
data                           hoge
data                           fuga

PS />
0
0
2

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?