Michael M. Michael M. - 1 year ago 58
PowerShell Question

Weekly replacing string from multiple files

I have to replace a certain string in multiple files every week. I was trying to simplify that process using PowerShell the line that has to be replaced is following:


other files look the same but the String is different for ex.


Is there a way to tell my script just to search for the text part in the () and replace it with a user Input? Cause I can't use hardcoded searches since next week there won't be 149 but 150 and so on.

I have been using a script to replace the whole line in a file using PowerShell for another application, but I couldn't figure out how to code it, so it only replaces the part in the brackets. PowerShell Script:

Get-ChildItem C:\Users\mosermich\Desktop\Extractor\Ressources -Filter '*.sql' -ErrorAction Stop | ForEach-Object {
$content = Get-Content $_.Fullname
$content[7] = ' rel.nr sqlldr {0}' -f $releasenr
$content | Set-Content -Path $_.FullName

And here is one of the files that in which I would need to replace the number in the () on line 2:


Answer Source

I would use a regex with a positive lookahead and lookbehind:

$userInput = 250
$filePath = 'yourFilePath'

$content = Get-Content $filePath
$content -replace '(?<=\()(\d+)(?=\))', $userInput | Set-Content $filePath



Regular expression visualization

Edit: Here the script adopted to your example:

$userInput = 250 # The number you want to put in the parentheses
Get-ChildItem C:\Users\mosermich\Desktop\Extractor\Ressources -Filter '*.sql' -ErrorAction Stop | 
    ForEach-Object {
        $content = Get-Content $_.Fullname
        $content -replace '(?<=\()(\d+)(?=\))', $userInput | Set-Content $_.Fullname