Home > OS >  Powershell - iterating through json file
Powershell - iterating through json file

Time:02-15

my json file looks like this:

[
    {
        "OU":  "ABC",
        "OUDN":  "OU=x,OU=x,DC=x,DC=x,DC=x"
    },
    {
        "OU":  "XYZ",
        "OUDN":  "OU=x,OU=x,DC=x,DC=x,DC=x"
]

"OU" is the name of an AD Organizational Unit

"OUDN" is the associated DistinguishedName of the AD Organizational Unit

I want to get the description (AD-Attribute) of every Organizational Unit in the json File:

Get-ADOrganizationalUnit -Identity "DistinguishedName of the OU"|FT description

How can I do that? How can I iterate through my json file?

My approach:

$OU = (Get-Content -path "C:\file.json"|ConvertFrom-JSON).OU
$OUDN = (Get-Content -path "C:\file.json"|ConvertFrom-JSON).OUDN

foreach ($item in $OU) {
Get-ADOrganizationalUnit -Identity ????? }

THANK YOU SO MUCH!

CodePudding user response:

You're very close, you can iterate over the elements of the Json object with the foreach loop as you're already doing it:

$json = Get-Content 'C:\file.json' | ConvertFrom-Json

$ous = foreach($item in $json) {
    Get-ADOrganizationalUnit $item.OUDN -Properties Description
}

$ous | Select-Object Name, Description

Note that you don't need to Get-Content two times for each property, each object of your Json holds the values of the two properties (OU and OUDN):

PS /> $json[0]

OU  OUDN
--  ----
ABC OU=x,OU=x,DC=x,DC=x,DC=x

PS /> $json[0].OUDN

OU=x,OU=x,DC=x,DC=x,DC=x
  • Related