The -replace
operator offers several placeholders to refer to what the regex matched in the substitution operand; $&
refers to the entirety of the match[1], and can be used here:
PS> '00469-101236-01-V-3-20-001' -replace '...$', '$& $&'
00469-101236-01-V-3-20-001 001
Instead of '...$'
, you could also do '.{3}$'
Note that $&
expands to '001'
, i.e. the last 3 chars. The reason that the start of the filename - everything before the last 3 chars., '00469-101236-01-V-3-20-'
- is also present is that -replace
only replaces the matching part of the input string.
In the context of your command:
Get-ChildItem -Recurse | Rename-Item -NewName {
($_.BaseName -replace '...$', '$& $&') + $_.Extension
} -Whatif
Note: The -WhatIf
common parameter in the command above previews the operation. Remove -WhatIf
once you're sure the operation will do what you want.
[1] You can alternatively use $0
instead of $&
, even though only $&
is directly documented; $0
is modeled on $<n>
, where <n>
refers to the index of a capture group inside the regex ((...)
), starting with 1
($1
).
That $0
works like $&
can be inferred from the documentation of the underlying Regex
type: "If the regular expression engine can find a match, the first element of the GroupCollection object (the element at index 0
) returned by the Groups
property contains a string that matches the entire regular expression pattern" - thanks, marsze.
This helpful regex documentation site contrasts the behavior of various regex engines.