I am trying to parse the response from one of the functions in PowerShell Script and based on the response I have to make some decision.
The function is returning JSON object successfully but not able to parse the response from the function. I need to check if validnodes count is 0 or not.
[String[]] $NodeList = 'a1572dev00e001','a1572dev00q001'
$Response = Get-Nodes
Write-Output "Response $Response"
$JSRes = $Response | ConvertFrom-Json
Write-Output "Parsing response $JSRes"
#$Result = "success"
if($JSRes.ValidNodes.Count -gt 0)
{
Write-Output "$JSRes.ValidNodes"
$Result = "success"
}
else
{
Write-Output "All nodes are Invalid"
Write-Output "Invalid Nodes: $JSRes.Invalid"
$Result = "failed"
$ErrorMessage = "All nodes are Invalid"
}
Write-Output $Result
#Function
function Get-Nodes
{
$ValidNodes=@()
$InvalidNodes=@()
foreach($Node in $NodeList)
{
if(Get-ADComputer -filter {Name -eq $Node})
{
$ValidNodes +=$Node
}
else
{
$InvalidNodes +=$Node
}
}
$JRes = @{"ValidNodes"=$ValidNodes;"Invalid"=$InvalidNodes} | ConvertTo-Json -Compress
Write-Output $JRes
return $JRes
}
Output:
Response {"ValidNodes":["a1572dev00e001","a1572dev00q001"],"Invalid":[]} {"ValidNodes":["
a1572dev00e001","a1572dev00q001"],"Invalid":[]}
Parsing response
All nodes are Invalid
Invalid Nodes:
failed
$JSON = $Response | ConvertFrom-String->$JSON = $Response | ConvertFrom-Json. I would suggest renaming$JSONto something else - it's no longer json :)