ログまたは画面に出力する必要がある多くの文字列を含むスクリプトを作成しています。メンテナンスを簡素化するために、文字列を格納する非常に単純な lang.xml ファイルを作成しました。多くの文字列は、スクリプト内の変数に保持されている情報を表示するため、返された xml #text ノードで文字列を展開する小さなコマンドレットを作成しました。
エラーメッセージをフォーマットするためにcatchブロックでこれを使用するまで、これは非常にうまく機能します。たとえば、例外メッセージを展開しようとすると、空の文字列が返されます。例外オブジェクトをコマンドレットに渡しても、空の文字列に展開されます。以下は、出力例を含む XML とコマンドレットのスニペットです。
サンプル XML:
<?xml version="1.0" ?>
<lang>
<keyword name="ERRMessage">
<string>"Error message: $($Exception.Exception.Message)"</string>
</keyword>
</lang>
</xml>
コマンドレット:
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") }
}
}
}
例:
try { get-content goo -ErrorAction Stop} catch { Read-Lang -KeyWord 'ERRMessage' -Exception $_ }
期待される出力:
Error Message: Cannot find path 'path\to\goo' because it does not exist.
実際の出力:
Error Message: