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

7 months, 1 week ago.

  • Author
  • #112091

    Topics: 8
    Replies: 11
    Points: 89
    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

    Topics: 2
    Replies: 392
    Points: 667
    Helping Hand
    Rank: Major Contributor

    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

      Topics: 8
      Replies: 11
      Points: 89
      Rank: Member

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

The topic ‘Matching Part of a filename’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort