'powershell regex replace using variable parameters when calling replace
I wondering how to make the following powershell code work with regular expressions. For example I want to call it like this:
rename_file -OneFile proj1_file.txt -Replace0 "^proj1_" -Replace1 "mynewproj_"
The problem is that as soon as I add the regular expression caret (^) my function stops matching for the replace function... If I remove the caret anchor the code works... but is dangerous because its not anchored to the front of the string... I really want the regular expressions chracters to work when passing the string in to this function...
Here's my powershell code...
$script:TotalRename = 0
function rename_file {
param(
[string]$OneFile,
[string]$Replace0,
[string]$Replace1
)
#$NewName = $OneFile.Replace($Replace0, $Replace1)
$NewName = $OneFile -replace $Replace0, $Replace1
if ($NewName -eq $OneFile) {
write-host "NoChange $OneFile"
return
}
$script:TotalRename = $script:TotalRename + 1
write-host "rename $OneFile => $NewName"
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
