Reputation: 11
I'm new to understanding how power-shell commands works. I'm struggling to understand a easy method/way to add a new line into an existing "obunity.exe.config" file.
New line is:
<RequestTimeoutSeconds Value="270"/>
This has to go in after service locations as per below.
.config file starts like below
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
in the middle is this section - the section i need to add the line
</ServiceLocations>
<RequestTimeoutSeconds Value="270"/>
<AllowAllSSLCertificates Enabled="false"/>
<OptimizedServicePipeline Enabled="true"/>
</Hyland.Services.Client>
The GOAL! The .ps1 when created is to be deployed via SCCM to update all the users with this software and the .config file located in the c drive.
I tired to search google for some examples, but for me it's trying to understand how the code works and i guess understanding the syntax. Below is an example of code i've tried to get working.
One example i have from doing a load of google searching - however when i test this the additional line is not included.
$thefilename = 'obunity.exe.config'
$oldfile = [System.IO.File]::ReadAllText($(Get-Item($thefilename)).FullName)
$matchtext = '[</ServiceLocations>]'
$newtext = '<RequestTimeoutSeconds Value="270"/>'
$newfile = $oldfile -split $matchtext,0,'simplematch' -join ($matchtext+"`r`n"+$newtext)
$newfile = $newfile[0..($newfile.length-3)] -join ''
$newfile | out-file $thefilename
I expect the output to add in the additional line to the .config file automatically and the deployment method via SCCM to all users of the particular software. Thanks so much in advance.
Upvotes: 1
Views: 864
Reputation: 10019
You can this by manipulating the xml as an object.
$thefilename = 'c:\temp\obunity.exe.config'
$newtext = '<RequestTimeoutSeconds Value="270"/>'
# read the file using the Get-Content native PowerShell cmdlet, cast to xml object
[xml]$xmlObj = Get-Content $thefilename
# specify where you want the new node to be added by dot-indexing using the node names
$addhere = $xmlObj.configuration.configSections.'Hyland.Services.Client'
# create the new node
$newNode = $addhere.OwnerDocument.ImportNode(([xml]$newtext).DocumentElement,$true)
# add it to xml
$addhere.AppendChild($newNode)
save xml back to file
$xmlObj.Save($thefilename)
I am assuming this simplified xml structure when specifying where the new node goes:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<Hyland.Services.Client>
<ServiceLocations>
</ServiceLocations>
<AllowAllSSLCertificates Enabled="false" />
<OptimizedServicePipeline Enabled="true" />
</Hyland.Services.Client>
</configSections>
</configuration>
Upvotes: 1