question

PeizhiYu avatar image
0 Votes"
PeizhiYu asked ToddAlbers commented

how to check a value is that null in powershell script

I want to check the PasswordLastSet value of the user is that empty.


 PS Z:\> Get-ADUser -Identity test1 -Properties * | select passwordlastset
    
 passwordlastset
 ---------------

By if to judgment is that null.



this is my script

 $password = Get-ADUser -Identity test1 -Properties * | select passwordlastset
  if ($password -ne $null){
     Write-Output "It's empty"
     }
 else {
     Write-Output "It isn't empty"
    }



That always output "It's empty"

what should I do? How to change it?

windows-server-powershell
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

IanXue-MSFT avatar image
0 Votes"
IanXue-MSFT answered RichMatheisen-8856 commented

Hi,
The $password is an object of type ADUser. You'd use the property $password.passwordlastset in the if condition and the comparison operator should be -eq. Select-Object returns not the specified property but an object that has only the specified property.

  $password = Get-ADUser -Identity test1 -Properties * | select passwordlastset
   if ($password.passwordlastset -eq $null){
      Write-Output "It's empty"
      }
  else {
      Write-Output "It isn't empty"
     }


Best Regards,
Ian

============================================
If the Answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.





· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Actually, because of the Select-Object, the variable $password is of the type PSCustomObject.

The $password variable isn't $null because it contains that PSCustomObject. The $password variable has a single NoteProperty named passwordlastset. It's that property that contains a $null value.

Changing the original code slightly would make the the OP's test work:

 $password = (Get-ADUser -Identity test1 -Properties * ).PasswordLastSet
 if ($null -ne $password){
     Write-Output "It's not null" -Foreground Green
 }
 else {
     Write-Output "It is null" -Foreground Yellow
 }


0 Votes 0 ·