2

If i run the following code, I get the expected result based on whether the file exists or not with complete output (ie. $filepath always equals "C:\test\test.txt"):

$filepath = "C:\test\test.txt"

If( Test-Path $filepath)
{
    Write-Host "File does exist: " $filepath
}
Else
{
    Write-Host "File does not exist: " $filepath
}

ie. $filepath is in scope within the if block

Why does this behaviour not seem to translate when reading the filepath from an external file? Here, the conditional always returns false and the output prints as though $fileLocation is empty.

testConfig.xml file:

<ConfigFile>
    <FileLocation>C:\test\test.txt</FileLocation>
</ConfigFile>

powershell code:

[xml]$config = Get-Content ".\testConfig.xml"

$fileLocation = $config.SelectNodes("//FileLocation")

If( Test-Path -LiteralPath $fileLocation)
{
    Write-Host "File does exist: " $fileLocation
}
Else
{
    Write-Host "File does not exist: " $fileLocation
}

Is this something to do with the variable scope? How can I get the same behaviour as the first codeblock when reading the filepath from an xml file?

1 Answer 1

2

SelectNodes returns a XmlNodeList, not a string. If you want to select only one Node, you should use SelectSingleNode instead. Also, if you pass the XmlNode returned by SelectSingleNode, it will pass FileLocation to the Test-Path cmdlet because the ToString() method of the XmlNode gets called and actually returns the name of the node. You do this with the InnerText property:

$node = config.SelectSingleNode("//FileLocation")
Test-Path $node.InnerText
Sign up to request clarification or add additional context in comments.

Comments

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.