Readini.ps1

This is an example how to read a value from an inifile with Powershell.

#***************************************************************************
#** Script:   ReadIni.ps1
#** Version:  1.0
#** Created:  12/19/2010 11:09AM
#** Author:   Adriaan Westra
#** Website:  http://www.westphil.nl
#**
#** Purpose / Comments:
#**    Get a value from an IniFile
#**
#**
#** Changelog :
#** 12/19/2010 11:09AM  : Initial version
#** 03/08/2011 08:00PM : Added substring to deal with = in returnvalue
#***************************************************************************
#***************************************************************************
#** Function: Read-Ini
#** Version:  1.0
#** Created:  12/19/2010 11:09AM
#** Author:   Adriaan Westra
#** Website:  http://www.westphil.nl
#**
#** Purpose / Comments:
#**    Read a value from an IniFile. 
#**    ; on the first position of a line is treated as comment in inifile
#**
#** Arguments :
#**    $IniFile        : Name (and path) of the inifile to read
#**    $Section        : Section which holds the key to read
#**    $Key            : Key of the value to read
#**
#** Returns   :
#**    The value from the inifile if found
#**    Null if not found
#**
#** Changelog :
#** 12/19/2010 11:09AM  : Initial version
#**
#***************************************************************************
Function Read-Ini ($IniFile, $Section, $Key) {
# Iinitialize $match to false
$match = $false
# Read the inifile
$text = get-content $IniFile 
# Process the lines read from the inifile in a for loop
For ( $i=0; $i -lt $text.length ; $i++) { 
# If first character = ; (comment line) then skip line
    if ($text[$i] -match "^;") {
        Continue
    }
# If First Character = [ then check if it's the correct section 
    If ( $text[$i] -iMatch "^\[") {
       If ( $text[$i] -imatch "\[" + $Section + "\]") { 
          $match = $true 
       } Else {
          $match = $false 
       }
    }
# Found the section now process the keys
    If ($match) {
# Split the line on the = , Value[0] holds the key Value[1] holds the value to return
        $value = [regex]::split( $text[$i],'=')
        If ($value[0] -eq $key ) {
            $Pos = $text[$i].indexof("=") + 1
            $returnvalue = $text[$i].Substring($pos, $text[$i].Length - $pos)
            Return $returnvalue
        }    }
 } # End For loop
 Return $null
} # End Function
#***************************************************************************
#** Start of script
#***************************************************************************
#** Clear the screen
Clear-host
#** Initialize the variables
$IniFile = "test.ini"
$Section = "main"
$Key = "test2"
#** Call the Read-Ini Function
Read-Ini -IniFile $iniFile -Section $Section -key  $Key

Geef een reactie

Je e-mailadres wordt niet gepubliceerd. Vereiste velden zijn gemarkeerd met *