2

I want to shorten this file name from '210 8th Waverly Updated Submittal (#26 0100-15.0 260100-015.00 - Short Circuit & Protective Device Coordination Study (For Rushing Review)).txt'

to '26 0100-15.0 260100-015.00 - Short Circuit & Protective Device Coordination Study.txt'

I use the pound (#) sign to clip the front, and the text '(For Rushing Review)' to clip the end.

Get-ChildItem 'c:\*Rushing*.txt' | Rename-Item -NewName {$_.BaseName.substring($_.BaseName.lastindexof('(#') + 15, $_.BaseName.IndexOf('(For Rushing Review)')-$_.BaseName.lastindexof('(#') + 15)+$_.Extension }

But I get the error Rename-Item : The input to the script block for parameter 'NewName' failed. Exception calling "Substring" with "2" argument(s): "Index and length must refer to a location within the string. Parameter name: length"

Because of the variable length of the file name, I need to use a variable for the end of the substring.

mklement0
  • 382,024
  • 64
  • 607
  • 775
markus1998
  • 23
  • 5

2 Answers2

0

Regular expressions are nice for this kind of string parsing.

Using your same logic of # at the start and (For Rushing Review) at the end, I set the new filename and extension as the two capture groups.

$Original = '210 8th Waverly Updated Submittal (#26 0100-15.0 260100-015.00 - Short Circuit & Proctective Device Coordination Study (For Rushing Review)).txt'
$Pattern = '^.+\(#(.+) \(For Rushing Review\).*(\..+)$'

$Original -Match $Pattern
$Matches[1]+$Matches[2]

Regexr link for character-by-character breakdown

OwlsSleeping
  • 1,487
  • 2
  • 11
  • 19
0

You're better off using the -replace operator to extract the substring of interest:

$baseName = '210 8th Waverly Updated Submittal (#26 0100-15.0 260100-015.00 - Short Circuit & Protective Device Coordination Study (For Rushing Review))'

($baseName -replace '^.+#([^(]+).+$', '$1').TrimEnd()

The above yields
26·0100-15.0·260100-015.00·-·Short·Circuit·&·Protective·Device·Coordination·Study,
as expected.

In the context of your command:

Get-ChildItem c:\*Rushing*.txt | Rename-Item -NewName { 
  ($_.BaseName -replace '^.+#([^(]+).+$', '$1').TrimEnd() + $_.Extension
}
mklement0
  • 382,024
  • 64
  • 607
  • 775