New Progrommer
New Progrommer

Reputation: 35

How to invoke PowerShell script from command prompt that updates XML file?

Invoke PowerShell script from command prompt to update XML file nodes.

Sample XML File

<Job>
  <ProcFile name="jobName" />
  <Category name="Indicative">
    <Item name="rbfVersion">versionname</Item>
    <Item name="rbfRelease">releaseNumber</Item>
  </Category>
  <Category name="Parameters">
    <Item name="MmsPzapAppId">Value1</Item>
  </Category>
</Job>

PowerShell Script prepared to update nodes of xml file.

param ($workingDir, $fileName, $arrayOfObject)

if (!$workingDir) {
    throw "Working Directory Parameter is missing"
}elseif(!$fileName){
    throw "File name or Runbook name Parameter is missing"
}elseif(!$arrayOfObject){
    throw "Input parameters are missing"
}
$keyVauleHash = $arrayOfObject

#concatenating two parameters to get full path 
$filePath = "$workingDir\$fileName"
 
#Reading Values 
Write-Host "Working Directory: $workingDir"
Write-Host "File Name : $fileName"
Write-Host "Full Path : $filePath"
Write-Host "Number of Nodes to be updated:"$keyVauleHash.Count

#Get Content of XML file and store it in $xml file
[xml]$xml = Get-Content $filePath

#Looping through each key:value pair from array of object and updating respective nodes
foreach($item in $keyVauleHash.GetEnumerator()){
    $key = $item.key
    $value = $item.value
    $parametersNode = $xml.Job.Category | where {$_.Name -eq 'Parameters'}
    $foundNode = $parametersNode.Item | where {$_.Name -eq $key} 
    Write-Output $foundNode
    $foundNode.'#text' = $value
    Write-Output $foundNode
}

#Saving the changes
$xml.Save($filePath)

Script usage or invoke command

pwsh -command C:\Path\To\PowerShellScript\UpdateXML.ps1 -workingDir 'C:\Path\To\xmlFile' -fileName 'xmlFileName.xml' -arrayOfObject '@{InputFile="Value"}'

Above script should be invoked from command prompt.

Tried different method also, Tried PowerShell.exe instead of pwsh then also didn't work.

alternate invoke command

PowerShell.exe C:\Path\To\PowerShellScript\UpdateXML.ps1 -workingDir 'C:\Path\To\xmlFile' -fileName 'xmlFileName.xml' -arrayOfObject '@{InputFile="Value"}'

Both of the invoke methods are not working actually. I am getting this below error.

The property '#text' cannot be found on this object. Verify that the property exists and can be set.

Upvotes: 1

Views: 123

Answers (2)

mklement0
mklement0

Reputation: 437978

Your immediate problem is with the syntax of your CLI calls (powershell.exe for Windows PowerShell, pwsh for PowerShell (Core) 7+)):

-arrayOfObject '@{InputFile="Value"}'

due to use of enclosing '...', passes a string with verbatim content @{InputFile=Value} to your script's -arrayOfObject parameter, not a hashtable object as you intend - also note the loss of the unescaped " characters, which are removed during initial parsing of the command line.

Instead, use either of the following:

# Note the need to \-escape the " chars.
-arrayOfObject @{InputFile=\"Value\"}

# Alternative, with single quotes
-arrayOfObject @{InputFile='Value'}

There are also problems with your PowerShell code, notably not guarding against not finding a target XML element of interest.

That is, if $foundNode happens to be $null, $foundNode.'#text' = ... yields the error you saw (try $null.foo = 'bar', for instance).

Your PowerShell code can be both simplified and made more robust - see next section.


A robust and PowerShell-idiomatic reformulation of your script:

# Make the parameters mandatory and specify *data types* for them.
param (
  [Parameter(Mandatory)]
  [string] $workingDir, 
  [Parameter(Mandatory)]
  [string] $fileName, 
  [Parameter(Mandatory)]
  [hashtable] $arrayOfObject # Probably worth renaming this.
)

# Load the XML file into an in-memory DOM
$filePath = Convert-Path -LiteralPath "$workingDir\$fileName"
# Note: Constructing an [xml] instance and then using .Load() is 
#       more robust than using [xml]$xml = Get-Content $filePath
$xml = [xml]::new(); $xml.Load($filePath)

# Determine the parent element of the elements to modify.
$parametersNode = $xml.Job.Category | Where-Object Name -eq Parameters

# Loop over all key-value pairs passed in and modify
# child elements whose 'Name' attribute matches a key with the
# corresponding value.
foreach ($key in $arrayOfObject.Keys) {
  if ($foundNode = $parametersNode.Item | Where-Object Name -eq $key) {
    $foundNode.'#text' = $arrayOfObject[$key]
  }
}

# Save the modified document.
$xml.Save($filePath)

Upvotes: 2

jdweng
jdweng

Reputation: 34421

Following code uses XML and a dictionary to change values of nodes

using assembly System.Xml.Linq

$inputFilename = "c:\temp\test.xml"
$outputFilename = "c:\temp\test1.xml"

$doc = [System.Xml.Linq.XDocument]::Load($inputFilename)

$items = $doc.Descendants("Item")

$dict = [System.Collections.Generic.Dictionary[string, [System.Xml.Linq.XElement]]]::new()

$items | foreach { $name = $_.Attribute("name").Value; $element = $_; $dict.Add($name, $element) }

$newValues = @{
   rbfVersion = 'version1'
   rbfRelease = '2.0'
   MmsPzapAppId = '123'
}
foreach($newValue in $newValues.Keys)
{
   $key = $newValue 
   $value = $newValues[$newValue]
   $element = $dict[$key]
   $element.SetValue($value)
}
$doc.Save($outputFilename)

Upvotes: 1

Related Questions