Sunday, February 13, 2011

Powershell - search folder hierarchy for names matching a pattern from a file and copy them.


So I had a request this week for a quick script that could search a folder structure for filenames for patterns that matched strings inside of a text file and then copy them to another folder. All the files had long complicated filenames so they needed an easy way to search through them. If it was *nix I'd just use Perl but since it was for Windows Powershell's the right way to go.

the text file contained strings like
00xy569e
TRs3002010
00xy589f
00xy589s

# Gnawgnu - 2/2011
# Searches filenames in a folder structure for
# patterns provided via text file

# Files to be Searched.
$srcFolder = "D:\filestobesearched"

# Destination of file copy.
$dest = "d:\CopyMatchesHere"

# List of patterns to look for.
$srcFile = "d:\matchlist.txt"

# Read in matchlist from text file.
$matchlist = Get-Content $srcFile
foreach ($match in $matchlist) {
$a = gci -r -i *$match* $srcFolder
foreach ($c in $a) {
# Change to move-item if needed
copy-item $c $dest
}
}


No comments: