2

GUIを使用してADのユーザーを検索するためのPowerShell関数を作成しています。この関数は、ユーザーが検索を実行するためのWindowsフォームをShowDialog()し、ユーザーが[OK]をクリックするとフォームが閉じ、関数は選択したADユーザーを含むArrayListを返します。

フォームが閉じるまで、すべてが機能しています。フォームが閉じた後、私のArrayListは、選択したADユーザーを含むのではなく、突然0のカウントになります。

ArrayList($ alRetrievedSelection)が空になる理由がわかりません。私は文字通り、このArrayListを変更するコードを1行しか持っていません。他のすべては、私自身のデバッグ目的のための単なる書き込み警告です。

#This function returns an arraylist that contains the items selected by the user
function Retrieve-DataGridSelection{...}

#Fake sample data
$array = "Item 1","Item 2","Item 3","Item 4"
$arraylist = New-Object System.Collections.ArrayList(,$array)

#Create the basic form
$frmWindow = New-Object System.Windows.Forms.Form

#Create the OK button
$btnOK = New-Object System.Windows.Forms.Button
$btnOK.Add_Click({
    $alRetrievedSelection = Retrieve-DataGridSelection -dgDataGridView $datagrid
    #This warning always shows the correct Count
    Write-Warning("Received from Retrieve-DataGridSelection: " + $alRetrievedSelection.Count)
})
$frmWindow.Controls.Add($btnOK)

#Create the datagrid where users will select rows
$datagrid = New-object System.Windows.Forms.DataGridView
$datagrid.DataSource = $arraylist
$frmWindow.Controls.Add($datagrid)

#Give focus to the form
$frmWindow.Add_Shown({$frmWindow.Activate()})

#Display the form on the screen
$frmWindow.ShowDialog()

#This warning keeps telling me the Count is 0 when it should not be
Write-Warning("After the form closes: " + $alRetrievedSelection.Count)
4

1 に答える 1

0

これは、PSのスコープ規則によるものです。差出人Get-Help about_Scopes

子スコープで作成および変更する[I]temsは、アイテムの作成時にスコープを明示的に指定しない限り、親スコープに影響を与えません。

つまり、Clickハンドラースクリプトブロック(C#ラムダと同等)に変数を設定する場合、グローバルスコープではなく、そのブロックのローカルスコープにのみ変数を設定します。

グローバルスコープに変数を設定するには、globalスコープ修飾子を使用します。

$global:alRetrievedSelection = Retrieve-DataGridSelection …
于 2013-01-30T02:57:54.577 に答える