Using Powershell version 3 & reading the contents of a file, which I then need to see if I have one of several strings that are contained in the file and replace them if they are. The issue in my case is that one of the strings I need to match on may have a variable amount of blank spaces in it (or none at all).
The string I'm matching on has double quotes in it, which is followed by a colon (:) then whitespace (or none) and then any number of statuses (can be either alpha or numeric) followed by a comma. For simplicity, I'm just using a number in the code below.
$txt = (Get-Content $file)
$oldstr = "`"status`": 1,"
$newstr = '`"status`": 0,"
if (($txt.Contains($old1)) -or ($txt.Contains($oldstr)) -or ($txt.Contains($old2))) {
$txt.Replace($oldstr, $newstr).Replace($old1, $new1).replace($old2, $new2)| Set-Content -Path $file
}
The problem I'm having is matching the $oldstr
which may have none, one or more spaces between the colon and the status code, which in this example is a number but it may also be several different numbers or strings. The $newstr
has no need to replicate the whitespace from the $oldstr
. Also, in the above example, it is using one of three conditions in the Contains. The actual data may contain none, one, two, or all three of those strings.
How can you do the match/contains and the replace of the strings which can have whitespace in them?