String to Property Name

This topic contains 3 replies, has 3 voices, and was last updated by  Clum09 4 years, 1 month ago.

  • Author
  • #15803



    I want to convert a string with spaces to use as a property name. See example below.

    $filePath = 'C:\Scripts\Data.csv'

    Within the Data.csv file, there is a column header with name 'Text with space' and the value under this header is a value called True:

    Header: Text with space
    The line below the header line has a value of True. I convert this header (Text with space) to a property name and the line below it (True) to the value of the property by using the ConvertTo-Csv cmdlet like below.

    $data1 = Get-Content $filePath | ConvertFrom-Csv -Delimiter ','

    Now, I have a PSObject array ($data2) with a property name called 'Name' and its property value also called 'Text with space', and I want to check against the elements of $data1 to see if the value of of 'Text with space' contains the value called 'True'.

    foreach ($a in $data2) {
    foreach ($b in $data1) {
    if ($b.{$a.Name} -eq 'True') {
    Code to do something here..

    $a.Name in the above loop is a string. How can I convert this string to become a property name?


  • #15805

    Matt McNabb

    I think what you need is a subexpression like this:

  • #15810


    Yes, that seems to do the trick. Thank you all for the help!

  • #15806

    Dave Wyatt

    I think what you need is a subexpression like this:

    Yep, that'll do the trick. Though it's not strictly necessary, I'd probably assign $a.Name to another temporary variable first (something like $propertyName), then just use $b.$propertyName . It looks a bit more readable to me.

    $propertyName = $a.Name
    if ($b.$propertyName -eq 'True')
        # Do something

You must be logged in to reply to this topic.