Aaron Johnsen
Aaron Johnsen

Reputation: 93

Get-Child Item for Only Files Contained in Array

I'm trying to limit the return of a gci to only items contained in an array. Let's say the folder below contains several files, all named File_A, File_B, etc. up to File_Z. I only want to return the name and size of files contained in the array $myArray. Running this code as is will return all files, which is not what I want.

$MyDocuments = "C:\Documents\MyFiles"
$myArray = @()
$myArray += "File_A.txt"
$myArray += "File_B.txt"
$myArray += "File_C.txt"

cd $MyDocuments
Get-ChildItem * -Filter $myArray | Select-Object Name, Length

Upvotes: 0

Views: 931

Answers (1)

Austin T French
Austin T French

Reputation: 5131

We can also do this a little more clearly / explicitly like so:

$array = New-Object -TypeName System.Collections.Generic.List[string]
$array.Add("File_A.txt")
$array.Add("File_B.txt")
Get-ChildItem | Where-Object {$array.Contains($_.Name)}  | select Name, Length

Upvotes: 2

Related Questions