在if语句中检查$ null

时间:2019-03-24 09:52:26

标签: powershell powershell-v2.0

以下脚本在较新的Powershell版本上运行良好,但我也需要Powershell 2.0的版本。

问题似乎是我在这里不能使用if ($class.$property -eq $null),但是类似if (($class | select -expand $property) -eq $null)的东西也无法使用。

那么如何在Powershell 2.0中检查$class.$property是否是null

脚本: (我以后需要更多的值,但这显示了问题,因为我的情况下SKU为null)

function Get-Value-From-Class($class, $property) {
    if ($class.$property -eq $null) {
        # property is null
        $arr = @()

        for ($i=1; $i -le $class.count; $i++) {
            $arr += $null
        }

        return $arr
    } else {
        # property is not null
        return $class | select -expand $property
    }
}


$memory = Get-WmiObject -class Win32_PhysicalMemory
$result = @{memory = @{}}

$result.memory.capacity = Get-Value-From-Class -class $memory -property Capacity # this is not null
$result.memory.sku = Get-Value-From-Class -class $memory -property SKU # this is null here

$result | ConvertTo-Json # I know this won't work too but I have a polyfill for this

在powershell 5上的输出(就像我在2.0中一样需要它):

{
    "memory":  {
                   "sku":  [
                               null,
                               null
                           ],
                   "capacity":  [
                                    8589934592,
                                    8589934592
                                ]
               }
}

如西奥所建议:

[... code for ConvertTo-STJson ...]

function Get-Value-From-Class($class, $property) {
    if (!($class.$property)) {
        return "top"
    } else {
        return "bottom"
    }
}


$memory = Get-WmiObject -class Win32_PhysicalMemory

$result = @{memory = @{};}

$result.memory.capacity = Get-Value-From-Class -class $memory -property Capacity
$result.memory.sku = Get-Value-From-Class -class $memory -property SKU

ConvertTo-STJson -InputObject $result | Out-File .\json_output.json -Encoding utf8

这为不同的Powershell版本提供了不同的结果:

结果为2.0

{
    "memory":
    {
        "sku": "top",
        "capacity": "top"
    }
}

结果为5.1

{
    "memory":
    {
        "sku": "bottom",
        "capacity": "bottom"
    }
}

0 个答案:

没有答案