Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <#
- .SYNOPSIS
- Get-IniItem displays found key-value pairs in ini file.
- .Description
- Get-IniItem displays found key-value pairs in ini file based on passed wildcard expression.
- Only *, ?, [] wildcards are supported.
- .PARAMETER Name
- Specifies ini file path.
- .PARAMETER Filter
- Specifies key-value pair file filter. Use section.key syntax to filter key-value pairs. If key-value pair has no section you can omit section name.
- .INPUTS
- No inputs accepted.
- .OUTPUTS
- System.Collections.Generic.Dictionary<string, string>
- #>
- using namespace System.Collections.Generic;
- [CmdletBinding()]
- param (
- [switch]
- $Version,
- [Parameter(Mandatory)]
- [string]
- $Name,
- [Parameter(Mandatory)]
- [string]
- $Filter
- )
- class Section {
- [string] $Name;
- [IDictionary[string, string]] $KeyValuePairs
- Section([string] $name) {
- $this.Name = $name
- $this.KeyValuePairs = New-Object -TypeName "Dictionary[string, string]"
- }
- [void] Add([string] $key, [string] $value) {
- if (!$key) {
- throw "Key must be non-empty string."
- }
- $this.KeyValuePairs.Add($key, $value)
- }
- [void] Remove([string] $key) {
- if (!$key) {
- throw "Key must be non-empty string."
- }
- $this.KeyValuePairs.Remove($key)
- }
- }
- function Get-IniFileContents($name) {
- if (-not (Test-Path $name)) {
- throw "File doesn't exist."
- }
- $globalSection = New-Object -TypeName "Section" -ArgumentList ""
- $currentSection = $globalSection
- $sections = @($globalSection)
- foreach ($line in Get-Content $name) {
- switch -Regex ($line) {
- "^\s*(#.*)?$" {
- continue
- }
- "^\s*\[(.+?)\]\s*$" {
- $currentSection = New-Object -TypeName "Section" -ArgumentList $Matches[1]
- $sections += $currentSection
- }
- "^\s*(\w+)=(\w+)\s*$" {
- $currentSection.Add($Matches[1], $Matches[2])
- }
- default {
- throw "Wrong ini file format: `"$line`" must be an empty line, comment, section or key-value-pair declaration."
- }
- }
- }
- Write-Output $sections
- }
- Set-Variable -Name SuccessStatus -Value 0 -Option Constant
- Set-Variable -Name WrongOptionStatus -Value 2 -Option Constant
- if ($Filter -notmatch "\.") {
- $Filter = ".$Filter"
- }
- $filterArray = $Filter -split "\."
- $sectionName = $filterArray[0]
- $keyName = $filterArray[1]
- Get-IniFileContents $Name |
- Where-Object { $_.Name -like $sectionName } |
- Select-Object -ExpandProperty KeyValuePairs
- exit $SuccessStatus
Add Comment
Please, Sign In to add comment