Rakha
Rakha

Reputation: 2054

Parsing a file that has a parameter and a value

I'm a bit struggling trying to find the best way to parse this :

Secure Boot = Enabled;[Optional:Disabled = Enabled]
Network Offline Locker = Disabled;[Optional:Disabled = Enabled]
Chassis Intrusion Detection = Disabled;[Optional:Disabled = Enabled]
Configuration Change Detection = Disabled;[Optional:Disabled = Enabled]
Password Count Exceeded Error = Enabled;[Optional:Disabled = Enabled]
CSM = Disabled;[Optional:Disabled = Enabled]
Boot Up Num-Lock Status = On;[Optional:Off = On]

I need to have it so $Config and $ConfigValue are for example :

$Config
Secure Boot
$ConfigValue
Enabled;[Optional:Disabled = Enabled]

So the configuration name is left of " = " and it's value is right of the " = ".

I'm doing this for now and it seems to work fine :

  (Get-Content "File.ini") | ForEach-Object {

      #Isolate parameter (what is left of " = ")
      $Config =  ($_ -split " = ")[0]

      #Isolate value of parametre (what is right of " = ")
     $ConfigValue = ($_ -split " = ")[1]
}

Does that make the most sense? It's working fine but i'm always curious to find different ways to analyze it.

Much appreciated.

Upvotes: 0

Views: 65

Answers (1)

Olaf
Olaf

Reputation: 5232

I'd recommend to use a PSCustomObject like this:

Get-Content -Path D:\sample\File.ini |
ForEach-Object {
    [PSCustomObject]@{
        Config      = ($_ -split '=')[0].Trim()
        ConfigValue = (($_ -split '=')[1..10].Trim()) -join '='
    }
}

I assume that you don't have more than 10 equal signs in your ini file. ;-)

You have a string with 2 (or more) equal signs in it. But you just want to split it on the first one. So you split the string on each equal sign, use the first part as the first part and join the rest of them as the second part. Therefor you re-join them with an equal sign again.

Upvotes: 1

Related Questions