2017-01-20 13 views
0

あらかじめ必ずしも存在していないグローバルアレイリストに項目を追加します。それは私がエラーを取得する未定義だ場合、それが動作グローバルarrayListが関数内に存在するかどうかを確認し、存在しない場合はadd + addを実行できますか?

You cannot call a method on a null-valued expression. 
At line:14 char:1 
+ [System.Collections.ArrayList]$Global:shells.Add(($cmdProc)) 

が、私は何とかそれが$Global:shellsを作成することはできます - $Global:shells ArrayListのは、関数呼び出しの前にグローバルに定義されて

function runGrunt ($fwd="./projectFolder", [email protected]()) 
{ 
$cmdProc=start-process powershell -ArgumentList "-noexit",("-command grunt "+ [string]$argList) -WorkingDirectory $fwd -PassThru 
[System.Collections.ArrayList]$Global:shells.Add(($cmdProc)) 
} 

場合:ここで私がしようとしているものですarrayListがまだ存在しない場合は、それに項目を追加します。それはarrayListとして$nullをキャストしようとしているようですが、明らかに失敗します。私はGet-Variable shells -Scope globalを使うことができますが、ブール値ではなくオブジェクトを取得します。isEmpty()メソッドまたはそれ以外のものがないため、変換する方法が分かりません。

+1

'if(-not(テストパス変数:\ shells)){$ global:shells = New-Object System.Collections.ArrayList}' –

答えて

0

グローバル変数オブジェクトがnullであるかどうかをチェックし、必要に応じて作成します。また、PowerShellの型固有のメソッドを呼び出すたびに正しい型であることを確認することを忘れないでください。

function runGrunt ($fwd="./projectFolder", [email protected]()) 
{ 
    $cmdProc=start-process powershell -ArgumentList "-noexit",("-command grunt "+ [string]$argList) -WorkingDirectory $fwd -PassThru 

    if($null -eq $global:shells) # note that $global:shells -eq $null would not work due to the way how comparison operator work in PowerShell 
    { 
     $global:shells = New-Object System.Collections.ArrayList 
    } 
    elseif($global:shells.GetType() -eq [System.Collections.ArrayList] 
    { 
     $global:shells.Add(($cmdProc)) 
    } 
    else 
    { 
     Write-Error "Global variable 'shells' is not of expected type System.Collections.ArrayList. Type is: $($global:shells.GetType())" 
    } 
} 
関連する問題