1

I have two string arrays in my PowerShell script:

$search = @('File1', 'File2');
$paths = @('C:\Foo\File1.pdf', 'C:\Foo\Bar.doc', 'C:\Foo\File2.txt');

How can I get all file paths which contain the file names from the search array? Can this be done in a pipeline?

2 Answers 2

3

You could use the GetFileNameWithoutExtension method to retrieve the filename of the path and use -in to filter them:

$paths | ? { [System.IO.Path]::GetFileNameWithoutExtension($_) -in $search }
Sign up to request clarification or add additional context in comments.

Comments

1

If you need to do partial matches you could do something like this:

$paths | Where-Object {
  $filename = Split-Path $_ -Leaf
  $search | Where-Object { $filename -like "*$_*" }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.