Most scripters would prefer to use XML or hashtables as input.
But… some Admins don’t like the XML formatting, but love the formatting of INI files.
So, here is a function to validate an INI file. It checks the content of each line against REGEX matches:
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 |
function Validate-INI { [cmdletbinding()] param ( [parameter(mandatory=$true,position=0)][String]$Path ) $Check = @() $File = try { Get-Content -Path $Path -ErrorAction 'SilentlyContinue' } catch { } if ($File -ne $null) { foreach ($Line in $File) { switch -regex ($Line) { # Section "^\[(.+)\]$" { $Check = $Check + $true break } # Integer "^\s*([^#].+?)\s*=\s*(\d+)\s*$" { $Check = $Check + $true break } # Decimal "^\s*([^#].+?)\s*=\s*(\d+\.\d+)\s*$" { $Check = $Check + $true break } # Comment "^[;]" { $Check = $Check + $true break } # Empty line "^\s*$" { $Check = $Check + $true break } # Everything else that is allowed "^\s*([^#].+?)\s*=\s*(.*)" { $Check = $Check + $true break } default { $Check = $Check + $false $LineNumber = $Check.count write-verbose "A problem was found on line $LineNumber" break } } } if ($Check -contains $false) { $false } else { $true } } else { Write-Warning "Unable to open and/or validate $Path" $false } } |