How can I store one result from a Get-ChildItem as one array value?
It's not a good practice to use format-list
for handling data. format-list
is for visualizing output.
Instead, you should tell your variable that it definetly is an array, even if it has only one value. You can do that by casting it to a [string[]]
or by wrapping your entire command into @()
which makes it an array even before it's stored in the variable.
See the difference here:
Your way works if there is more than one return, since then it automatically is an array. However it does not work if there is only a single return, since PowerShell thinks you want your Variable to be a string, because you don't specifically tell it that you want it to be an array:
PS C:\Install\mydir> $Dirlist = gci . | ? { $_.PSIsContainer } | sort CreationTime | select -ExpandProperty Name
PS C:\Install\mydir> $Dirlist[0..3]
M
y
F
o
You can cast it to an array and it will work:
PS C:\Install\mydir> [string[]]$Dirlist = gci . | ? { $_.PSIsContainer } | sort CreationTime | select -ExpandProperty Name
PS C:\Install\mydir> $Dirlist[0..3]
MyFolder-2021-11-22
Or wrap the entire command in @()
:
PS C:\Install\mydir> $Dirlist = @(gci . | ? { $_.PSIsContainer } | sort CreationTime | select -ExpandProperty Name)
PS C:\Install\mydir> $Dirlist[0..3]
MyFolder-2021-11-22
btw. instead of
| select -Property Name | foreach { $_.Name }
just use
| select -ExpandProperty Name
I just added a format-list (ft is the short version) in the end and it worked for me:
$Dirlist= gci $LBDestination | ? { $_.PSIsContainer } | sort CreationTime | select -Property Name | foreach { $_.Name } | fl