Search code examples
powershellmatchpowershell-3.0

Powershell number notation matches and rename-item logic


In the below solution for renaming files taken from an answer to my question Rename-Item error, what do the following bits of code do?

  1. ^\d{4}
  2. e={$Matches[1]}
  3. Rename-item -Newname {"{0:D4} - sp - C - {1}" -f ++$Count.Value,$_.Name}

For 1. I think this is saying a four digit number but I would like to understand the notation used.

For 2. $Matches hasn't been set anywhere, is this a variable specific to Select-Object?

For 3. what is {0:D4} doing and the {1} at the end of the same string. Also, is this line concatenating two strings with the comma delimiter?

$Count = [Ref][math]::Max(1000,
    [int](Get-ChildItem -Path $Folder -Filter *.sql -File|
            Where-Object Name -match '^(\d{4}) - sp - C -' | 
            Select-Object @{n='Count';e={$Matches[1]}} -Last 1).Count)

Get-ChildItem -Path $Folder -Filter *.sql -File |
  Where-Object Name -NotMatch '^\d{4} - sp - C - ' | 
    Rename-item -Newname {"{0:D4} - sp - C - {1}" -f ++$Count.Value,$_.Name}

Solution

    1. ^\d{4} is a Regular Expression
      ^ anchors at line begin
      \d represents a digit
      {4} is a quantifier, specifying exactly 4 of the previous, here digits
      () parentheses mark a capture group

    2. cite from Get-Help about_Comparison_Operators

      The -Match and -NotMatch operators populate the $Matches automatic variable.

      Where $Matches[1] represents the 1st capture group of the RegEx.
      The Select-Object builds a calculated property from the match (4 digit number) and only uses the last/highest

    3. Obtaining the previously used highest number was a bonus I should have explained better 1st place.
      As the obtained number now contains 4 digits (no more a fixed 1 and three zeroes) the -format operator (shorted to just -f) is used to build the new file name by inserting variable contents in place of the {x} where x is a zero based number.