0

I am trying to edit an attribute value in a XML file with the id of the user logged in

i tried :

$user = $env:USERNAME
$xml = [xml](Get-Content "D:\Python\prm.xml")
$node = $xml.BootStrap.DataBaseAliases.LastLoginUserName
$node.SetAttribute("LastLoginUserName", "$user");

It returns an error : You cannot call a method on a null-valued expression. At D:\Python\a.ps1:5 char:1 + $node.SetAttribute("LastLoginUserName", "$user"); + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull

Also tried following:

$user = $env:USERNAME
$FileLocation = "D:\Python\prm.xml"
$File = Get-Content $FileLocation
$XML = [XML]$File
$XPpath = "/BootStrap/DataBaseAliases/LastLoginUserName"
$node = $XML.SelectNodes($XPpath)
$node | % { $_.SetAttribute("attribute-1", "$user") }
$XML.OuterXml | Out-File $FileLocation

This doesnt return any error, but xml is unchanged. XML content below:

<?xml version="1.0" encoding="utf-8"?><BootStrap MajorVersion="18" 
MinorVersion="8" PatchVersion="5" DeploymentVersion="0"><DataBaseAliases 
DefaultPMAlias="Corp_2016" LastLoginUserName="FOOUSER"><Alias>
<Name>PMDB</Name><AppType>Project Management</AppType><Connection> 
<DriverName>SQLServer</DriverName><BlobSize>-

i would like to replace FOOUSER with user currently logged in.

1
  • Thanks,Fixed the typo, but now it returns the below error: Method invocation failed because [System.String] does not contain a method named 'SetAttribute'. At D:\Python\a.ps1:5 char:1 + $node.SetAttribute("LastLoginUserName", "$user"); + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : MethodNotFound Commented Mar 25, 2019 at 10:33

1 Answer 1

1

The XPath is not pointing to proper an element, so the result is an empty set. Let's see why.

/BootStrap/DataBaseAliases/LastLoginUserName would match XML like so,

<BootStrap>
  <DatabaseAliases>
    <LastLoginUserName />
  </DatabaseAliases>
</BootStrap>

That's not what is in the sample. LastLoginUserName is an attribute of DatabaseAliases. Change the XPath to point into DataBaseAliases element and set its properties, like so:

$XPpath = "/BootStrap/DataBaseAliases"
$node = $XML.SelectNodes($XPpath)
$node | % { $_.SetAttribute("LastLoginUserName", $user) }
$XML.InnerXML
Sign up to request clarification or add additional context in comments.

1 Comment

perfect, works like a charm, Thanks for your help with this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.