Pode icon indicating copy to clipboard operation
Pode copied to clipboard

Issue with `ConvertTo-PodeYaml` when `Count` is a Key in Hashtable or PSCustomObject

Open mdaneri opened this issue 4 months ago • 0 comments

Summary:

There is an issue in the ConvertTo-PodeYaml function in Pode that causes the conversion to fail if the source Hashtable or PSCustomObject contains a key named Count. This problem occurs due to the way the Count property is being checked during conversion, leading to conflicts when Count is a key in the object.

File:

  • File Name: Helper.ps1
  • Location:
    • Line 3576: if ($InputObject.Count -gt 0) {
    • Line 3602: if ($InputObject.Count -gt 0) {

Steps to Reproduce:

  1. Create a Hashtable or PSCustomObject with a key named Count.
  2. Attempt to convert the object to YAML using ConvertTo-PodeYaml.
  3. The conversion will fail due to a conflict with the Count property being treated as a method rather than a key.

Example:

$object = @{
    Count = 5
    Name = "TestObject"
}

ConvertTo-PodeYaml -InputObject $object

Root Cause:

The issue arises because the Count property is being accessed directly ($InputObject.Count), which conflicts when Count is used as a key in the Hashtable or PSCustomObject. The Count property is treated as a method in such cases, causing the conversion to fail.

Fix:

The proposed solution is to adjust the conditions to avoid using the direct Count property in situations where Count could be a key.

  1. Line 3576:

    • Current Code:
      if ($InputObject.Count -gt 0) {
      
    • Proposed Fix:
      if ($hashtable.GetEnumerator().MoveNext()) {
      
  2. Line 3602:

    • Current Code:
      if ($InputObject.Count -gt 0) {
      
    • Proposed Fix:
      if ($InputObject.PSObject.Properties.Count -gt 0) {
      

Additional Notes:

  • The fix ensures that when Count is used as a key, it will not conflict with the Count property of the object, and the conversion to YAML will work as expected.
  • The proposed fix uses .GetEnumerator().MoveNext() to check for the presence of elements in a Hashtable, and .PSObject.Properties.Count to properly count the properties in a PSCustomObject.

mdaneri avatar Oct 15 '24 12:10 mdaneri