Link to home
Create AccountLog in
Avatar of Manikandan Narayanswamy
Manikandan NarayanswamyFlag for India

asked on

Powershell script to modify file content

Need power-shell script to modify parameter in configuration file

I'm attaching an test file where I need to modify GIM_USE_SSL value to 0 using power shell on 100 of servers. Need a way to automate this thing kindly find the below parameter which needs to be modified using script

GIM_USE_SSL' => {
                                                                     'ts' => '2009-07-15 17:05:17.0',
                                                                     'value' => '1'
Test.txt
Avatar of oBdA
oBdA

Try this; $InFile and $OutFile may be identical.
$InFile = "D:\Temp\test.txt"
$OutFile = "D:\Temp\test2.txt"
$Param = 'GIM_USE_SSL'
$NewValue = '0'

$RegEx = "(?<=\A\s*'value'\s*=>\s*')(?<Value>.*?)(?='\s*\Z)"
$MatchFound = $false
$InParamSection = $false
@(Get-Content -Path $InFile) | ForEach-Object {
	If ($_ -match "'$($Param)' => {") {
		$InParamSection = $true
		$_
	} Else {
		If ($InParamSection) {
			If ($_ -match "\A\s*}\s*,\s*\Z") {
				$InParamSection = $false
				$_
			} Else {
				If ($_ -match $RegEx) {
					$MatchFound = $true
					$_ -replace $RegEx, $NewValue
					Write-Host "[$($InFile)] $($Param): replaced old value '$($Matches['Value'])' with '$($NewValue)'" -ForegroundColor Yellow
				} Else {
					$_
				}
			}
		} Else {
			$_
		}
	}
} | Set-Content -Path $OutFile
If (-not $MatchFound) {
	Write-Error "[$($InFile)] no match found for $($Param)!"
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Ben Personick (Previously QCubed)
Ben Personick (Previously QCubed)
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of Manikandan Narayanswamy

ASKER

Thanks for the help