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で参照渡しされたものをさらに参照渡しする方法

Posted at

参照渡しの仕方は検索するとすぐわかるのですが、それをさらに参照渡しする方法がわからなかったので、試した結果です。

まずは単なる参照渡し

おさらい的に、単なる参照渡しです。 「([ref]$変数名)」で渡します。
次の通りです。

function test1([ref] $param){
    $param.value = "abc";
}

function main(){
    $variable = "";
    test1 ([ref]$variable);
    Write-Host $variable;
}

これで、mainを実行すると、abc が表示されます。

参照渡しされたものをさらに参照渡し

では、test1からさらに別の関数、たとえばtest2に渡す場合はどうなるでしょうか?

渡された側でvalueプロパティから代入してるということは、渡されたものを渡す場合は、valueプロパティを渡すのかもしれないなと考えて、
([ref]$param) なのか ([ref]$param.value) なのか悩みましたが、試した結果、どちらでもありませんでした。 意外でしたので、他にも同じことを悩んでいる方がいらっしゃるかもしれないと思い、共有の投稿です。

結論としては、$param をそのまま渡すでした。 

以下が正解例となります。

function test2([ref] $param){
    $param.value = "abc";
}

function test1([ref] $param){
    test2 $param;
}

function main(){
    $variable = "";
    test1 ([ref]$variable);
    Write-Host $variable;
}

main

これで、mainを実行すると、abc が表示されます。

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?