Share via

Creating a variable in PowerShell with complex value

jansi rani krishnan 601 Reputation points
Jun 15, 2021, 7:33 PM

Hi Experts,

I would like to create a variable in PowerShell with value as below.

![105951-image.png][1]

Is it possible to create a variable which holds the value as below in PowerShell? Please suggests. If yes, Please show the syntax.
![105952-image.png][2]

Regards,
Jansi

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,628 questions
{count} votes

Accepted answer
  1. Andreas Baumgarten 119.5K Reputation points MVP
    Jun 15, 2021, 7:47 PM

    Hi @jansi rani krishnan ,

    could you please post the code as code and not as a screenshot.
    It's really time consuming to write all the stuff from the screenshot. Copy&Paste is much easier.
    Please try this:

     $a = '"RunbookId":"11212313",  
     "Parameters":"<Data><Parameter><Name>Urgency</Name><ID>{121242342342}</ID><Value>High</Value></Parameter></Data>"'  
    

    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards
    Andreas Baumgarten


2 additional answers

Sort by: Most helpful
  1. Michael Taylor 58,126 Reputation points
    Jun 15, 2021, 7:55 PM

    Yes. Depends on what you intend to do with it though as to how you do it. In most cases just use a hashtable in PS.

    $JSONBody = @{ RunbookId = '1234'; Parameters = '<xml></xml>' }   
    $JSONBody | Get-Member
    

    However if you are really working with JSON then PS supports conversion to and from already. Normally you get JSON as a string from some API. PS can convert that string to a PS object.

    # From some API
    $json = '{ "RunbookId": "1234", "Parameters": "<xml></xml>" }'
    $data = ConvertFrom-Json $json   
    $data | Get-Member
    

  2. Ian Xue-MSFT 41,616 Reputation points Microsoft External Staff
    Jun 16, 2021, 4:25 AM

    Hi,

    Please post your code using the Ctrl-K tool. You can try the ConvertFrom-Json cmdlet to convert the JSON string to a variable.

    $JsonBody='  
    {  
    "ID": "e8d-a0c",  
    "Parameter": "<Data><Name>{226-91c}</Name></Data>"  
    }'  
    $var = $JsonBody | ConvertFrom-Json  
    

    Best Regards,
    Ian Xue

    ============================================

    If the Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.