1
1

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 5 years have passed since last update.

PowerShell: function の返り値に配列を使う際の TIPS

Posted at

function の返り値に配列を指定しても、思い通りにならない事例

返り値は空配列・その1

 function func1
 {
     $Response = @()
     $Response
 }

 $r = func1
 write-host $r.GetType()
 write-host $r.Length
null 値の式ではメソッドを呼び出せません。 発生場所 行:32 文字:1 + write-host $r.GetType() + ~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) []、RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull 0

返り値は空配列・その2

 function func2
 {
     $Response = @()
     ,$Response
 }

 $r = func2
 write-host $r.GetType()
 write-host $r.Length

System.Object[]
0

返り値は配列で、要素は 1 つだけ・その1

 function func3
 {
     $Response = @("abc")
     $Response
 }

 $r = func3
 write-host $r.GetType()
 write-host $r.Length

System.String
3

返り値は配列で、要素は 1 つだけ・その2

 function func4
 {
     $Response = @("abc")
     ,$Response
 }

 $r = func4
 write-host $r.GetType()
 write-host $r.Length

System.Object[]
1

まとめると

function を呼びだした側が受け取ったものは…

返り値の記述 コンマ無し コンマ有
function 内での配列長
0 $null @()
1 "abc" @("abc")
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?