Reputation: 3521
I have a script that gets response from another script as JSON,
$resp = & ".\script1.ps1" | ConvertFrom-Json
$resp[1]
and I get the following output:
abc : 1234
defghjk: 897
klm : something12
Now i want to store those as keys/values in hashtable
$hash = @{}
$($resp[1]) | ForEach-Object {
# Split each pair into key and value
$key,$value = $_.Split(':')
# Populate $hash
$hash[$key] = $value
}
return $hash
I get the following error:
Method invocation failed because [System.Management.Automation.PSCustomObject] does not contain a method named 'Split'
and
Index operation failed; the array index evaluated to null. At $hash[$key] = $value
UPDATE: With this i am able to output the Key, Value, and Name
$resp[1].PSObject.Properties | Foreach { $hash[$_.Key] = $_.Value }
return $hash
I get back:
Key : abc
Value : 1234
Name: abc
Key : defghjk
Value : 897
Name: defghjk
and so on...
suppose i have a SQL table as follows
and I have the following query to get the ID:
$DB_ID = Query "select ID from table where DB = 'cube1'" | Select -ExpandProperty ID;
How do i get the value based on $DB_ID
match with Key/Name and store the value in a variable say $password
?
in other words, i am looking for something like this:
$password = $hash.value where $hash.key -match `$DB_ID`
so then the password in this case (cube1) would be: 1234 because the key abc would match abc from table
UPDATE2: Now that i think about it, i probably didnt even need to hash the response to begin with. mayb i can do something like this, right?:
$password = $resp[1].PSObject.Properties.value where $resp[1].PSObject.Properties.key -match $DB_ID
Upvotes: 1
Views: 682
Reputation: 21418
A PSCustomObject
is basically already keys and values, it's a proper object - it just outputs with the :
as a friendly way to display the information to you. The left side of the :
is the key and the right side is the value. If you want it to be a proper hashtable though, you'll have to do iterate over the properties like so:
$myHash = @{}
$resp[1].PSObject.Properties | Foreach { $myHash[$_.Name] = $_.Value }
The way this works is that PSCustomObject
has a PSObject
property from which you can get the properties from. Iterate over each property on the PSCustomObject
, and set the property name as a key in $myHash
, and the value of the same property as the value of that key in $myHash
.
You would access those like follows: $myHash['cube1']
and $myHash['cube2']
.
If you already know the target $DB_ID
ahead of time, and the desired returned object from that script already organizes a DB to an ID you can do this: $myHash[$DB_ID]
.
You actually don't even need to convert it to a hashtable to do that, either. You can simply use the original PSCustomObject
you converted from JSON like so:
$resp[1].$DB_ID
or $resp[1]."$DB_ID"
Upvotes: 1