Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all articles
Browse latest Browse all 6937

PowerShell and RegEx

$
0
0

Hello - I  have been trying to figure out how to insert a variable in the regex -replace statement and cannot figure out to get it to work.  This is my code - any help is greatly appreciated.

I have a variable defined that is called $wordToFind.  I want to use that variable in the matching portion of the -replace regex statement.  So, if it find that word/username then I want it to replace the password in the webconfig file.  I have another variable called $wordToReplace that will contain the new password and I figured out how to use that variable in the replace portion of the -replace statement by escaping the capture groups with a tick (`).....but what is the correct syntax to use for the variable $wordToFind in my code below.  Nothing I have tried seems to work. (I have bolded the area I am talking about in the code below)

 

$directoryToTarget="r:\test"
$wordToFind="FinanceReportUser;"
$wordToReplace='testpass" '

Clear-Content log.txt

Get-ChildItem -Path $directoryToTarget -Filter *.config -Recurse | where { !$_.PSIsContainer } | % {

$file = Get-Content $_.FullName
$containsWord = $file | %{$_ -match $wordToFind}
If($containsWord -contains $true)
{
    Add-Content log.txt $_.FullName
 
    ($file) | ForEach-Object { $_ -replace '(?i)(^|.*;)(user id=.*;)$wordToFind(password=)(.*")(\sproviderName=.*$)' , "`$1`$2`$3$wordToReplace`$5" }  |
     Set-Content $_.FullName
}

}

 

Thank you so much for any help.

 


Viewing all articles
Browse latest Browse all 6937

Trending Articles