Reputation: 557
Please excuse my complete ineptness when it comes to using powershell. I'm not really a windows guy and I've found myself in a sticky situation. What I need to do is use a json config file named optionsConfig.json
that contains a dict and based off whatever key I have, I assume that the elements in the list (value for that key) are environment variables on the system and I need to find their values. Here are the config contents.
{"test1": ["options_size", "options_connection", "options_object"],
"test2":["options_customArgs", "options_noUDP", "options_noName"]}
In this example I'll say,
$env:options_size = 'size1'
$env:options_connection = 'conn1'
$env:options_object = 'obj1'
I know that I will have an environment variable on the system called test
and value of that will be some key in the json object. Here is what I have so far.
# Read the JSON file into a custom object.
$configObj = Get-Content -Raw C:\TestWare\carstenSample\optionsConfig.json |
ConvertFrom-Json
# Retrieve the environment variables whose
# names are listed in the $env:test property
# as name-value pairs.
Get-Item -Path env:* -Include $configObj.$env:testTool
Also, this code will convert the environment variables to Json but in a form that I do not prefer
Get-Item -Path env:* -Include $configObj.$env:testTool |
Select-Object Name, Value | ConvertTo-Json
Here is the output
[
{
"Name": "options_connection",
"Value": "conn1"
},
{
"Name": "options_object",
"Value": "obj1"
},
{
"Name": "options_size",
"Value": "size1"
}
]
Is there a way when I can modify that Json or is their a different way to convert these env variables to json so my json object can look like this? Any help would be appreciated. Thanks
{
"options_size": "size1",
"options_connection": "conn1",
"options_object": "obj1"
}
Upvotes: 0
Views: 147
Reputation: 9143
I managed to convert your example to self-test-one. Here are the results:
#your options
$env:options_size = 'size1'
$env:options_connection = 'conn1'
$env:options_object = 'obj1'
#your key in configuration
$env:testTool = "test1"
#your configuration (in memory to simplify)
$configObj = '{"test1": ["options_size", "options_connection", "options_object"],
"test2":["options_customArgs", "options_noUDP", "options_noName"]}' | ConvertFrom-Json
#convert object to hashtable
Get-Item -Path env:* -Include $configObj.$env:testTool |
% {$hash = @{}} {$hash[$_.Name]=$_.Value} {$hash} | ConvertTo-Json
Nicely formatted JSON is returned:
{
"options_size": "size1",
"options_object": "obj1",
"options_connection": "conn1"
}
Upvotes: 3