0

Using Get-ChildItem I have pulled a list of files that meet a criteria, then split a part of the Basename and want to build an array with that part of the name. I can do that successfully, except the array returns on long string. I'd like each part of the array to return on a new line.

Script:

$files = GCI "\\Paths" -Recurse | Where-Object {$_.LastWriteTime -ge (Get-Date).Adddays(-22)}

$name = ""

foreach($file in $files){
    $file = $file.basename.Split(".")[0]
        $array += $file    
}

I also tried the following with no luck:

$files = GCI "\\Paths" -Recurse | Where-Object {$_.LastWriteTime -ge (Get-Date).Adddays(-22)}
    
    $name = ""
    
    foreach($file in $files){
        $file = $file.basename.Split(".")[0]
            $array+= $file -split "`n"        
    }

Current outcome when calling $array:

file01file02file03file04

Desired outcome when calling $array:

file01    
file02    
file03 
file04
Garrett
  • 617
  • 12
  • 30

2 Answers2

4

The string is returned because $array is not an array. It is typed at assignment and its first assignment is a string. Therefore it keeps appending new values to that string.

You may do the following instead:

$array = foreach($file in $files){
    $file.basename.Split(".")[0]
}

When iterated values are output within a foreach statement, that statement output can be captured into a variable. Each value will be an element of an array.

As an aside, the += syntax to add elements to an array is inefficient because a new array is created each time after retrieving all the contents of the current array.

AdminOfThings
  • 23,946
  • 4
  • 17
  • 27
3

You're already returning an array, so just narrow it down to what you're assigning to your variable.

$files = GCI "\\Paths" -Recurse | 
    Where-Object {$_.LastWriteTime -ge (Get-Date).Adddays(-22)} | 
    ForEach-Object -Process {
        $_.basename.Split(".")[0]

    }

Or, just assign a variable to your foreach loop removing the output to an array.:

$arr = foreach (...)
Abraham Zinala
  • 4,267
  • 3
  • 9
  • 24