Home > front end >  PowerShell: How can I output a hashtable as json and store it in a variable using a foreach loop?
PowerShell: How can I output a hashtable as json and store it in a variable using a foreach loop?

Time:09-21

I'm trying to write a script that interacts with a Rest API to make changes in active directory (I know that doesn't make a lot of sense, but it's how our company does things). The change is to modify the homeDirectory attribute of a list of users belonging to a specific security group. The user's aren't all in the same domain, but are in the same forest and are registered in the global catalog.

So far, this is what I have that works:

function get-groupusers{
$memberlist = get-adgroup -filter "name -eq 'group.users'" -server "server.domain.com" -property member |select -expandproperty member
$GlobalCatalog = Get-ADDomainController -Discover -Service GlobalCatalog
foreach ($member in $memberlist){
get-aduser -identity $member -server "$($GlobalCatalog.name):3268"
  }
}
$sAMAccountName = (get-groupusers).samaccountname

This is the part I'm running into problems with:

foreach($an in $SamAccountName){
$json = @{
  input = @{
    key = "homeDirectory"
    value = "\\filepath\$an"
    }
  }
}

The goal here, is to convert the hashtables into json (the required format for interacting with the API), and save it in the following format (note, the "input" "key" and "value" keys are all what the API actually uses, not just substitutions):

{
  "input":{
           "key":"homeDirectory",
           "value":"\\\\filepath\\$an"
          },
          {
           "key":"homeDirectory",
           "value":"\\\\filepath\\$an"
          }
}

But right now, the foreach loop just overwrites the $json variable with the last set of hashtables. The loop is iterating over the list correctly, as I can put a convertto-json|write-host cmdlet in it but then the $an variable outputs as "@(samaccountname="$an") instead of just whatever the $an actually is.

CodePudding user response:

If my guess is right and you want a resulting Json as the one shown in your question (with the exception that, as mclayton stated in comments, the input property value should be wrapped in [...] to be an array) then this should do it:

$json = @{
    input = @(
        foreach($an in $SamAccountName) {
            [ordered]@{
                key   = "homeDirectory"
                value = "\\filepath\$an"
            }
        }
    )
}

$json | ConvertTo-Json -Depth 99
  • Related