Why errors are not returned when calling properties that do not exist?

Given the following snippet

$drives = Get-PSDrive

foreach($drive in $drives)
{
    Write-Host $drive.Name "`t" $drive.Root
    Write-Host " - " $drive.Free "`t" $drive.PropertyDoesntExist
}   

The drive.PropertyDoesntExist property does not exist ... erm ... exists, so I expect an error to be selected, but instead it returns null.

How can I get errors or exceptions?

EDIT - I feel bad - I asked two questions in one, so I moved one to a separate question .

+4
source share
1 answer

NextHop Blog provides a good solution to this problem. This does not give you an error, but instead a logical one. You can use Get-Memberto get a collection of all the real properties of an object type, and then match the required property.

:

PS C:\> $test = "I'm a string."
PS C:\> ($test | Get-Member | Select-Object -ExpandProperty Name) -contains "Trim"
True
PS C:\> ($test | Get-Member | Select-Object -ExpandProperty Name) -contains "Pigs"
False

, Set-Strictmode Set-StrictMode -version 2, . , :

PS C:\> Set-StrictMode -version 2
PS C:\> "test".Pigs
Property 'Pigs' cannot be found on this object. Make sure that it exists.
At line:1 char:8
+ "test". <<<< Pigs
    + CategoryInfo          : InvalidOperation: (.:OperatorToken) [], RuntimeException
    + FullyQualifiedErrorId : PropertyNotFoundStrict

PS C:\> Set-StrictMode -off
+4

All Articles