title: Powershell sort PSObject alphabetically
body: <p>Given a custom powershell object (bar) that is created from json (foo.json)</p>
  
  <p>How would you sort the object alphabetically by key?</p>
  
  <pre><code>foo.json
  {
    "bbb": {"zebras": "fast"},
    "ccc": {},
    "aaa": {"apples": "good"}
  }
  </code></pre>
  
  <p>Desired output</p>
  
  <pre><code>foo.json
  {
    "aaa": {"apples": "good"},
    "bbb": {"zebras": "fast"},
    "ccc": {}
  }
  </code></pre>
  
  <p>Example</p>
  
  <pre><code>$bar = get-content -raw foo.json | ConvertFrom-Json  
  $bar.gettype()  
  
  IsPublic IsSerial Name                                     BaseType
  -------- -------- ----                                     --------
  True     False    PSCustomObject                           System.Object
  </code></pre>
  
  <p>I've tried the following using <a href="https://technet.microsoft.com/en-us/library/ee176968.aspx?f=255&amp;MSPPError=-2147217396" rel="nofollow noreferrer">sort-object</a></p>
  
  <p><code>$bar = $bar | Sort</code><br>
  <code>$bar = $bar | Sort-Object</code><br>
  <code>Sort-Object -InputObject $bar</code><br>
  <code>Sort-Object -InputObject $bar -Property Name</code><br>
  <code>Sort-Object -InputObject $bar -Property @{Expression="Name"}</code><br>
  <code>Sort-Object -InputObject $bar -Property @{Expression={$_.PSObject.Properties.Name}}</code>  </p>
  
  <p>I've also tried converting the PSObject to a hashtable (hashtables appear to automatically sort based on name), then convert that hashtable back to json, but it looses the order again. </p>
  
  <pre><code>$buzz = @{}
  $bar.psobject.properties |Foreach { $buzz[$_.Name] = $_.Value }
  ConvertTo-Json $buzz -Depth 9
  </code></pre>
  
  <p><strong>Update</strong><br>
  Changed foo.json to include values aswell as keys</p>