Check for $null in if statementPowershell: Get-Process Returns “Invalid” VM SizeHow to dynamically define a class in C# PowerShell CmdletRename computer and join to domain in one step with PowerShellHow do I get total physical memory size using PowerShell without WMI?Powershell: Dynamically Convert Get-WMIObject to PSObjectPowershell - RPC, OBJ Null and -Replace ERRORS in MySQL insert querywin32_physicalMemory.Capacity returns null in powershell.count in multiple powershell versionsGet total amount of memory on NUMA systems in PowershellFiltering Get-WmiObject Class Property Output to include only value

Adding strings in lists together

Get LaTeX form from step by step solution

Can an old DSLR be upgraded to match modern smartphone image quality

Rotated Position of Integers

Is it possible to kill all life on Earth?

Why is there a need to modify system call tables in linux?

If I create magical darkness with the Silent Image spell, can I see through it if I have the Devil's Sight warlock invocation?

Infinitely many hats

Term for checking piece whose opponent daren't capture it

Team member doesn't give me the minimum time to complete a talk

Can a helicopter mask itself from Radar?

Is a hash a zero-knowledge proof?

Are UK pensions taxed twice?

Draw a checker pattern with a black X in the center

How can I grammatically understand "Wir über uns"?

Could I be denied entry into Ireland due to medical and police situations during a previous UK visit?

What is game ban VS VAC ban in steam?

chmod would set file permission to 000 no matter what permission i try to set

Different PCB color ( is it different material? )

Humans meet a distant alien species. How do they standardize? - Units of Measure

How do I subvert the tropes of a train heist?

Hiker's Cabin Mystery | Pt. IX

Did airlines fly their aircraft slower in response to oil prices in the 1970s?

Expenditure in Poland - Forex doesn't have Zloty



Check for $null in if statement


Powershell: Get-Process Returns “Invalid” VM SizeHow to dynamically define a class in C# PowerShell CmdletRename computer and join to domain in one step with PowerShellHow do I get total physical memory size using PowerShell without WMI?Powershell: Dynamically Convert Get-WMIObject to PSObjectPowershell - RPC, OBJ Null and -Replace ERRORS in MySQL insert querywin32_physicalMemory.Capacity returns null in powershell.count in multiple powershell versionsGet total amount of memory on NUMA systems in PowershellFiltering Get-WmiObject Class Property Output to include only value






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















The following script works well on newer powershell versions but I also need a version for powershell 2.0.



The problem seems to be that I can't use if ($class.$property -eq $null) here, but something like if (($class | select -expand $property) -eq $null) won't work too.



So how can I check if $class.$property is null in powershell 2.0?



script:
(there are more values I need later, but this shows the problem because SKU is null in my case)



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


output on powershell 5 (and like I would need it in 2.0 also):




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





As Theo suggested:



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


This gives different results für different powershell versions:



result with 2.0




"memory":

"sku": "top",
"capacity": "top"




result with 5.1




"memory":

"sku": "bottom",
"capacity": "bottom"











share|improve this question



















  • 1





    You should test with if (!($class.$property)) instead of testing for equality with $null. Then, as you already know, in PowerShell version 2, there is no ConvertTo-Json. If you do need that, I suggest you look for modules on the internet like perhaps ConvertTo-STJson

    – Theo
    Mar 24 at 11:18







  • 2





    Also, if you specifically want to check for $null, it is best to put the $null on the lefthand side of the equasion. See Null comparison demystified

    – Theo
    Mar 24 at 11:23











  • Thank you @Theo but this behaves different on different versions of powershell. I edited the question to show you what I mean. Any idea why this happens?

    – Michon
    Mar 24 at 13:28






  • 2





    When testing, using this syntax if (!($class[$property])) seems to return the same results in PS 5.1 and PS 2.0. However, the returned value for Get-WmiObject -Class Win32_PhysicalMemory is an array while your function Get-Value-From-Class does not deal with arrays. In this case send it the index of one item in the array (Get-Value-From-Class -class $memory[0]) or adapt your function to handle arrays of objects. As an aside, to get the total physical memory in GB, you can use (Get-WmiObject Win32_PhysicalMemory | Measure-Object Capacity -sum).sum / 1GB

    – Theo
    Mar 24 at 15:12












  • @Theo You're absolutely right, thank you.

    – Michon
    Mar 26 at 10:28

















0















