Matching Part of a filename

Welcome Forums General PowerShell Q&A Matching Part of a filename

This topic contains 2 replies, has 2 voices, and was last updated by

1 month ago.

  • Author
  • #112091

    Points: 0
    Rank: Member


    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]}




  • #112093

    Points: 19
    Rank: Member

    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 {
    • #112097

      Points: 0
      Rank: Member

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

You must be logged in to reply to this topic.