There are a ton of great answers here! I came here looking for the same answer you were. While looking at the answers, I thought "There should be a super simple way of completing this while looking nice." There for I done a ton of research and believe I have came up with the simplest, cleanest, and easiest to understand.
Setting up
First, we will want to create the INI file and a PowerShell script in a test folder.
SQLConfig.ini
[SQL Info]
SQLHost =SERVER\SQL
SQLDB =Database
SQLUser =User
SQLPass =Password123
Getting the information
Now that we have the INI file, we want to get the information from this file. To achieve this, we will use the Get-Content function.
Get-Content
$SQLFile = Get-Content SQLConfig.ini
Loop through the file
This will not tell the script to read the INI file. Now that we are reading the file, we need to get the contents of that file. To achieve this, we will use a foreach loop.
Foreach loop
foreach($line in $SQLFile) {
#To be added
}
Setting the variables
Now that we are looping through each line of the INI file, we want to set variables based on the variable in the INI file and set the value. To do this, we will add an IF statement for each variable we want to retrieve.
Using the IF statement, we can say, if that line contains "The INI Variable Name" then Split that line and set the PowerShell Variable to whatever is after the =
Note: If you have a space between the "=" and the value in the INI file, that space will also be in the Powershell variable.
Adding to foreach
foreach($line in $SQLFile) {
if($line -match "SQLHost"){$SQLHost = $line.Split('=')[1]}
if($line -match "SQLDB"){$SQLDB = $line.Split('=')[1]}
if($line -match "SQLUser"){$SQLUser = $line.Split('=')[1]}
if($line -match "SQLPass"){$SQLPass = $line.Split('=')[1]}
}
Testing
Now that we have it setup, we will test the code to ensure that it works correctly. We will add the following to the end of the script to print out the variable so that we can see if they were set correctly.
Print out variables
$SQLHost
$SQLDB
$SQLUser
$SQLPass
Output
SERVER\SQL
Database
User
Password123
Success!
Whole PowerShell Script
$SQLFile = Get-Content SQLConfig.ini
foreach($line in $SQLFile) {
if($line -match "SQLHost"){$SQLHost = $line.Split('=')[1]}
if($line -match "SQLDB"){$SQLDB = $line.Split('=')[1]}
if($line -match "SQLUser"){$SQLUser = $line.Split('=')[1]}
if($line -match "SQLPass"){$SQLPass = $line.Split('=')[1]}
}
$SQLHost
$SQLDB
$SQLUser
$SQLPass
Futhermore
I like to have a space on both sides of my "=" sign in the INI file. (In my opinion, it looks cleaner.) I tried to add a space in the split but that just caused it to output nothing. If you know of a way to fix that while still being simple and clean, please feel free to edit or add. Thank you!