Skip to content

PowerShell should be better able to reveal developer information on an unknown object #17701

Closed

Description

@iRon7

Summary of the new feature / enhancement

PowerShell Write-* cmdlets are sending information to the related output streams which (all?) are eventually displaying information in a way the end-user would probably prefer to receive it but as a script developer, the way this is displayed is often misleading.

For a new PowerShell scripter, a known pitfall is the object enrolment were is unclear what type is actually being output from the pipeline in the case of a single item.
And there are a lot of different object types that all show the same "empty" result as e.g. '', $Null, @(), @(''), @($Null),@($Null, ''),

See e.g. #17683 $null should be indicated by a blank line, especially when within an array.

Proposed technical implementation details (optional)

It would be nice if e.g. the Write-Debug cmdlet would an addition -Object parameter that reveals developer information about a specific object.

Currently, any argument other than a string provided to the Write-Object cmdlet results in an error:

$Name  = 'John', 'Doe'
Write-Debug $Name

Write-Debug: Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'Message'. Specified method is not supported.

What I would like to see instead (as a developer), is a formatted object that doesn't leave any room for misinterpretation (e.g. the same way as it is required to be formatted for the PowerShell engine)

Wishful thinking:

$Name  = 'John', 'Doe'
Write-Debug $Name
'John',
'Doe'
$Name  = $Null
Write-Debug $Name
$Null
$Name  = ''
Write-Debug $Name
''
$Name  = @()
Write-Debug $Name
@()
$Name  = @('', $Null)
Write-Debug $Name
@('', $Null)

This could go as deep as something prototyped here: ConvertTo-Expression which definitely doesn't make it an easy request.

