0

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

TMRW
  • 107
  • 3

1 Answers1

2

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

X.J
  • 662
  • 3
  • 6
  • 1
    A couple of notes: 1. Only the first argument to **-replace** is a regex. The `.` shouldn't be escaped in the replacement string, because that will add a literal `\ ` to the replacement text. 2. Be careful of re-encoding the file (unless you don't care). **Out-File** uses UTF16 by default, whereas **Set-Content** uses the system default (typically ASCII). By using **Out-File**, you're probably converting an ASCII file to UTF16. Both cmdlets have an **-Encoding** parameter to specify which encoding you want (use "Unicode" for UTF16, because Microsoft decided to be silly about that). – Adi Inbar Nov 12 '13 at 22:30
  • (BTW, before anyone gets me on a technicality...yes, I realize that technically it's ANSI Code Page 1252, not ASCII, but I thought it would be more widely understood this way, especially since you specify it as "ASCII" in the argument to the **-Encoding** parameter.) – Adi Inbar Nov 12 '13 at 22:38
  • 1
    BTW, here's a compact one-line version of the above: `gci | %{sc $_ ((gc $_) -replace '"AMD679E\.1 = "AMD Radeon HD 7800 Series"','"AMD679E.1 = "AMD Radeon HD 7930"')}` (I just love PowerShell!) – Adi Inbar Nov 13 '13 at 02:43
  • Hmm somthing is wrong here. Im getting access to the path is denied errors. The files are not modified yet the last modified date changes. – TMRW Nov 13 '13 at 13:40