Functions/Set-ValuesFromExpressions.ps1
function Set-ValuesFromExpressions { <# .Synopsis Returns the input object populated by Expression executions .DESCRIPTION Enumerates a PSObject properties for code to run. The code to run is placed in brackets. For example "(Get-Process -Name 'NotePad')" .PARAMETER inputData Typically a PSCustomObject generated by using: Get-Content "someJsonFile.json" | ConvertFrom-Json .EXAMPLE $DriveInfo = New-Object psobject -Prop ([ordered] @{Name=((Get-PSDrive).Name); Free = ((Get-PSDrive).Free); Used = ((Get-PSDrive).Used)}) $DriveInfo2 = New-Object psobject -Prop ([ordered] @{Name="((Get-PSDrive).Name)"; Free = "((Get-PSDrive).Free)"; Used = "((Get-PSDrive).Used)"}) #$DriveInfo sames as $DriveInfo2 if piped to Set-ValuesFromExpressions $DriveInfo2 | Set-ValuesFromExpressions .EXAMPLE $json='{"paths": ["($ExecutionContext.SessionState.Path.CurrentLocation.Path + ''\\logs'')","C:\\Temp"]}' $location=$json | ConvertFrom-Json | Set-ValuesFromExpressions .Notes Prefix a value with space to use a brackets in a JSON file - "note":" (This is NOT an expression)" #> [CmdletBinding(SupportsShouldProcess = $False)] param ( [Parameter(Mandatory,ValueFromPipeline)] [PSObject]$inputData ) process { foreach($property in $inputData.psobject.properties.name) { #if ($property -eq "answer1") { # $haltOnThis="" #} #Write-Verbose ($property + ":" + $inputData.$property.GetType().Name) switch -Regex ($inputData.$property.GetType().Name) { 'Object$' { Write-Verbose ("Recurse object: " + $inputData.$property) $inputData.$property=Set-ValuesFromExpressions -inputData $inputData.$property Break } '\[\]$' { Write-Verbose ("Enum array: " + $property) for ($n=0;$n -lt $inputData.$property.count ; $n++) { Write-Verbose ("Evaluating prop: $property [" + $inputData.$property[$n].GetType().Name + "]") if ($inputData.$property[$n].GetType().Name -match "Object$") { Write-Verbose ("Recurse object: $property [$n]") $inputData.$property[$n]=Set-ValuesFromExpressions -inputData $inputData.$property[$n] } else { if ($inputData.$property[$n].GetType().Name -eq "String" -and $inputData.$property[$n].SubString(0,1) -eq '(') { Write-Verbose ("Expression: " + $inputData.$property[$n]) $inputData.$property[$n]=(Invoke-Expression -Command $inputData.$property[$n]) } } } Break } 'String' { if ($inputData.$property.SubString(0,1) -eq '(') { Write-Verbose ("Expression: " + $inputData.$property) $inputData.$property=(Invoke-Expression -Command $inputData.$property) } Break } } } return $inputData } } |