Search code examples
powershellget-childitem

Get-ChildItem using multiple paths, and retrieve all files that matches and their path - only the server name


I build a script that retrieve all files form specific paths that match a name, and also the path that the files are in.

I want only to get the file name and the server name (Server-1, Server-2 etc..), and not all the path (\Server-1\test\Desktop\ etc..).

How can I do it?

Thank you

This is the script that I have so far:

$filename= Read-Host "Please Enter The file Name Or Part Of It"
$path="\\SERVER-1\test\Desktop\test"
$path2="\\SERVER-2\test\Desktop\test"
$path3="\\SERVER-3\test\Desktop\test"


foreach($path in $path){
Get-ChildItem -Path $path,$path2,$path3 | Where-Object {$_.Name -like "*$filename*"} | Format-List Name -GroupBy DirectoryName
}

Solution

  • Since Get-ChildItem can take an array of paths, there is no need for a foreach loop.

    Here's one aproach:

    $filename = Read-Host "Please Enter The file Name Or Part Of It"
    $paths = '\\SERVER-1\test\Desktop\test', '\\SERVER-2\test\Desktop\test', '\\SERVER-3\test\Desktop\test'
    Get-ChildItem -Path $paths -Filter "*$filename*" -File | 
    Select-Object @{Name = 'Server'; Expression = {$_.DirectoryName.Trim("\").Split("\")[0]}}, Name