OK, so I’m hoping someone can help with this. I’m trying to edit a number of text files used as configuration files. I’m currently having two issues with the code:
First, the
If ($oFile -match “$sString” )check fails; I’ve tried -match, -like, -contains; with and without quotes. It’s in there, but it won’t see it and I don’t know why.
Second, When I’m re-writing the file I’m destroying the formatting (I’ve tried using both Set-Content and Out-file). This has no functionality effect but if/when a person has to look at the file it destroys the readability.
$aSearchFolders = "$sSysDr\Loc1", "$sPF\Loc2"
$aOldStrings = 'Name=(Settings)','Name=(Settings)','Name=Setting'
$aNewStrings = 'Name=(NewSettings)','Name=(NewSettings)','Name=NewSetting'
ForEach ($sFolder in $aSearchFolders) {
If (Test-Path "$sFolder") {
Set-Location $sFolder
$aSessions = Get-ChildItem -Path $sFolder -Filter *session*.txt -Recurse -Force
ForEach ($oSession in $aSessions){
#Write-Host "Session: $oSession"
ForEach ($sString in $aOldStrings){
#Write-Host "Search String: $sString"
$oFile = (Get-Content $oSession)
#Write-Host $oFile
If ($oFile -match "$sString" ) {
Write-Host "Inside the IF!"
$iNdx = [array]::IndexOf($aOldStrings,$sString)
$oFile.replace($sString, $aNewStrings[$iNdx])
Set-Content -Value $oFile -Path $oSession.FullName -Force
#$oFile -replace $sString, $aNewStrings[$iNdx] | Out-Null
}
If ($sString -eq "Name=Setting") {$oFile = ((Get-Content $oSession) -join "`n") -replace "DiffName=DiffSetting", "DiffName=DiffSetting`nNewName=NewSetting"}
Set-Content -Value $oFile -Path $oSession.FullName -Force
}
}
}
}
So where’s my mis-step? And thanks in advance…
Also, if it helps, the text files are formatted like this:
[Region0]
Name=(Settings)
Name=(Settings)
Name=Setting
[Region1]
Name=(Settings)
Name=(Settings)
Name=Setting