PowerShell to Read single value from simple .ini f

2020-06-18 06:46发布

问题:

Everything I've found looks way over complex. It's almost like I just need to read a text file.

ADAP.ini contains this, nothing else:

http://xxx.104.xxx.226
APP=2.3.6
DLL=2.3.6

Using Powershell, how can I read what APP=value is? and or what DLL=value is?

I would store the value in a variable and use it later in Powershell script.

回答1:

This looks like a good use case for ConvertFrom-StringData which by default looks for key value pairs separated by the equals symbol.

Because the first line of your .ini file doesn't have an equals we would need to skip it to avoid an error. This can be done simply with Select -Skip 1.

Here's the code:

$ADAP = Get-Content 'ADAP.ini' | Select -Skip 1 | ConvertFrom-StringData

You can then get the values of APP and DLL by accessing them as named properties of the $ADAP object, as follows:

$ADAP.APP
$ADAP.DLL


回答2:

You can quite easily write a PowerShell function that allows you to read ini files:

function Get-IniFile 
{  
    param(  
        [parameter(Mandatory = $true)] [string] $filePath  
    )  

    $anonymous = "NoSection"

    $ini = @{}  
    switch -regex -file $filePath  
    {  
        "^\[(.+)\]$" # Section  
        {  
            $section = $matches[1]  
            $ini[$section] = @{}  
            $CommentCount = 0  
        }  

        "^(;.*)$" # Comment  
        {  
            if (!($section))  
            {  
                $section = $anonymous  
                $ini[$section] = @{}  
            }  
            $value = $matches[1]  
            $CommentCount = $CommentCount + 1  
            $name = "Comment" + $CommentCount  
            $ini[$section][$name] = $value  
        }   

        "(.+?)\s*=\s*(.*)" # Key  
        {  
            if (!($section))  
            {  
                $section = $anonymous  
                $ini[$section] = @{}  
            }  
            $name,$value = $matches[1..2]  
            $ini[$section][$name] = $value  
        }  
    }  

    return $ini  
}  

$iniFile = Get-IniFile .\ADAP.ini
$app = $iniFile.NoSection.APP
$dll = $iniFile.NoSection.DLL

For this sample ini file saved as Test.ini:

; last modified 1 April 2001 by John Doe
[owner]
name=John Doe
organization=Acme Widgets Inc.

[database]
; use IP address in case network name resolution is not working
server=192.0.2.62     
port=143
file="payroll.dat"

Doing this:

$testIni = Get-IniFile .\Test.ini

Allows you to retrieve values like this:

$server = $testIni.database.server
$organization = $testIni.owner.organization


回答3:

You do "just need to read a text file" .. and then find which line begins with APP and then extract the value from it.

# read text file                        # find line beginning APP=
$AppLine = Get-Content -Path test.ini | Where-Object { $_ -match 'APP=' }

# split on = symbol and take second item
$AppVersion = $AppLine.Split('=')[1]

And you might benefit from [version]$AppVersion to make it into a proper sortable, comparable version number instead of a string.

And there's plenty of variation of ways you could do the reading and matching and extracting of a value (Get-Content, switch -file, Select-String, ForEach-Object, -match 'APP=(.*)', etc. in various combinations).

But Mark Wragg's answer is nicer, overall.



回答4:

$content = Get-Content ADAP.ini

$app = $content[1].Substring($content[1].IndexOf("=") + 1)
$dll = $content[2].Substring($content[2].IndexOf("=") + 1)

You can get the content by calling cmdlet Get-Content and assigning it to variable. By accessing to rows like indexes in arrays you can call methods for working with strings.

note: the code is ugly, I know.



回答5:

A slightly modified version of Mark Wragg's answer, with a simple check to make sure each line is valid before passing it to the cmdlet for processing.

$Config = Get-Content "C:\scripts\config.ini" |
    Where-Object {$_ -match "="} | ConvertFrom-StringData

Just adding it as I landed here myself and ended up using this solution to handle configuration files with multiple categories and comment lines.