2

Go easy on me, first time posting.

I'm trying to use Powershell to Get-Content from an INI file. Particularly, I need to change two separate lines in the file. It runs, but instead of just replacing those 2 lines, it duplicates everything. It also doesn't replace the line I'm trying to tell it to replace, but instead it just adds my new line leaving the original in as well.

$FilePath = "C:\Users\folder\*.ini"

(Get-Content $FilePath) |
ForEach-Object { 
    $_ -replace "MailBell=0","MailBell=1"
    $_ -replace "MailWindow=0","MailWindow=1"
    } |
Set-Content $FilePath

There is a look at the code. Any help is greatly appreciated.

  • This article has some good tips in it might meet your needs: https://stackoverflow.com/questions/417798/ini-file-parsing-in-powershell – Thom Schumacher Mar 20 '18 at 16:14
  • You're running a replace twice. Put both `-replace` on the same line and it should be fine: `$_ -replace 'etc','etc1' -replace 'etc2', 'etc3'` – Maximilian Burszley Mar 20 '18 at 16:18
  • Although you're not using regex, so I'd use the string replace method instead: `$_.Replace('MailBell=0','MailBell=1').Replace('MailWindow=0','MailWindow=1'` – Maximilian Burszley Mar 20 '18 at 16:18
  • @TheIncorrigible1 Thank you. It's a little better now; however, instead of duplicating each line in sequence, it's taking the whole block of text and duplicating it twice. In other words, all the content of the ini file is being entered in below the original content twice...if that makes sense. – iTechThingsSeriously Mar 20 '18 at 17:54
  • Use `-Raw` on your `Get-Content` call and instead of `ForEach-Object`, just attach the `.Replace()` chain from my comment above. – Maximilian Burszley Mar 20 '18 at 17:55
  • @TheIncorrigible1 I'm sorry. I'm very new at this. Is this what you mean? `(Get-Content -Raw $FilePath) | $_.Replace('MailBell=0','MailBell=1').Replace('MailWindow=0','MailWindow=1') | Set-Content $FilePath` – iTechThingsSeriously Mar 20 '18 at 18:04
  • @TheIncorrigible1 I got that working based on your recommendations. I was on a computer that had version 2 installed saw the RAW command was confusing me until I found out it wasn't supported in ver 2. My source folder was also tripping me up because I was using an additional wildcard that I didn't believe to be relevant to this post....it was. The only other odd thing is that when it runs I get the addition of a blank space at the end of the file after each run iteration. I'm not sure why that is. – iTechThingsSeriously Mar 20 '18 at 21:12

0 Answers0