powershell - 在 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
解决方案
一个问题是您要输出 $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
推荐阅读
- c# - 如何在没有设置器的情况下设置私有变量值?
- react-hook-form - 反应钩子形式+材料ui:日期选择器没有得到初始日期
- javascript - 通过测试库中的屏幕验证 div 是否已禁用
- r - 如何指定依赖于 dplyr 中的分组变量的条件?
- git - 无法解析主机:适用于 Linux 的 Windows 子系统 (WSL) 上的 dev.azure.com
- angular-dart - 如何从子组件中读取值
- sql - 消除 sql 索引假脱机时间
- swift - SwiftUI 将 HStack 与不同大小的元素对齐
- css - 如何使用背景图像绘制网格
- python - 在python中获取一个多边形/多多边形的坐标