Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell ArrayList turns a single array item back into a string

I have a powershell script that generates an ArrayList based on the names of the folders in a given directory. So if the directory looked like the following:

C:\Directory\One

C:\Directory\Two

C:\Directory\Three

$list is an array that contains [One, Two, Three]. The line is as follows:

[System.Collections.ArrayList]$list = (Get-ChildItem C:\Directory -dir).Name

I can then iterate through the array of strings and do various things with them. However this stops working when there is only one folder in the directory. It seems it is no longer an ArrayList and becomes just a string. I get the following error:

Cannot convert the "Directory" value of type "System.String" to type "System.Collections.ArrayList"

What can be done here? Should I be using a different kind of array type?

like image 662
Guitrum Avatar asked Jan 30 '23 05:01

Guitrum


1 Answers

You need to force the output into an array.

@((Get-ChildItem C:\Directory -dir).Name)

like image 154
Daniel Mann Avatar answered May 20 '23 12:05

Daniel Mann