please take a look of this. maybe it's helpfull
https://www.dev4sys.com/2016/05/how-to-parse-ini-file-in-powershell.html
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Hello. I have ini file with different sections like:
[section1]
bla bla 1
bla bla 2
[Section2]
blala 3
bla bla 4
etc.
How can I read in a variable specific section of the file.
p.s. The brackets can be changed , even the structure of the file.
Thank you in advance.
please take a look of this. maybe it's helpfull
https://www.dev4sys.com/2016/05/how-to-parse-ini-file-in-powershell.html
Thank you both. If I make the file look like CSV it would be easy.
You might be able to use this:
function ConvertFrom-Ini{
[CmdletBinding()]
param (
[Parameter()]
[string[]]
$str
)
$ns = ''
$sections = [ordered]@{}
$counter = 0
[array]$lines = $str -split "(?:\015{1,2}\012|\015|\012)"
ForEach ($line in $lines){
$counter++;
# Skip comments and empty lines.
if ($line -match "^\s*(?:\#|\;|$)"){
continue
}
# Remove inline comments.
$line = $line -replace "\s\;\s.+$",""
# Handle section headers.
if ( $line -match "^\s*\[.*\]\s*$" ){ # is this a section header?
# Create the sub-hash if it doesn't exist.
# Without this sections without keys will not
# appear at all in the completed struct.
if ( $line -match "^\s*\[\s*(.+?)\s*\]\s*$" ){ # does the section have a name?
$ns = $matches[1]
$sections[$ns] = @()
continue
}
$sections[""] = @()
continue
}
# Handle properties.
if ( $line -match "^\s*([^=]+?)\s*=\s*(.*?)\s*$" ){
$sections[$ns] += @{$matches[1]=$matches[2]}
continue
}
throw "Syntax error at line $counter : '$_'"
}
$sections
}
Here are a few examples of using it:
# test
$ini = @"
rootproperty=blah
[section]
reg_exp_1=High Priority
reg_exp_2=Low Priority
three= four
Foo =Bar
empty=
"@
$x=ConvertFrom-Ini $ini
# show all section and keys/values
$x.Keys |
ForEach-Object{
"[$_]" # section name
$sec = $_
$x[$_].keys | # all keys in section
ForEach-Object{
"`t$_ = $($x[$sec].$_)" # key = value
}
}
# if you know the section and value name
$x["section"].Foo
# Export section/keys/values to CSV
$x.Keys |
ForEach-Object{
$sec = $_
$x[$_].keys | # all keys in section
ForEach-Object{
[PSCustomObject]@{
Section = $sec
Name = $_
Value = $x[$sec].$_
}
}
} | Export-Csv c:\junk\ini.csv -notypeinfo