PowerShellでオブジェクトを文字列化(Serialize)
スクリプト
% { $str = " world!"; echo "hello"+$str } | ConvertTo-Xml -as String -Depth 1
実行結果
<?xml version="1.0"?> <Objects> <Object Type="System.Management.Automation.ScriptBlock"> $str = " world!"; echo "hello"+$str </Object> </Objects>
スクリプトブロックも変換できている。ScriptBlockはクロージャではないので呼び出し時のバインディングを用いることになる。しかしGetNewClosure()メソッドを呼び出せばクロージャに変換できる。
ファイルに保存・読み込みしたい場合はExport-Clixml, Import-Clixmlというコマンドレットがある。
変換できるのは組み込み型とPSObjectだけだろうか。