Jay
Jay

Reputation: 2107

PowerShell, search specific directories for specific filename

I've got a program outputting a filename to the console at the moment.

I want to give it a series of directories to search through (in order) to search through to find that filename and, if it finds it, copy to another directory.

I've got this far:

[string]$fileName = "document12**2013" #** for wildcard chars
[bool]$found = false
Get-ChildItem -Path "C:\Users\Public\Documents" -Recurse | Where-Object { !$PsIsContainer -and GetFileNameWithoutExtension($_.Name) -eq "filename" -and $found = true }

if($found = true){
Copy-Item C:\Users\Public\Documents\ c:\test
}

As it stands I've got two issues. I only know how to look through one directory, and I don't know how to specify the script to copy the particular file I've just found.

Upvotes: 1

Views: 7255

Answers (3)

Leptonator
Leptonator

Reputation: 3499

What about wrapping this into a function?

Using Shay's Approach:

function copyfile($path,$fileName,$Destination) {
Get-ChildItem -Path  $path -Recurse -Filter $fileName | 
Copy-Item -Destination $Destination
}

$path1=C:\Users\Public\Documents
$path2=C:\Users\Public\Music
$path3=C:\Users\Public\Pictures

copyfile $path1 corporate_policy.docx \\workstation\c$\users\Public\Documents
copyfile $path2 intro_from_ceo.mp3 \\workstation\c$\users\Public\Music
copyfile $path3 corporate_logo.jpg \\workstation\c$\users\Public\Pictures

Upvotes: 1

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200193

You can do all of this in one pipeline:

$folders = 'C:\path\to\folder_A', 'C:\path\to\folder_B', ...

$folders | Get-ChildItem -Recurse -Filter filename.* |
    ? { -not $_.PSIsContainer } | Copy-Item -Destination 'C:\test\'

Note that you must have a trailing backslash if you're using a folder as the destination in Copy-Item, otherwise the cmdlet will try to replace the folder C:\test with a file C:\test, which will cause an error.

Upvotes: 0

Shay Levy
Shay Levy

Reputation: 126702

The Path parameter accepts an array of paths so you can specify more than one. You use the Filter parameter to get the file name you're after and pipe the results to the Copy-Item cmdlet:

Get-ChildItem -Path C:\Users\Public\Documents,$path2,$path3 -Recurse -Filter $fileName | 
Copy-Item -Destination $Destination

Upvotes: 3

Related Questions