I wonder is there some other benefits it brings when doing such explicit type casting ?
None that I can think of other than the string example shown below.
And is such type casting really needed when passing the $var1 to the downstream pipeline part ConvertTo-Json cmdlet ?
For the question being asked, you really don't need to wrap your hashtable for ConvertTo-Json to work correctly.
You're correct in that PSObject serves the purpose of an invisible wrapper. The .NET doc already describes it perfectly:
Wraps an object providing alternate views of the available members and ways to extend them. Members can be methods, properties, parameterized properties, etc.
Those members referred to in the description that could be added to a PSObject can be:
[psobject].Assembly.GetTypes() |
Where-Object { $_.IsSubclassOf([System.Management.Automation.PSMemberInfo]) }
As for alternative views they're probably referring to adding the special PSTypeName property and then assigning a formatting or extended type data, see for example: How can I set left/right column justification in Powershell's "format-table".
They could also refer to adding a PSMemberSet:
$object = [pscustomobject]@{
foo = 1
bar = 2
baz = 3
}
$propertySet = [System.Management.Automation.PSPropertySet]::new(
'DefaultDisplayPropertySet', [string[]] ('foo', 'bar'))
$object.PSObject.Members.Add(
[System.Management.Automation.PSMemberSet]::new(
'PSStandardMembers',
[System.Management.Automation.PSPropertySet[]] $propertySet))
# $object now hides `baz` property in the default display
$object
There is usually no need to wrap an object in PSObject manually, however you can do so if you want to extend that object. For example for a string, if you wrap it you could add a new property to it:
$string = [psobject] "a string"
$string.PSObject.Properties.Add([psnoteproperty]::new('NewProperty', 'hi'))
$string # still shows the actual value
$string.NewProperty # but now has a hidden property
PSObject is also the base for creating PSCustomObject:
[pscustomobject]@{ NewProperty = 'hi' }
Which is essentially a PSObject with PSNoteProperty added to it:
$acustomObject = [psobject]::new()
$acustomObject.PSObject.Properties.Add([psnoteproperty]::new('NewProperty', 'hi'))
$acustomObject
ConvertTo-Jsonwould work just fine whiteout the need to wrapping it in aPSObject. Unsure where you got that it was required