2

I'm a beginner of powershell and I'm having trouble reading the path value of an xml file.

Settings.xml

<?xml version="1.0"?>
 <Configuration>
   <EmailSettings>
    <SMTPServer>blabla</SMTPServer>
    <SMTPPort>blabla</SMTPPort>
    <Path>Repository\Excel</Path>   
  </EmailSettings>
 </Configuration>

To read the data in the XML file I do this way

$ScriptPath = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent

[xml]$ConfigFile = Get-Content "$ScriptPath\Settings.xml"

The problem is that if I display the extracted value it is shown correctly, while if I concatenate it with another value, for example to obtain a complete path, I get this

Write-Host $ScriptPath  
--> c:\script

write-host $ConfigFile.Configuration.EmailSettings.Path 
--> Repository\Excel

write-host $ScriptPath\$ConfigFile.Configuration.EmailSettings.Path   
--> c:\script\System.Xml.XmlDocument.Configuration.EmailSettings.Path

How do we do to get the value (in string format??) to be able to concatenate to other variables?

Thank you

1
  • You are already using Split-Path to get a part into a variable, well what about Join-Path? Commented Nov 2, 2018 at 20:06

1 Answer 1

1

You need $(...), the subexpression operator, in order to evaluate an expression such as $ConfigFile.Configuration.EmailSettings.Path inside an expandable string.
By contrast, a simple variable reference such as $ScriptPath is fine without the $(...):

Write-Host "$ScriptPath\$($ConfigFile.Configuration.EmailSettings.Path)"

Note that I've additionally added explicit double-quoting, to make the command more robust - see below for details.

As an aside: Write-Host is generally the wrong tool to use, unless the intent is explicitly to write to the display only, bypassing PowerShell's output streams.


Generally, unquoted tokens that aren't single expressions are implicitly treated like expandable strings, i.e., as if they had been passed in double quotes, and by and large the same rules apply.

However, in the absence of explicit quoting there are additional pitfalls, such as tokens that start with - or the need to escape additional characters, so always double-quoting expandable tokens is a good habit to form.

How PowerShell parses unquoted tokens in argument mode in general is a complex topic - see this answer.

Sign up to request clarification or add additional context in comments.

1 Comment

My pleasure, @Gus; glad to hear it was helpful.

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.