Alexey Nasakin
Alexey Nasakin

Reputation: 3

Convertto-Json from HashTable

I need some help. I need to export list of IIS certificates to json in next format:

{
  "Certificate.FriendlyName1":{
    "daysleft":"33"
  },
  "Certificate.FriendlyName2":{
    "daysleft":"67"
  },
  "Certificate.FriendlyName3":{
    "daysleft":"12"
  }
}

Now i am trying to use next code:

$sites = Get-Website | ? { $_.State -eq "Started" } | % { $_.Name }
$certs = Get-ChildItem IIS:SSLBindings | ? {
           $sites -contains $_.Sites.Value
         } | % { $_.Thumbprint }

$certificate = Get-ChildItem CERT:LocalMachine/My | ? {
  $certs -contains $_.Thumbprint
}
   $data = [PsCustomObject]@{

    $certificate.FriendlyName     = @{
                               daysleft = ($certificate.NotAfter).subtract([DateTime]::Now).days}
   }

Convertto-json $data

But getting a next output

{
    "System.Object[]":  {
                            "daysleft":  [
                                             1775,
                                             574
                                         ]
                        }
}

How to get data from Hashtable variable like members of Array in JSON-output? Thank You.

Upvotes: 0

Views: 165

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174690

You need to add each certificate entry one-by-one:

# grab the matching certificates
$certificates = Get-ChildItem CERT:LocalMachine/My | ? {
  $certs -contains $_.Thumbprint
}

# create hashtable to hold the data
$data = @{}

foreach($certificate in $certificates){
    # add each cert one by one
    $data[$certificate.FriendlyName] = @{
        daysleft = $certificate.NotAfter.Subtract([DateTime]::Now).days
    }
}

ConvertTo-Json $data

Upvotes: 2

Related Questions