Search code examples
powershellreplaceinf

Replace text string in driver file with PS when not knowing the file path


Ok so i've tried to wrap my head around this but all i've gotten is a big headache. What i would like to do is replace specific strings of text in three driver files in two folders. Problem is that i cant give the exact path in the command because it changes and the filenames may change too. Problem is that PowerShell does not seem to play nice with wildcards (problably my fault tho). The path is for example like this:

C:\AMD\AMD_Catalyst_13.11_BetaV6\Packages\Drivers\Display\WB6A_INF\CU164159.inf

I would like to use:

C:\AMD\*\Packages\Drivers\Display\WB6A_INF\*.inf

To replace the following string ("" included):

"AMD679E.1 = "AMD Radeon HD 7800 Series"

With:

"AMD679E.1 = "AMD Radeon HD 7930"

In 3 separate .inf files and then save the changes to those files (no new files). Is it doable without an overly complex script or am i asking for too much? Btw this should also work with PS v2.0


Solution

  • The first step is to locate the file(s):

    $foundFiles = Get-ChildItem -File C:\AMD\*\Packages\Drivers\Display\WB6A_INF\*.inf
    

    then, loop through the files, read the content, and apply the replace:

    foreach ($file in $foundFiles)
    {
        $lines = Get-Content $file
        $replaced = $lines -replace '"AMD679E\.1 = "AMD Radeon HD 7800 Series"','"AMD679E.1 = "AMD Radeon HD 7930"'
        $replaced | Set-Content $file
    }
    

    Note the use of single quote in -replace, since your original string contains double quote. Also note you need to escape '.' in regex.

    You can shorten all these into one line using pipeline of course.

    Edit: fixed errors pointed by @AdiInbar