powershellnull-conditional-operator

How to Skip Null Objects returned from CimInstance


Get-CimInstance -ComputerName $pc -Class Win32_UserProfile | Where-Object { $_.LocalPath.split('\')[-1] -eq $compare } | Remove-CimInstance

Because some system profiles have empty values for LocalPath, I get the following:

You cannot call a method on a null-valued expression. At line:52 char:88

Where-Object { $_.LocalPath.split('')[-1] -eq $compare })

Any way either first check for empty value and skip to next?

ty


Solution

  • In PowerShell (Core) 7.1 and above, you can use the null-conditional operator, ?.:

    Get-CimInstance -ComputerName $pc -Class Win32_UserProfile | 
      Where-Object { $_.LocalPath?.split('\')[-1] -eq $compare } | 
      Remove-CimInstance
    

    As a general caveat:


    In Windows PowerShell you can use PowerShell's implicit to-Boolean conversion rules:

    Get-CimInstance -ComputerName $pc -Class Win32_UserProfile | 
      Where-Object { $_.LocalPath -and $_.LocalPath.split('\')[-1] -eq $compare } | 
      Remove-CimInstance