PowerShell – convert delimited record to object

Spent sometime struggling with this, so worth recording. Test. Code.

 

Advertisements

PowerShell: ConvertFrom-Json

I want to express a simple file format spec in Json format, and then ingest it into a PowerShell object.

The spec content:

And then various views in PowerShell

22 $specAsJson = Get-Content -Raw .\FileSpec.json
23 $spec = $specAsJson | ConvertFrom-Json
24 $spec
25 $spec.FriendsSpec
26 $spec.FriendsSpec.columnSet
27 $spec.FriendsSpec.columnSet.column1
28 $specAsJson.GetType()
29 $spec.GetType()

In fact on reflection those are the rules, the schema effectively… cept in Json I believe we don’t like schemas. So the spec for the Friends spec I meant… let’s call it RealFriends as I don’t intend going back:


(Note the typo ref ReaDFriends). This is more like it. With the added plus that as a first class object, we can do stuff like Count. Spec is

$specAsJson = Get-Content -Raw .\ReadFriendsSpec.json
$specAsJson
Get-History
$spec = $specAsJson | ConvertFrom-Json
$spec
$spec.FriendsSpec
$spec.FriendsSpec.Fields
$spec.FriendsSpec.Fields.Count

PowerShell: array of PSObject

This says it all, I think:

PsObject01

or here. Or Code.

$w = New-Object -TypeName PSCustomObject -Property @{numcol = [int] 13; stringCol = “the original”}
$w | Get-Member
$w
$x = New-Object -TypeName System.Management.Automation.PSCustomObject -Property @{numcol = [int] 22; stringCol = “something”}
$x | Get-Member
$x
$y = New-Object -TypeName PSObject -Property @{numcol = [int] 42; stringCol = “something additional”}
$y | Get-Member
$y.GetType().ToString()

$z = @()

$z += $w
$z += $x
$z += $y
$z[0]

$z.GetType().ToString()

$z[1] | Get-Member

$z | % { $_.stringCol }

$sum = 0
$concattedString = “”

$z | % { $sum += $_.numCol; $concattedString += “[$($_.stringCol)]” }

$sum
$concattedString