1

I need to get the name of the last file that was copied and then increment by one to get the next file. The files follow the pattern DDMM###.TXT where ### will start with 000 and end with 005 for the day. I know I can use substring to get the ###, and then increment by 1, and then used replace to replace the ### with the new incremented "string". I was just wondering if there was a more elegant way to do this.

    $value = $filetotransfer.substring(4,3)
    $newvalue = ([int]$value+1).ToString('000')
    $filetotransfer = $filetotransfer.Replace($value,$newvalue)

Where $filetotransfer can be mmdd000.txt to mmdd005.txt depending on the time of the day.

user2073183
  • 141
  • 1
  • 3
  • 13

1 Answers1

0
  • If you're using PowerShell (Core) 7+:

    # -> '0506001.txt'
    '0506000.txt' -replace '(?<=^\d{4})...', { '{0:000}' -f (1 + $_.Value) }
    
  • In Windows PowerShell, the -replace operator doesn't support script blocks ({ ... }) as the replacement operand, which makes the solution more complex, because a direct call to the underlying .NET API is required:

    # -> '0506001.txt'
    [regex]::Replace('0506000.txt', '(?<=^\d{4})...', { param($m) '{0:000}' -f (1 + $m.Value) })
    

For an explanation of these techniques, see this answer.

mklement0
  • 382,024
  • 64
  • 607
  • 775