Michael M. Michael M. - 3 months ago 11
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:

extract_mdp_staging_error(149);


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

extract_kdp_staging(149);
extract_zub_staging_error(149);
...


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.

EDIT
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:

begin
extract_zdlb_staging(149);
commit;
end;
/
quit;

Answer

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

Regex:

(?<=\()(\d+)(?=\))

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
    }