Created
May 22, 2015 07:29
-
-
Save michaelvdnest/58f96cb59027efbc3425 to your computer and use it in GitHub Desktop.
Gets the content of an INI file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Function Get-IniContent | |
{ | |
<# | |
.Synopsis | |
Gets the content of an INI file | |
.Description | |
Gets the content of an INI file and returns it as a hashtable | |
.Notes | |
Author : Oliver Lipkau <oliver@lipkau.net> | |
Blog : http://oliver.lipkau.net/blog/ | |
Date : 2010/03/12 | |
Version : 1.0 | |
#Requires -Version 2.0 | |
.Inputs | |
System.String | |
.Outputs | |
System.Collections.Hashtable | |
.Parameter FilePath | |
Specifies the path to the input file. | |
.Example | |
$FileContent = Get-IniContent "C:\myinifile.ini" | |
----------- | |
Description | |
Saves the content of the c:\myinifile.ini in a hashtable called $FileContent | |
.Example | |
$inifilepath | $FileContent = Get-IniContent | |
----------- | |
Description | |
Gets the content of the ini file passed through the pipe into a hashtable called $FileContent | |
.Example | |
C:\PS>$FileContent = Get-IniContent "c:\settings.ini" | |
C:\PS>$FileContent["Section"]["Key"] | |
----------- | |
Description | |
Returns the key "Key" of the section "Section" from the C:\settings.ini file | |
.Link | |
Out-IniFile | |
#> | |
[CmdletBinding()] | |
Param( | |
[ValidateNotNullOrEmpty()] | |
[ValidateScript({(Test-Path $_)})] | |
[Parameter(ValueFromPipeline=$True,Mandatory=$True)] | |
[string]$FilePath | |
) | |
Begin | |
{Write-Verbose "$($MyInvocation.MyCommand.Name):: Function started"} | |
Process | |
{ | |
Write-Verbose "$($MyInvocation.MyCommand.Name):: Processing file: $Filepath" | |
$ini = @{} | |
switch -regex -file $FilePath | |
{ | |
"^\[(.+)\]$" # Section | |
{ | |
$section = $matches[1] | |
$ini[$section] = @{} | |
$CommentCount = 0 | |
} | |
"^(;.*)$" # Comment | |
{ | |
if (!($section)) | |
{ | |
$section = "No-Section" | |
$ini[$section] = @{} | |
} | |
$value = $matches[1] | |
$CommentCount = $CommentCount + 1 | |
$name = "Comment" + $CommentCount | |
$ini[$section][$name] = $value | |
} | |
"(.+?)=(.*)" # Key | |
{ | |
if (!($section)) | |
{ | |
$section = "No-Section" | |
$ini[$section] = @{} | |
} | |
$name,$value = $matches[1..2] | |
$ini[$section][$name] = $value | |
} | |
} | |
Write-Verbose "$($MyInvocation.MyCommand.Name):: Finished Processing file: $FilePath" | |
Return $ini | |
} | |
End | |
{Write-Verbose "$($MyInvocation.MyCommand.Name):: Function ended"} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment