Guitrum
Guitrum

Reputation: 191

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?

Upvotes: 5

Views: 4793

Answers (2)

Shawn Esterman
Shawn Esterman

Reputation: 2342

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 @().

Upvotes: 0

Daniel Mann
Daniel Mann

Reputation: 59016

You need to force the output into an array.

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

Upvotes: 8

Related Questions