Public/Get-JavaProperties.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<#
 .Synopsis
  Reads a Java-style Properties file and returns a hashtable of its content

 .Description
  Retrieves properties from a java property file and returns them as a hashtable. It allows specific properties to be retrived, in the case the property file is too large

 .Parameter PropertyFilePath
  The path to the property file that will be parsed.

 .Parameter PropertyList
  If specified, only properties in this list will be retrieved

 .Example
   # Get java properties from a file
   Get-JavaProperties "C:\myprops.properties"
#>

Function Get-JavaProperties() {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "")]
    [CmdletBinding(SupportsShouldProcess=$False)]
    [OutputType([Hashtable])]
    param (
        [parameter(Mandatory=$true,position=0)]
        [string]
        $PropertyFilePath,

        [parameter(Mandatory=$false,position=1)]
        [string[]]
        $PropertyList
    )

    [hashtable] $props = @{}
    
    if (Test-Path $PropertyFilePath) {
        $file = Get-Content $PropertyFilePath
        
        foreach($line in $file) {
            if ((!($line.StartsWith('#'))) -and
                (!($line.StartsWith(';'))) -and
                (!($line.StartsWith(";"))) -and
                (!($line.StartsWith('`'))) -and
                (($line.Contains('=')))) {
                $propName=$line.split('=', 2)[0]
                $propValue=$line.split('=', 2)[1]

                if ($PropertyList) {
                    $PropertyList | ForEach-Object {
                        if ($_ -eq $propName){
                            $props.Add($propName, $propValue)
                        }
                    }
                } else {
                    $props.Add($propName, $propValue)
                }
            }
        }
    } else {
        Write-Error "Java Property file: $PropertyFilePath not found"
    }

    Return $props
}