0

My code

[System.Collections.ArrayList]$Global:shells=@()
$cmdProc = Start-Process powershell -ArgumentList "-noexit", ("-command grunt "+ [string]$argList) -WorkingDirectory $fwd -PassThru
[System.Collections.ArrayList]$Global:shells.Add(($cmdProc))

does add a PowerShell process to $shells arrayList. But it also displays an error message:

cannot convert the "0" value of type "System.Int32" to type
"System.Collections.ArrayList".
At line:16 char:1
+ [System.Collections.ArrayList]$Global:shells.Add(($cmdProc))

It is definitely related to index of arrayList it adds at, but what's going on? I can access $shells[0] just fine.

2 Answers 2

3

In the last statement:

[System.Collections.ArrayList]$Global:shells.Add(($cmdProc))

PowerShell attempts to cast the output from the Add() method call (which is 0, the index you just inserted at), to an ArrayList because of the [System.Collections.ArrayList] literal in front.

Change it to:

[void]$Global:shells.Add(($cmdProc))
Sign up to request clarification or add additional context in comments.

Comments

1

In my mind, the better solution would be to set the type of your array properly, i.e.:

[System.Diagnostics.Process[]] $Global:shells = @();

try {
    $shells += Start-Process powershell <blah blah> -PassThru;
    } #try
catch [System.Exception] {
    # blah
    } #catch

...for those not familiar with PowerShell, the -passthru parameter causes the Start-Process cmdlet to return the object that it generated. This is normally done so that you can use this object to push further down the powershell "pipeline". In the case of Start-Process, it returns objects of type System.Diagnostics.Process, thus the static data type assignment.

1 Comment

Would be fine if [System.Diagnostics.Process[]] was not a static collection. I generally try to avoid the += for static arrays where I need to add staff. It actually seems somewhat unfortunate to me that powershell basic array types do not support Add(), Remove() etc. methods natively...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.