首页 > 解决方案 > 在 PowerShell 脚本中解析函数返回

问题描述

我正在尝试解析来自 PowerShell 脚本中的一个函数的响应,并根据响应我必须做出一些决定。

该函数成功返回 JSON 对象,但无法解析来自该函数的响应。我需要检查有效节点计数是否为 0。

      [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
}

输出:

Response {"ValidNodes":["a1572dev00e001","a1572dev00q001"],"Invalid":[]} {"ValidNodes":["
a1572dev00e001","a1572dev00q001"],"Invalid":[]}
Parsing response 
All nodes are Invalid
Invalid Nodes: 
failed

标签: powershellpowershell-3.0powershell-4.0

解决方案


一个问题是您要输出 $Jres 两次。

Write-Output $JRes 
return $JRes

这些有效地做完全相同的事情。接下来,您在ConvertFrom-String看起来应该使用的时候使用ConvertFrom-Json

$JSON = $Response | ConvertFrom-String

最后,您尝试输出$ValidNodes并且$InvalidNodes仅存在于您的函数中。将这些更改为$JSON.ValidNodes$JSON.InvalidNodes

另一个建议是参数化节点列表,这样您就可以将节点传递给函数。

#Function
function Get-Nodes
{
    Param([string[]]$nodelist)
    $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
    $JRes 
}

$Response = Get-Nodes a1572dev00e001,a1572dev00q001

Write-Output "Response $Response"
$JSON = $Response | ConvertFrom-Json
Write-Output "Parsing response $JSON"

if($JSON.ValidNodes.Count -gt 0)
    {
            Write-Output "Valid Nodes: $($JSON.ValidNodes)"
            $Result = "success"
             
    }
    else
    {
            Write-Output "All nodes are Invalid"
            Write-Output "Invalid Nodes: $($JSON.InValidNodes)"
            $Result = "failed"
            $ErrorMessage = "All nodes are Invalid"

    }
Write-Output $Result

推荐阅读