Следующий скрипт хорошо работает на более новых версиях powershell, но мне также нужна версия для powershell 2.0.
Проблема заключается в том, что я не могу использовать if ($class.$property -eq $null)
здесь, но что-то вроде if (($class | select -expand $property) -eq $null)
не будет работать тоже.
Итак, как я могу проверить, *
есть ли
$class.$property
в powershell 2.0? *1009*
скрипт: (есть еще значения, которые мне понадобятся позже, но это показываетпроблема, потому что в моем случае SKU является нулевым)
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"
}
}