No error when selecting non-existing property

前端 未结 3 1920
梦谈多话
梦谈多话 2021-01-14 12:07

I want PowerShell to throw an error when trying to select non-existing properties, but instead I get empty column as output. Example:

$ErrorActionPreference=         


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-14 12:54

    You are actually using what some people would call a feature. That is a simpler rendition of using Add-Member on all the array members to add an empty column.

    In the case of Import-CSV what you do in that case is check the property names before the Select where you call them.

    $data = Import-csv C:\Temp\file.csv 
    $props = $data | Get-member -MemberType 'NoteProperty'  | Select-Object -ExpandProperty Name
    

    I can see the documentation be a little misleading when it says for Set-StrictMode:

    Prohibits references to non-existent properties of an object.

    But in this case you are not trying to get the property reference but using a function of the Select-Object cmdlet. The following would have generated an error though

    PS C:\Users\mcameron> Set-StrictMode -Version 'Latest'
    (Get-Process *ex*).Bagels
    
    The property 'Bagels' cannot be found on this object. Verify that the property exists.
    At line:2 char:1
    + (Get-Process *ex*).Bagels
    + ~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [], PropertyNotFoundException
        + FullyQualifiedErrorId : PropertyNotFoundStrict
    

提交回复
热议问题