title: How to exclude non-valued object properties when converting to JSON in Powershell
body: <p>I have a piece of code that works but I want to know if there is a better way to do it. I could not find anything related so far. Here are the facts:</p>
  
  <ul>
  <li>I have an object with n properties.</li>
  <li>I want to convert this object to JSON using (ConvertTo-Json).</li>
  <li>I don't want to include in the JSON those object properties that are not valued. </li>
  </ul>
  
  <blockquote>
    <p>Building the object (not really important):</p>
  </blockquote>
  
  <pre><code>$object = New-Object PSObject
  Add-Member -InputObject $object -MemberType NoteProperty -Name TableName -Value "MyTable"
  Add-Member -InputObject $object -MemberType NoteProperty -Name Description -Value "Lorem ipsum dolor.."
  Add-Member -InputObject $object -MemberType NoteProperty -Name AppArea -Value "UserMgmt"
  Add-Member -InputObject $object -MemberType NoteProperty -Name InitialVersionCode -Value ""
  </code></pre>
  
  <blockquote>
    <p>The line that I need improvements (to filter out the non-valued properties and not include them in the JSON)</p>
  </blockquote>
  
  <pre><code># So I want to 'keep' and deliver to the JSON only the properties that are valued (first 3).
  $object | select -Property TableName, Description, AppArea, InitialVersion | ConvertTo-Json
  </code></pre>
  
  <blockquote>
    <p>What this line delivers:</p>
  </blockquote>
  
  <pre><code>Results:
  {
      "TableName":  "MyTable",
      "Description":  "Lorem ipsum dolor..",
      "AppArea":  "UserMgmt",
      "InitialVersion":  null
  }
  
  What I want to obtain:
  {
      "TableName":  "MyTable",
      "Description":  "Lorem ipsum dolor..",
      "AppArea":  "UserMgmt"
  }
  </code></pre>
  
  <blockquote>
    <p>What I've tried and works, but I don't like it since I have much more properties to handle: </p>
  </blockquote>
  
  <pre><code>$JSON = New-Object PSObject
  
  if ($object.TableName){
     Add-Member -InputObject $JSON -MemberType NoteProperty -Name TableName -Value $object.TableName
  }
  
  if ($object.Description){
     Add-Member -InputObject $JSON -MemberType NoteProperty -Name Description -Value $object.Description
  }
  
  if ($object.AppArea){
     Add-Member -InputObject $JSON -MemberType NoteProperty -Name AppArea -Value $object.AppArea
  }
  
  if ($object.InitialVersionCode){
     Add-Member -InputObject $JSON -MemberType NoteProperty -Name InitialVersionCode -Value $object.InitialVersionCode
  }
  
  $JSON | ConvertTo-Json
  </code></pre>