如何在Powershell中对JSON数据执行逻辑If..then?

时间:2018-11-08 16:38:13

标签: powershell

我正在尝试遍历所需注册表值的JSON数组,然后检查注册表值的正确设置。

我的问题是我没有在循环中正确定义'if ..()'逻辑测试。问题代码位于以下行:if($protocols[$i][$tempdisabledKVString] -eq "true")

我有以下对象:

$protocolsJSON = @"
[  
   {
    "Name": "TLS 1.2",
    "Server-Enabled": True,
    "Client-Enabled": True
   }
] 
"@
$protocols = $protocolsJSON  | ConvertFrom-Json

以下哪个嵌套if语句失败(异常行为)

elseif ($isDefaultDisabled -eq 0) # Protocol is manually enabled in registry (part 1.A)
{
    if($protocols[$i][$tempdisabledKVString] -eq "True")  # Protocol should be manually enabled in registry (part 1.B)
    {
        # For TLS 1.2 to be enabled and negotiated on servers that run Windows Server 2008 R2,
        # you MUST create the DisabledByDefault entry in the appropriate subkey (Client, Server) 
        # and set it to "0". The entry will not be seen in the registry and it is set to "1" by default.
        $errorString = "Warning: Protocol is only partially enabled."
        $TLSProtocolResult.Errors = $errorString
    }
    else
    {
        write-host "DEBUG " $protocols[$i][$tempdisabledKVString]
        write-host "DEBUG " $protocols[$i] 
        write-host "DEBUG " [$tempdisabledKVString]
        $errorString = "Error: Protocol should be disabled."
        $TLSProtocolResult.Errors = $errorString
    }         
}

哪个会产生以下输出

DEBUG
DEBUG  @{Name=TLS 1.2; Server-Enabled=True; Client-Enabled=True}
DEBUG  [Server-Disabled]
DEBUG
DEBUG  @{Name=TLS 1.2; Server-Enabled=True; Client-Enabled=True}
DEBUG  [Client-Disabled]

如何编辑IF语句,以便可以测试$protocols[$i][$tempdisabledKVString]的正确/错误状态?

2 个答案:

答案 0 :(得分:2)

问题是您正在尝试像访问嵌套数组一样访问属性。

尝试一下:

$protocolsJSON = @"
[  
   {
    "Name": "TLS 1.2",
    "Server-Enabled": true,
    "Client-Enabled": true
   }
] 
"@

$protocols = $protocolsJSON  | ConvertFrom-Json

$property = "Server-Enabled"

Write-Host "RESULT: $($protocols[0].$property)"

答案 1 :(得分:0)

您的问题很可能是未解析JSON。尝试在您的价值观周围加上引号。即用"Server-Enabled": True,替换"Server-Enabled": "True",

此外,如果$tempdisabledKVString是属性的名称,则需要作为属性而不是索引来访问它。即将$protocols[$i][$tempdisabledKVString]替换为$protocols[$i]."$tempdisabledKVString"

Clear-Host
$protocolsJSON = @"
[  
   {
    "Name": "TLS 1.2",
    "Server-Enabled": "True",
    "Client-Enabled": "True"
   }
] 
"@
$protocols = $protocolsJSON  | ConvertFrom-Json
$i = 0
$tempdisabledKVString = 'Server-Enabled'
if ($protocols[$i]."$tempdisabledKVString" -eq 'True') {
    ":)"
} else {
    ":("
}

从理论上讲,这些问题应该导致引发异常。由于某些原因,您没有看到这些,或者会提示您找到原因。请检查$ErrorActionPreference的值;默认情况下,应将其设置为Continue;但您的会话似乎已更新为SilentlyContinue。在某些情况下可以使用此设置。但是通常最好在发生错误时将其引发,以便您可以查看出了什么问题。