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 1 year has passed since last update.

PowershellでCannot index into a null arrayというエラーが出た

Posted at

背景

powershellで配列を使用してコードを作成していました。
ファイルの中身は以下の通りです。

join.ps1
@('私の出身は',$todouhuken[0],'です') -join ""

$todouhuken = @(
'tokyo'
'yamanashi'
'shizuoka'
)

実行すると以下のエラーが出ました。

Cannot index into a null array

直訳すると「null 配列にインデックスを付けることはできません。」という内容。
nullなんて使っていないぞ、、、

原因と対処法

どうやら変数で定義されていない配列を書いているのが原因のようです。先に配列を書いていないから認識されない、当たり前でした。

そこで配列の定義を前に移動させます。これで認識されるはず。。

join.ps1
$todouhuken = @(
'tokyo'
'yamanashi'
'shizuoka'
)

@('私の出身は',$todouhuken[0],'です') -join ""

実行結果が以下の通り、配列で定義した中身が出ました。0番目が一番前ですのでtokyoが表示されます。

私の出身はtokyoです

雑感

変数、配列を先に定義しないと後ろでは認識されないということを認識しました。
基本的なことですが、再度頭に入れていきたいと思います。

0
0
0

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?