Shell – Elegent way to set variables in .ini files

powershellsql-server-2012

I'm currently trying to script the installation of Microsoft Sql Server 2012, and I've run into a problem with letting the user set options for the installation process in my powershell script

Because sql server's options are set in an .ini file, I'm not sure what the best way to edit said .ini file is. I could see myself

  • Copying the whole .ini file in powershell and setting variables within the quotes to write it out later, or
  • saving the ini file separately and searching for each line I need to set variables as a string to edit separately.

Is there any more elegant way to work with .ini files than this?
Is there any "find and replace" powershell module for files that I could use?

Best Answer

Treat the .ini as a text file. Say we have the following .ini:

[section1]
var1=foo1
[section2]
var2=foo2
var3=foo3

To change the value assigned to "var2", we can do:

(get-content .\test.ini).Replace('foo2','bar2') | Set-Content .\test.ini

Where "bar2" is the user defined value. To incorporate the user defined value, you could do:

$ini = ".\test.ini"
$userInput = Read-Host -Prompt "Enter a new value for var2"
(get-content $ini).Replace('foo2',$userInput) | Set-Content $ini

The way you choose to design how you handle the replace will rely on the data in your particular file.

Related Question