Home > Net >  PowerShell 51 function not displaying expected ouput
PowerShell 51 function not displaying expected ouput

Time:01-16

I'm testing deserializing and splatting but not getting expected output from function Function1

Deserializing (not working as expected)

$pick1 = 'red,blue' -split ","
$favoriteColors = @()
$favoriteColors  = $pick1

$payload = @{}
$payload.add('DEV',@{firstName='Rod';favoriteColors=$favoriteColors})

# Serialize 
$serialPayload = $payload | ConvertTo-Json -compress

# Deserialize test
$payload2 = @{}
(ConvertFrom-Json $serialPayload).psobject.properties | Foreach { $payload2[$_.Name] = $_.Value }

function Main(){
  $test = $payload2['DEV']
  Function1 @test
}
function Function1([object] $favoriteColors){
  "Value1: $($favoriteColors)"
}

Main

I was expecting:

"red,blue" string

But I'm getting the entire payload2['DEV'] object, not what I expected from splatting.

Value1: @{favoriteColors=System.Object[]; firstName=Rod} 

Without serializing (works as expected)

$pick1 = 'red,blue' -split ","
$favoriteColors = @()
$favoriteColors  = $pick1

$payload = @{}
$payload.add('DEV',@{firstName='Rod';favoriteColors=$favoriteColors})

function Main(){

  $test = $payload['DEV']
  Function1 @test
}
function Function1([object] $favoriteColors){
  "Value: $($favoriteColors)"
}

Main

Output:

Value: red blue

CodePudding user response:

I had to reserialize then deserialize, feedback?

$pick1 = 'red,blue' -split ","
$favoriteColors = @()
$favoriteColors  = $pick1

$pick2 = 'green,yellow' -split ","
$favoriteColors2 = @()
$favoriteColors2  = $pick2

$payload = @{}
$payload.add('DEV',@{firstName='Rod';favoriteColors=$favoriteColors})
$payload.add('UAT',@{firstName='Char';favoriteColors=$favoriteColors2})

# Serialize 
$serialPayload = $payload | ConvertTo-Json -compress

# Deserialize test
$payload2 = @{}
(ConvertFrom-Json $serialPayload).psobject.properties.Value.psobject.Properties | Foreach { $payload2[$_.Name] = $_.Value }

function Main(){

  Function1 @payload2
}
function Function1([object] $favoriteColors){
  "Value1: $($favoriteColors)"
}

Main
  • Related