Home > Net >  Powershell, modify TXT/XML file to add a string after a specific variable?
Powershell, modify TXT/XML file to add a string after a specific variable?

Time:01-17

Trying to edit the DyanmoSettings.xml file without installing any specific packages on the Windows systems (sed, awk, etc)

to do: need to modify this file; %appdata%\dynamo\Dynamo Revit\2.3\DynamoSettings.xml

and within that file above, find this line;

>
> <CustomPackageFolders>
>     <string>C:\Users\user1.mydomain\AppData\Roaming\Dynamo\Dynamo Revit\2.3</string>
>  </CustomPackageFolders>
>

and add 'C:\Users%USERNAME%\OneDrive\DT-s\Revit Scripts\Dynamo\Custom Packages '

so it looks like this;

> 
> <CustomPackageFolders>
>     <string>C:\Users\user1.mydomain\AppData\Roaming\Dynamo\Dynamo Revit\2.3</string>
>     <string>C:\Users\%USERNAME%\OneDrive\DT-s\Revit Scripts\Dynamo\Custom Packages </string>
>   </CustomPackageFolders>
> 
> 

TIA!

tried using standard >> method in CMD but this didn't work.

CodePudding user response:

Powershell uses c#. So any c# code can run inside powershell without any installation. Code below uses the c# library Xml Linq. Try following

using assembly System 
using assembly System.Xml.Linq 

$Filename = "c:\temp\test.xml"
$xDoc = [System.Xml.Linq.XDocument]::Load($Filename)

$customFolder =  $xDoc.Descendants("CustomPackageFolders")
$newElement = [System.Xml.Linq.XElement]::new("string","C:\Users\%USERNAME%\OneDrive\DT-s\Revit Scripts\Dynamo\Custom Packages")
$customFolder.Add($newElement)
Write-Host "customFolder = " $customFolder
$xDoc.Save("c:\temp\test1.xml")

CodePudding user response:

If that xml file looks anything like this

<DynamOconfig>
    <CustomPackageFolders>
        <string>C:\Users\user1.mydomain\AppData\Roaming\Dynamo\Dynamo Revit\2.3</string>
    </CustomPackageFolders>
</DynamOconfig>

then

# load the settings file
$xml = [System.Xml.XmlDocument]::new()
$xml.Load("$env:APPDATA\dynamo\Dynamo Revit\2.3\DynamoSettings.xml")

# create a new <string> node
$newNode = $xml.CreateElement('string')
$newNode.InnerText = 'C:\Users\%USERNAME%\OneDrive\DT-s\Revit Scripts\Dynamo\Custom Packages'
# find the <CustomPackageFolders> node and append the new node to it
[void]$xml.SelectSingleNode('//CustomPackageFolders').AppendChild($newNode)

# save to (for safety NEW) file
$xml.Save("$env:APPDATA\dynamo\Dynamo Revit\2.3\NEW_DynamoSettings.xml")

Result:

<DynamOconfig>
  <CustomPackageFolders>
    <string>C:\Users\user1.mydomain\AppData\Roaming\Dynamo\Dynamo Revit\2.3</string>
    <string>C:\Users\%USERNAME%\OneDrive\DT-s\Revit Scripts\Dynamo\Custom Packages</string>
  </CustomPackageFolders>
</DynamOconfig>

P.S. If your intention is to have %USERNAME% interpolated in the string so it expands to your username, then create the new node's innertext like ths:

$newNode.InnerText = "C:\Users\$env:USERNAME\OneDrive\DT-s\Revit Scripts\Dynamo\Custom Packages"

(mind you need double-quotes now)

  • Related