Home > Mobile >  Powershell Commenting and Uncommenting .properties file lines
Powershell Commenting and Uncommenting .properties file lines

Time:12-08

I have a test.properties file that has a format like the following:

hostName=hostName1
#hostName=hostName2
portNum=portNum1
#portNum=portNum2

I am attempting to write a powershell script that when run, will comment any hostNames and portNums, and only uncomment the new one that I want to pass in.

If I had a variable that was $hostNameToUncomment, then I would like the flow to say something like:

$hostNameToUncomment=hostName1

$propertiesFile = Get-Content ($path) | ForEach-Object {
     if hostName anywhere is uncommented, comment it

     if hostName value = $hostNameToUncomment,
          Remove the '#' from that line
}

How can this be done?

CodePudding user response:

You can use a switch to read the file and take advantage of it's -Regex switch:

$toUncomment = 'hostname2'
$file = 'path/to/file.txt'

$result = switch -Regex -File($file)
{
    "^#hostname=$toUncomment\b"
    {
        $Matches[0] -replace '^#'
    }
    "^[^#]\w =(?!$toUncomment).*"
    {
        $Matches[0] -replace '^','#'
    }
    Default
    {
        $_
    }
}

$result | Out-File $file

See https://regex101.com/r/sfhWz4/2 for explanation on both regex using hostname2 as an example.

  • Related