The following script works well on newer powershell versions but I also need a version for powershell 2.0.



The problem seems to be that I can't use if ($class.$property -eq $null) here, but something like if (($class | select -expand $property) -eq $null) won't work too.



So how can I check if $class.$property is null in powershell 2.0?



script:
(there are more values I need later, but this shows the problem because SKU is null in my case)



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


output on powershell 5 (and like I would need it in 2.0 also):




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





As Theo suggested:



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


This gives different results für different powershell versions:



result with 2.0




"memory":

"sku": "top",
"capacity": "top"




result with 5.1




"memory":

"sku": "bottom",
"capacity": "bottom"











share|improve this question



















  • 1





    You should test with if (!($class.$property)) instead of testing for equality with $null. Then, as you already know, in PowerShell version 2, there is no ConvertTo-Json. If you do need that, I suggest you look for modules on the internet like perhaps ConvertTo-STJson

    – Theo
    Mar 24 at 11:18







  • 2





    Also, if you specifically want to check for $null, it is best to put the $null on the lefthand side of the equasion. See Null comparison demystified

    – Theo
    Mar 24 at 11:23











  • Thank you @Theo but this behaves different on different versions of powershell. I edited the question to show you what I mean. Any idea why this happens?

    – Michon
    Mar 24 at 13:28






  • 2





    When testing, using this syntax if (!($class[$property])) seems to return the same results in PS 5.1 and PS 2.0. However, the returned value for Get-WmiObject -Class Win32_PhysicalMemory is an array while your function Get-Value-From-Class does not deal with arrays. In this case send it the index of one item in the array (Get-Value-From-Class -class $memory[0]) or adapt your function to handle arrays of objects. As an aside, to get the total physical memory in GB, you can use (Get-WmiObject Win32_PhysicalMemory | Measure-Object Capacity -sum).sum / 1GB

    – Theo
    Mar 24 at 15:12












  • @Theo You're absolutely right, thank you.

    – Michon
    Mar 26 at 10:28













0












0








0








The following script works well on newer powershell versions but I also need a version for powershell 2.0.



The problem seems to be that I can't use if ($class.$property -eq $null) here, but something like if (($class | select -expand $property) -eq $null) won't work too.



So how can I check if $class.$property is null in powershell 2.0?



script:
(there are more values I need later, but this shows the problem because SKU is null in my case)



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


output on powershell 5 (and like I would need it in 2.0 also):




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





As Theo suggested:



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


This gives different results für different powershell versions:



result with 2.0




"memory":

"sku": "top",
"capacity": "top"




result with 5.1




"memory":

"sku": "bottom",
"capacity": "bottom"











share|improve this question
















The following script works well on newer powershell versions but I also need a version for powershell 2.0.



The problem seems to be that I can't use if ($class.$property -eq $null) here, but something like if (($class | select -expand $property) -eq $null) won't work too.



So how can I check if $class.$property is null in powershell 2.0?



script:
(there are more values I need later, but this shows the problem because SKU is null in my case)



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


output on powershell 5 (and like I would need it in 2.0 also):




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





As Theo suggested:



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


This gives different results für different powershell versions:



result with 2.0




"memory":

"sku": "top",
"capacity": "top"




result with 5.1




"memory":

"sku": "bottom",
"capacity": "bottom"








powershell powershell-v2.0






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 24 at 13:26







Michon

















asked Mar 24 at 9:52









MichonMichon

254




