Keith
Keith

Reputation: 2019

Powershell string search with wildcard and backslashes

In a file I have the following string I need to search for multiple times:

e:\\installroot\\Development2_14.07.21.000\\

The first part of the string should always be constant: "e:\\installroot\\"

But the second part of the string will change (never be the same), and I also need to search for this string and replace it with a new value: "Development2_14.07.21.000"

Here is an example of the file (reg file) that I'm trying to update:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\CompanyName\Services]
"Proc"="w:\\installroot\\Development2_14.07.21.000\\debug\\job.dll,JobServiceThread,interval;30;w:\\installroot\\Development2_14.07.21.000\\debug\\proc.exe deltasets=TEMP"
"Order"="W:\\installroot\\Development2_14.07.18.000\\debug\\order.dll,OrderThread,"
"GBatch"="NULL,ServiceThread,daily;01:10;W:\\installroot\\Development2_14.07.18.000\\debug\\file.exe"

I'm not sure if a wildcard or regex search/replace would work best here, and therefore could use some input here as to what might be the best approach. NOTE the double-backslashes.

Also, instead of updating the reg file and doing a reg import, I'd prefer to update the registry directly, so hopefully that can be done here in PowerShell.

Also NOTE: I won't always be able to use the term "Development2_" in my search scenario. At times it might be "Development_", or "Test_" or "Release_", or whatever in that path. Just something that needs to be considered.

Upvotes: 0

Views: 2862

Answers (2)

Cole9350
Cole9350

Reputation: 5560

Insert Generic Find-and-Replace script Here:

(gc C:\temp.txt) | % { 
    if($_ -like "*installroot*") {
        $_ -replace 'installroot\\.+?\\',"installroot\Development_14.07.21.111\"
    }
    else {
        $_
    }
 }| set-content C:\Temp.txt

And yes, you're right, it would be easier to just make these changes to the registry directly with powershell. You should try it, let us know how it goes...

Upvotes: 1

AlexPawlak
AlexPawlak

Reputation: 799

Why is Select-String not operating as you require?

In:

(cat .\temp.txt | Select-String -Pattern "installroot") | % { $_.ToString() | % { $_ -replace $_.Substring(17), "Some new content" } }

Out:

e:\\installroot\\Some new content\

Upvotes: 1

Related Questions