0

I am trying to populate an array based on how many csv files are in a folder. here is my code so far:

CD "\\domain\folder\file drop location"
$Array = Get-ChildItem -Filter *.csv | 
       Where-Object {-not $_.PsIsContainer} | 
       Foreach-Object {$_.Name}
$Array[0]

This returns different values depending on how many .csv files are in the folder. If only 1 csv is present then $Array[0] returns the first character of the file name (I do not want this). If there are more than one csv files then it returns the entire file name (I DO want this). How do I cause the array to accept a single file as a 1-element array?

EDIT This question can be viewed as a duplicate unless you consider that amateurs/learners who don't understand PowerShell don't know how to phrase a question. My interpretation of the problem led me to dozens of pages which answered other problems, not mine.

n8.
  • 1,732
  • 3
  • 16
  • 38

2 Answers2

2

You can cast your variable as an array when you create it, and then it will always be an array, even if there's only one result.

[array]$Array = Get-ChildItem -Filter *.csv | 
       Where-Object {-not $_.PsIsContainer} | 
       Foreach-Object {$_.Name}
TheMadTechnician
  • 34,906
  • 3
  • 42
  • 56
2

Force result type to array as @( , ( command ) )

$Array = @(, (Get-ChildItem -Filter *.csv | 
       Where-Object {-not $_.PsIsContainer} | 
       Foreach-Object {$_.Name}))

Result type would be an array even if no .csv file found (but $Array.Count would be 0 so $Array[0] raises an error).

Forcing result type to array as , ( command ) and no .csv file found then $Array.Count would be 1 and $Array[0] would be $nul:

$Array = , (Get-ChildItem -Filter *.csv | 
       Where-Object {-not $_.PsIsContainer} | 
       Foreach-Object {$_.Name})
JosefZ
  • 28,460
  • 5
  • 44
  • 83