简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM