残念ながら、スクリプトのプロパティをパラメーター化する方法はありません。PowerShellのソースを読むことでこれを確認できます。内部的に、スクリプトプロパティのブックキーピングはPSScriptProperty
オブジェクトに保存されます。そのようなプロパティの値が要求または変更されると、プライベート関数InvokeGetter
またはInvokeSetter
がそれぞれ呼び出されます。InvokeSetter
新しい値を唯一の引数としてセッタースクリプトブロックを実行します(この抜粋の最後の行を参照)。
SetterScript.DoInvokeReturnAsIs(
useLocalScope: true,
errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToExternalErrorPipe,
dollarUnder: AutomationNull.Value,
input: AutomationNull.Value,
scriptThis: scriptThis,
args: new object[] { value });
InvokeGetter
引数なしでゲッタースクリプトブロックを実行します。
return GetterScript.DoInvokeReturnAsIs(
useLocalScope: true,
errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.SwallowErrors,
dollarUnder: AutomationNull.Value,
input: AutomationNull.Value,
scriptThis: scriptThis,
args: Utils.EmptyArray<object>());
したがって、追加情報をゲッターまたはセッターに渡すことはできません。(プロパティを設定しているオブジェクトscriptThis
のみを参照し$this
ます。)
回避策があります:パラメーターAdd-Type
付きのコマンドレット-TypeDefinition
。インデックス可能な型を定義するC#(または必要に応じてVB.NET)コードを埋め込むことができます。
Add-Type -TypeDefinition @"
using System;
using System.Runtime.CompilerServices;
public class SomeClass {
private int[] myArray;
public SomeClass(int Capacity) {
myArray = new int[Capacity];
}
[IndexerName("ArrayData")] public int this[int index] {
get {
Console.WriteLine("Somebody asked for the element at index " + index.ToString() + "!");
return myArray[index];
}
set {
if (value < 0) throw new InvalidOperationException("Negative numbers not allowed");
if (index == 0) throw new InvalidOperationException("The first element cannot be changed");
myArray[index] = value;
}
}
}
"@
その後、次のようなことができます。
$obj = [SomeClass]::new(5)
$obj[3] = 255
Write-Host $obj[3] # Prints the "somebody accessed" notice, then 255
または、インデクサー名を利用してこれを行うことができます。
$obj.ArrayData(3) = 255 # Note the parentheses, not brackets
Write-Host $obj.ArrayData(3) # Prints the notice, then 255