How to get an object's property's value by property name?

前端 未结 6 1687
野趣味
野趣味 2020-11-27 14:54

In PowerShell, how do you get an object\'s property value by specifying its name (a string)? I want something like the following:

$obj = get-something

# Vie         


        
6条回答
  •  孤街浪徒
    2020-11-27 15:43

    You can get a property by name using the Select-Object cmdlet and specifying the property name(s) that you're interested in. Note that this doesn't simply return the raw value for that property; instead you get something that still behaves like an object.

    [PS]> $property = (Get-Process)[0] | Select-Object -Property Name
    
    [PS]> $property
    
    Name
    ----
    armsvc
    
    [PS]> $property.GetType().FullName
    System.Management.Automation.PSCustomObject
    

    In order to use the value for that property, you will still need to identify which property you are after, even if there is only one property:

    [PS]> $property.Name
    armsvc
    
    [PS]> $property -eq "armsvc"
    False
    
    [PS]> $property.Name -eq "armsvc"
    True
    
    [PS]> $property.Name.GetType().FullName
    System.String
    

    As per other answers here, if you want to use a single property within a string, you need to evaluate the expression (put brackets around it) and prefix with a dollar sign ($) to declare the expression dynamically as a variable to be inserted into the string:

    [PS]> "The first process in the list is: $($property.Name)"
    The first process in the list is: armsvc
    

    Quite correctly, others have answered this question by recommending the -ExpandProperty parameter for the Select-Object cmdlet. This bypasses some of the headache by returning the value of the property specified, but you will want to use different approaches in different scenarios.

    -ExpandProperty

    Specifies a property to select, and indicates that an attempt should be made to expand that property

    https://technet.microsoft.com/en-us/library/hh849895.aspx

    [PS]> (Get-Process)[0] | Select-Object -ExpandProperty Name
    armsvc
    

    powershell variables

提交回复
热议问题