Activity

  1. added
    Issue-Enhancement
    Needs-Triage
    on Jul 18, 2022
  2. changed the title [-]`Write-Debug` should be able to reveal developer information on a object[/-] [+]`Write-Debug` should be able to reveal developer information on a PowerShell object[/+] on Jul 18, 2022
  3. fMichaleczek commented on Jul 20, 2022

    @fMichaleczek
    Contributor

    I think you are asking for new Format-* cmdlets.

    Format-Hex is nice for string, char and valuetype, but not good with null

    Format-Custom is nice with object, hashtable and collections.

    A command Format-Pretty should be a good feature.

    PS C:\> $Name  = 'John', 'Doe'
    PS C:\> $Name | Format-Hex
    
       Label: String (System.String) <4BDBB0C1>
    
              Offset Bytes                                           Ascii
                     00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
              ------ ----------------------------------------------- -----
    0000000000000000 4A 6F 68 6E                                     John
    
       Label: String (System.String) <4A3432CE>
    
              Offset Bytes                                           Ascii
                     00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
              ------ ----------------------------------------------- -----
    0000000000000000 44 6F 65                                        Doe
    
    PS C:\> (Get-UICulture).Calendar | Format-Custom -Depth 1
    
    class GregorianCalendar
    {
      MinSupportedDateTime =
        class DateTime
        {
          Date = 1/1/0001 00:00:00
          Day = 1
          DayOfWeek = Monday
          DayOfYear = 1
          Hour = 0
          Kind = Unspecified
          Millisecond = 0
          Microsecond = 0
          Nanosecond = 0
          Minute = 0
          Month = 1
          Second = 0
          Ticks = 0
          TimeOfDay = 00:00:00
          Year = 1
          DateTime = Monday, January 1, 0001 00:00:00
        }
      MaxSupportedDateTime =
        class DateTime
        {
          Date = 12/31/9999 00:00:00
          Day = 31
          DayOfWeek = Friday
          DayOfYear = 365
          Hour = 23
          Kind = Unspecified
          Millisecond = 999
          Microsecond = 999
          Nanosecond = 900
          Minute = 59
          Month = 12
          Second = 59
          Ticks = 3155378975999999999
          TimeOfDay = 23:59:59.9999999
          Year = 9999
          DateTime = Friday, December 31, 9999 23:59:59
        }
      AlgorithmType = SolarCalendar
      CalendarType = Localized
      Eras =
        [
          1
        ]
    
      TwoDigitYearMax = 2029
      IsReadOnly = True
    }

    The base serialization is CliXml, if you want to import/export object, you could export and display CliXml.

    PS>  (Get-UICulture).Calendar | Export-CliXml -Path $env:TMP/cal.clixml -Depth 1 -Force
    PS> Get-Content -Path "$env:TMP/cal.clixml"
    <Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">
      <Obj RefId="0">
        <TN RefId="0">
          <T>System.Globalization.GregorianCalendar</T>
          <T>System.Globalization.Calendar</T>
          <T>System.Object</T>
        </TN>
        <ToString>System.Globalization.GregorianCalendar</ToString>
        <Props>
          <DT N="MinSupportedDateTime">0001-01-01T00:00:00</DT>
          <DT N="MaxSupportedDateTime">9999-12-31T23:59:59.9999999</DT>
          <S N="AlgorithmType">SolarCalendar</S>
          <S N="CalendarType">Localized</S>
          <Obj N="Eras" RefId="1">
            <TN RefId="1">
              <T>System.Int32[]</T>
              <T>System.Array</T>
              <T>System.Object</T>
            </TN>
            <LST>
              <I32>1</I32>
            </LST>
          </Obj>
          <I32 N="TwoDigitYearMax">2029</I32>
          <B N="IsReadOnly">true</B>
        </Props>
      </Obj>
    </Objs>
    
    PS> Import-Clixml  -Path "$env:TMP/cal.clixml"
    
    MinSupportedDateTime : 1/1/0001 00:00:00
    MaxSupportedDateTime : 12/31/9999 23:59:59
    AlgorithmType        : SolarCalendar
    CalendarType         : Localized
    Eras                 : {1}
    TwoDigitYearMax      : 2029
    IsReadOnly           : True
    
  4. iRon7 commented on Jul 20, 2022

    @iRon7
    Author

    Flavien MICHALECZEK (@fMichaleczek),

    I think you are asking for new Format-* cmdlets.

    I guess that is indeed close to what I would like to see, but I do not want to predefine the <noun> in the the Format-* cmdlet as I have no clue what is in the object in advance (or what went wrong in my script). Take e.g. the StackOverflow questions concerning "You cannot call a method on a null-valued expression". The developers, get a clear error but are still not able to understand the cause of the issue. This is to my opinion because the standard display outputs are generally designed for the end-users (and not for the developers¹). In these outputs there is no easy way to distinguish between a $Null and objects as '', @(), @(''), @($Null) and @($Null, ''). Besides objects are quite flat in the end-users output where it gets even more vague determine value and the type of a property, e.g. $Object.Property.Method(), where the Property might be unexpectedly $Null or something else then imagined.

    1) Also knowing that there aren't always sophisticated source code editors available in environments as production

    Take the linked issue #17683 $null should be indicated by a blank line, especially when within an array as a example, as a developer I would like to be able to reveal the cause what happend here:

    $a = $Null, 1
    $a
    1
    ConvertTo-Expression $a # Could be any statement/cmdlet or even a kind of developer mode
    $Null,
    1

    Also take the very specific bug(?), I recently reported here: #17702 The last cell of an empty column read by ConvertFrom-Csv is inconsistently $Null. How would anyone able to easily reveal this?

    $Data = ConvertFrom-Csv @'
    Id,Name,Note
    01,John,
    02,Jack,
    03,Ryan,Just a note
    04,Luke,
    05,Noah,
    '@
    
    ConvertTo-Expression $Data # Could be any statement/cmdlet or even a kind of developer mode
    [pscustomobject]@{
        Id = '01'
        Name = 'John'
        Note = ''
    },
    [pscustomobject]@{
        Id = '02'
        Name = 'Jack'
        Note = ''
    },
    [pscustomobject]@{
        Id = '03'
        Name = 'Ryan'
        Note = 'Just a note'
    },
    [pscustomobject]@{
        Id = '04'
        Name = 'Luke'
        Note = ''
    },
    [pscustomobject]@{
        Id = '05'
        Name = 'Noah'
        Note = $Null      # <-- here is the issue
    }
    

    I indeed could also have used PSSerializer.Serialize Method for this:

    [System.Management.Automation.PSSerializer]::Serialize($Data)
    <Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">
      <Obj RefId="0">
        <TN RefId="0">
          <T>System.Object[]</T>
          <T>System.Array</T>
          <T>System.Object</T>
        </TN>
        <LST>
          <Obj RefId="1">
            <TN RefId="1">
              <T>System.Management.Automation.PSCustomObject</T>
              <T>System.Object</T>
            </TN>
            <MS>
              <S N="Id">01</S>
              <S N="Name">John</S>
              <S N="Note"></S>
            </MS>
          </Obj>
          <Obj RefId="2">
            <TNRef RefId="1" />
            <MS>
              <S N="Id">02</S>
              <S N="Name">Jack</S>
              <S N="Note"></S>
            </MS>
          </Obj>
          <Obj RefId="3">
            <TNRef RefId="1" />
            <MS>
              <S N="Id">03</S>
              <S N="Name">Ryan</S>
              <S N="Note">Just a note</S>
            </MS>
          </Obj>
          <Obj RefId="4">
            <TNRef RefId="1" />
            <MS>
              <S N="Id">04</S>
              <S N="Name">Luke</S>
              <S N="Note"></S>
            </MS>
          </Obj>
          <Obj RefId="5">
            <TNRef RefId="1" />
            <MS>
              <S N="Id">05</S>
              <S N="Name">Noah</S>
              <Nil N="Note" />
            </MS>
          </Obj>
        </LST>
      </Obj>
    </Objs>

    But that method is not easily available, requires knowledge of xml and the specific PowerShell schema (understanding what e.g. the Nil tag means) and quiet difficult to read for a human.

    Basically: to talk to the PowerShell engine, I am required to "speak PowerShell".
    As a developer, while debugging, I would like to see the engine to be able to respond back in PowerShell language.

    As said before, I realize that a PowerShell language serializer is not build without fight (taking issues along with cycled properties and lose of fidelity in account) but at the other hand, I think that I have proven with the ConvertTo-Expression script isn't entirely impossible. Besides there are other leverages apart from debugging, a PowerShell language serializer lets you easily round-trip objects and could therefore be useful in building Pester scripts, DSC and to create a Minimal, Reproducible Examples.

  5. changed the title [-]`Write-Debug` should be able to reveal developer information on a PowerShell object[/-] [+]PowerShell should be better able to reveal developer information on an unknown object[/+] on Jul 20, 2022
  6. iRon7 commented on Jul 21, 2022

    @iRon7
    Author

    # Could be any statement/cmdlet or even a kind of developer mode

    Second thoughts: I think this should actually controlled from a kind of SupportsDebugging cmdlet binding attribute which would than also partly cover the pitfall mentioned in #15781 Strict Write-Output.

    Meaning if the SupportsDebugging attribute is supplied to an advanced function and the concerned function is invoked with the common -Debug parameter, the objects at the end of the success stream will displayed in PowerShell notation rather than end-user strings.

    This would imply that most existing cmdlets (that produce objects) might support this SupportsDebugging attribute as well in the future. But write-* cmdlets should specifically be excluded (except for maybe Write-Output which -afaik- in fact eventually handles the display output at the end of the pipeline)

    Wishful thinking:

    function MyScript {
        [CmdletBinding(SupportsDebugging=$True)]
        Param( 
        )
    
        Param ($Parameter1)
        Begin{}
        Process{
            $a = ConvertFrom-JSON "[]" # https://github.com/PowerShell/PowerShell/issues/16548
            $a
        }
        End{}
    }
    
    MyScript
    
    MyScript -Debug
    $Null
  7. added
    WG-Engine
    on Jul 21, 2022
  8. rkeithhill commented on Aug 23, 2022

    @rkeithhill
    Collaborator

    WG-Engine discussed this today (8/22/2022).

    Such a feature (Format-Pretty|Debug|All|???) would be a good candidate for a community-supplied PowerShell module. We're not sure using the -Debug parameter would be appropriate since that simply enables Write-Debug messages to go to the Debug stream. Those do not go to the Output stream.

  9. added
    Resolution-Declined
    and removed
    Needs-Triage
    on Aug 23, 2022
  10. ghost closed this as completedon Aug 24, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Issue-EnhancementResolution-DeclinedWG-Engine

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions