0
votes

I have a PowerShell script that looks for specific files and folders and the file and folder URLs in contained in an XML file (written to a variable in PowerShell). I want to be able to look for files in the directory of the current user, but XML files can't contain dynamic variables, so I can't just do the following

<URL>C:\Users\$Env:UserName\SomeFile.*</URL>

So what I have done is declare an XML Entity as such:

<!DOCTYPE config [
  <!ENTITY user "UserName!">
]>

BUT, I can not figure out how to reference this entity from PowerShell to update it. So I can't just do this:

$Config.Config.UserName = $Env:UserName

Is there anyway to access entities once an XML file is written to a PowerShell variable. I.E. written to a var like this:

[xml]$Config = Get-Content ./SomeXML_File.xml

Update -- Here is an example of what I am looking at. I want to use PowerShell to replace "UserName!" with the current user of the system. So that "&user;" will be read as the current system user when the script gets data from the xml file.

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE config[
  <!ENTITY user "UserName!">
]>
<Configuration>
     <Files>
          <URL>C:\Users\&user;\Desktop\NewFolder</URL>
     </Files>
</Configuration>
'''

1
Does the above link may help you? If not, what is the error or problem when using .SelectNodes method? - Alex_P
I'm getting an overload definition error. I'm going to update my question with a sample of my xml doc, and maybe that will help. - Ken
As in, it's like the ENTITY isn't even there, but the actual file structure replaces "&user;" with the declared text of "UserName!"...so if I can update "UserName!" then I think it will work....and I'd rather not do it with a get-content -replace() workaround. - Ken
We haven't heard from you.. Did my answer solve your problem? If so, please consider accepting it by clicking ✓ icon on the left. This will help others with a similar question finding it more easily. - Theo

1 Answers

0
votes

I know one should not use string replacements on xml, but this seemed to be the only way to get it working:

Get the content of the XML as single string

$xmlText = Get-Content -Path 'D:\SomeFile.xml' -Raw

For demo I'm using a Here-String

$xmlText = @"
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE config[
  <!ENTITY user "UserName!">
]>
<Configuration>
     <Files>
          <URL>C:\Users\&user;\Desktop\NewFolder</URL>
     </Files>
</Configuration>
"@

# create a new Entity tag
$newEntity = '<!ENTITY user "{0}">' -f $env:USERNAME

# replace the current XML Entity with the new one
$xmlText = $xmlText -replace '<!ENTITY[^<>]*>', $newEntity

# load the xml from string to have it resolve the ENTITY username
$xml = [xml]$xmlText

# save the updated XML. Use an absolute path here
$xml.Save("D:\SomeFile.xml")