Matching Part of a filename


I use the following piece of code to match files in a directory from a hash table and send them onwards, based on the first 5 characters, it all works well. Where I’m stuck is how I could send the file based on the characters EF and they would have a variable length? (EF could also have the value of BB)

 $map = @{

BIGFILE_EF = "Import\test"

SMALL_EF = "Import\test1"


So I use the following code to match the first 5 characters:

$key = $file.Basename.Substring(0,5)

if ($key -in $map.Keys)

{$dstdir = Join-path -path $dstroot -childpath $map[$key]}





One quick way is to use [Math]::Min() to pick out a smaller of two values.

$TrimLength = [Math]::Min($File.Basename.Length, 5)
$key = $file.Basename.Substring(0, $TrimLength)

Alternatively, you can replace it with a simple if statement based on the length of the basename, skipping the substring entirely if it’s already short enough.

$Key = if ($File.Basename.Length -gt 5) {
else {

thanks, I’ll have a play about with that later.