Pass null instead of double quotes in Powershell ConvertTo-Json

robcool 96 Reputation points
2022-08-17T05:25:49.043+00:00

I'm passing a value to my JSON body for Invoke-RestMethod via PowerShell

Instead of passing null it passes "" as below:

$usermail = $null | ConvertTo-Json

I'm expecting $usermail to be null but instead its appearing as ""

Please let me know if there is any workaround as my POST method to Graph API fails as a result of bad request due to double quotes. Its expecting value as null instead.

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,389 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Rich Matheisen 45,096 Reputation points
    2022-08-17T18:28:38.333+00:00

    This won't work: $usermail = $null | ConvertTo-Json

    The variable "$usermail" is assigned a value of $null. Then $usermail is (supposed to be) passed into the pipe. But a $null value is never passed into a pipe. Because there's nothing in the pipe the "ConvertTo-Json" is never executed.

    Does this produce what you were expecting?

    [PSCustomObject]@{usermail=$null} | ConvertTo-Json  
    {  
        "usermail":  null  
    }  
    
    1 person found this answer helpful.