I am running a form to allow the end user to select 1 or more files from a listing. I am using a System.Windows.Forms.CheckedListBox. In my function I define an array as such:
[System.Collections.ArrayList]$outList = @()
When the subform with the scheckedlistbox is closed (via an OK button) I r run this:
at the end of the function that calls the form, I call"
return $outList
My delema is that even though I define $outList as an array, if there is only one item in it, I get the error:
Cannot convert the “FileOnRoot.txt” value of type “System.String” to type “System.Collections.ArrayList”.
With 2 or more files, no problem… I have even tried setting the type when defining the variable ([System.Collections.ArrayList]$myArray = …)
And that’s a pretty common “gotcha” in PowerShell. You’re going to have to check and see if only one item is selected, and create an array list from it, rather than trying to assign a string directly into the empty array list. That’s just kinda how .NET rolls.
Now I believe with some output testing, the problem seems to be where I have my Return? I am instead going to pass the array as a param, but if someone wants to share with me how to do a return from a button…
I set and test the value of $outList before and after it is populated with the values from the checkboxlist. All is good. But out side of the function, the value is not changed… Why?
Ok, solved this business. I looked around and found many a reference to scope, [ref], return, write-host, and lastly $script:. The later seems to be the only one that worked for me. Funny, they all worked in quick 15 line scripts, but maybe it has to do with working in a subform and have the return come after a button press to close out the subform.
The only thing I can think of is to close the form in code where you create / show it (not from within the button on the form) - you might be closing it before returning values?