254







  • 1





    You should test with if (!($class.$property)) instead of testing for equality with $null. Then, as you already know, in PowerShell version 2, there is no ConvertTo-Json. If you do need that, I suggest you look for modules on the internet like perhaps ConvertTo-STJson

    – Theo
    Mar 24 at 11:18







  • 2





    Also, if you specifically want to check for $null, it is best to put the $null on the lefthand side of the equasion. See Null comparison demystified

    – Theo
    Mar 24 at 11:23











  • Thank you @Theo but this behaves different on different versions of powershell. I edited the question to show you what I mean. Any idea why this happens?

    – Michon
    Mar 24 at 13:28






  • 2





    When testing, using this syntax if (!($class[$property])) seems to return the same results in PS 5.1 and PS 2.0. However, the returned value for Get-WmiObject -Class Win32_PhysicalMemory is an array while your function Get-Value-From-Class does not deal with arrays. In this case send it the index of one item in the array (Get-Value-From-Class -class $memory[0]) or adapt your function to handle arrays of objects. As an aside, to get the total physical memory in GB, you can use (Get-WmiObject Win32_PhysicalMemory | Measure-Object Capacity -sum).sum / 1GB

    – Theo
    Mar 24 at 15:12












  • @Theo You're absolutely right, thank you.

    – Michon
    Mar 26 at 10:28












  • 1





    You should test with if (!($class.$property)) instead of testing for equality with $null. Then, as you already know, in PowerShell version 2, there is no ConvertTo-Json. If you do need that, I suggest you look for modules on the internet like perhaps ConvertTo-STJson

    – Theo
    Mar 24 at 11:18







  • 2





    Also, if you specifically want to check for $null, it is best to put the $null on the lefthand side of the equasion. See Null comparison demystified

    – Theo
    Mar 24 at 11:23











  • Thank you @Theo but this behaves different on different versions of powershell. I edited the question to show you what I mean. Any idea why this happens?

    – Michon
    Mar 24 at 13:28






  • 2





    When testing, using this syntax if (!($class[$property])) seems to return the same results in PS 5.1 and PS 2.0. However, the returned value for Get-WmiObject -Class Win32_PhysicalMemory is an array while your function Get-Value-From-Class does not deal with arrays. In this case send it the index of one item in the array (Get-Value-From-Class -class $memory[0]) or adapt your function to handle arrays of objects. As an aside, to get the total physical memory in GB, you can use (Get-WmiObject Win32_PhysicalMemory | Measure-Object Capacity -sum).sum / 1GB

    – Theo
    Mar 24 at 15:12












  • @Theo You're absolutely right, thank you.

    – Michon
    Mar 26 at 10:28







1




1





You should test with if (!($class.$property)) instead of testing for equality with $null. Then, as you already know, in PowerShell version 2, there is no ConvertTo-Json. If you do need that, I suggest you look for modules on the internet like perhaps ConvertTo-STJson

– Theo
Mar 24 at 11:18






You should test with if (!($class.$property)) instead of testing for equality with $null. Then, as you already know, in PowerShell version 2, there is no ConvertTo-Json. If you do need that, I suggest you look for modules on the internet like perhaps ConvertTo-STJson

– Theo
Mar 24 at 11:18





2




2





Also, if you specifically want to check for $null, it is best to put the $null on the lefthand side of the equasion. See Null comparison demystified

– Theo
Mar 24 at 11:23





Also, if you specifically want to check for $null, it is best to put the $null on the lefthand side of the equasion. See Null comparison demystified

– Theo
Mar 24 at 11:23













Thank you @Theo but this behaves different on different versions of powershell. I edited the question to show you what I mean. Any idea why this happens?

– Michon
Mar 24 at 13:28





Thank you @Theo but this behaves different on different versions of powershell. I edited the question to show you what I mean. Any idea why this happens?

– Michon
Mar 24 at 13:28




2




2





When testing, using this syntax if (!($class[$property])) seems to return the same results in PS 5.1 and PS 2.0. However, the returned value for Get-WmiObject -Class Win32_PhysicalMemory is an array while your function Get-Value-From-Class does not deal with arrays. In this case send it the index of one item in the array (Get-Value-From-Class -class $memory[0]) or adapt your function to handle arrays of objects. As an aside, to get the total physical memory in GB, you can use (Get-WmiObject Win32_PhysicalMemory | Measure-Object Capacity -sum).sum / 1GB

– Theo
Mar 24 at 15:12






When testing, using this syntax if (!($class[$property])) seems to return the same results in PS 5.1 and PS 2.0. However, the returned value for Get-WmiObject -Class Win32_PhysicalMemory is an array while your function Get-Value-From-Class does not deal with arrays. In this case send it the index of one item in the array (Get-Value-From-Class -class $memory[0]) or adapt your function to handle arrays of objects. As an aside, to get the total physical memory in GB, you can use (Get-WmiObject Win32_PhysicalMemory | Measure-Object Capacity -sum).sum / 1GB

– Theo
Mar 24 at 15:12














@Theo You're absolutely right, thank you.

– Michon
Mar 26 at 10:28





@Theo You're absolutely right, thank you.

– Michon
Mar 26 at 10:28












0






active

oldest

votes












Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55322537%2fcheck-for-null-in-if-statement%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55322537%2fcheck-for-null-in-if-statement%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현