4

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?

Guitrum
  • 171
  • 1
  • 10

2 Answers2

8

You need to force the output into an array.

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

Daniel Mann
  • 57,011
  • 13
  • 100
  • 120
0

If you want to use an ArrayList, the constructor is just expecting an Array or another ArrayList. You can build off what @DanielMann said and do something like this:

New-Item -Path C:\TestDirectory\SubDirectory -Force | Out-Null # Creates one folder in C:\TestDirectory
[System.Collections.ArrayList] $ArrayList = @((Get-ChildItem C:\TestDirectory -Directory).Name)
Write-Host "Total directories: $($ArrayList.Count)"
Remove-Item -Path C:\TestDirectory -Recurse

As you can see, I am just wrapping the output of (Get-ChildItem).Name in an array @().

Shawn Esterman
  • 2,292
  • 1
  • 10
  • 15