I’m writing a script that has a lot of strings that need to be output either to a log or to the screen. To help simplify maintenance, I created a very simple lang.xml file where I store the strings. A lot of the strings display information that’s held in variables in the script, so I wrote a little cmdlet that will expand the strings in returned xml #text nodes.
This works pretty great up until I use this in catch block to format error messages. When I attempt to expand the Exception message, for example, an empty string is returned. Even when I pass the Exception object to the cmdlet it expands to an empty string. Below is a snippet of XML and the cmdlet, with example output.
Sample XML:
<?xml version="1.0" ?>
<lang>
<keyword name="ERRMessage">
<string>"Error message: $($Exception.Exception.Message)"</string>
</keyword>
</lang>
</xml>
Cmdlet:
function Read-Lang
{
[CmdletBinding()]
param(
[Parameter( Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
HelpMessage="The name atttribute of a keyword in lang.xml")]
[string[]] $Keyword,
$Exception
)
begin
{
if ( $global:LangXML -eq $null )
{
Write-Debug "Language XML has not been loaded, loading now."
$global:LangXML = [xml] (Get-Content '.\lang.xml')
}
}
process
{
foreach ( $name in $Keyword)
{
$Query = "/lang/keyword[@name=`"$name`"]/string"
$global:LangXML.SelectNodes($Query) |
ForEach-Object { $ExecutionContext.InvokeCommand.ExpandString($_."#text") }
}
}
}
Example:
try { get-content goo -ErrorAction Stop} catch { Read-Lang -KeyWord 'ERRMessage' -Exception $_ }
Expected output:
Error Message: Cannot find path 'path\to\goo' because it does not exist.
Actual output:
Error Message:
I’ve tested you code with xml example.
It works for me, after I removed the
</xml>closing tag inlang.xmlfile, that gives me error here$global:LangXML = [xml] (Get-Content '.\lang.xml')this what I got:
p.s.: error is in italian, I’m on it-it culture system but is the right error.