Skip to content

Commit 9eeee79

Browse files
Fix serialization of PSCustomObject wrapped object
With the switch away from converting PSCustomObjects to dictionaries we broke the way values that are wrapped in a PSCustomObject are serialized. This is evident when values of hashtables are generated using Write-Output which generates a PSCustomObject (Which is not evident in powershell, as there is a lot of magic in powershell), but is clearly evident when we try to use an object generated in PowerShell, in C#. This change looks at the nested type of a PSCustomObject, and unwraps it if it's not just another PSCustomObject. Fixes: #157 Signed-off-by: Gabriel Adrian Samfira <gsamfira@cloudbasesolutions.com>
1 parent 7e2611b commit 9eeee79

4 files changed

Lines changed: 26 additions & 1 deletion

File tree

Tests/powershell-yaml.Tests.ps1

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,21 @@ Import-Module $modulePath
2828
InModuleScope $moduleName {
2929
$compareStrictly = Get-EquivalencyOption -Comparator Equality
3030

31+
Describe "Test PSCustomObject wrapped values are serialized correctly" {
32+
Context "Wrapped values" {
33+
It "Should serialize correctly" {
34+
$expectBigInt = [System.Numerics.BigInteger]::Parse("9999999999999999999999999999999999999999999999999")
35+
$obj = [PSCustomObject]@{a = Write-Output 'string'; b = Write-Output 1; c = Write-Output @{nested = $true};d = [pscustomobject]$expectBigInt}
36+
$asYaml = ConvertTo-Yaml $obj
37+
$fromYaml = ConvertFrom-Yaml $asYaml
38+
39+
Assert-Equivalent -Options $compareStrictly -Expected "string" -Actual $fromYaml["a"]
40+
Assert-Equivalent -Options $compareStrictly -Expected 1 -Actual $fromYaml["b"]
41+
Assert-Equivalent -Options $compareStrictly -Expected $expectBigInt -Actual $fromYaml["d"]
42+
}
43+
}
44+
}
45+
3146
Describe "Test encode-decode symmetry." {
3247

3348
Context "Simple-Items" {
0 Bytes
Binary file not shown.
0 Bytes
Binary file not shown.

src/PowerShellYamlSerializer.cs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,17 @@ public void WriteYaml(IEmitter emitter, object value, Type type, ObjectSerialize
8181
emitter.Emit(new Scalar(AnchorName.Empty, "tag:yaml.org,2002:null", "", ScalarStyle.Plain, true, false));
8282
} else {
8383
serializer(prop.Name, prop.Name.GetType());
84-
serializer(prop.Value, prop.Value.GetType());
84+
var objType = prop.Value.GetType();
85+
var val = prop.Value;
86+
if (prop.Value is PSObject nestedPsObj) {
87+
var nestedType = nestedPsObj.BaseObject.GetType();
88+
if (nestedType != typeof(System.Management.Automation.PSCustomObject)) {
89+
objType = nestedPsObj.BaseObject.GetType();
90+
val = nestedPsObj.BaseObject;
91+
}
92+
}
93+
serializer(val, objType);
94+
8595
}
8696
}
8797
emitter.Emit(new MappingEnd());

0 commit comments

Comments
 (0)