1

I'm trying to set a child property in a custom object using a parent property.

$objServer = New-Object PSObject -Property @{
    Name = "Some Name";
    BaseFilePath = "c:\somepath"
    Section1 = New-Object PSObject -Property @{ 
        FilePath=$objServer.BaseFilePath + '\' + $objServer.Name + '\section1'; 
        AncestorId="557309"; 
        Title="Section 1"; 
        Enabled=$processFlag1; 
    }
    Section2 = New-Object PSObject -Property @{
        FilePath={$_.Parent.BaseFilePath} + '\' + {$_.Parent.Name} + '\' + '\section2'; 
        AncestorId="557319"; 
        Title="Tables"; 
        Enabled=$processFlag2; 
    }
}

Section 1 and Section 2 are examples of syntax I've tried. Is this possible? What am I doing wrong?

Hecatonchires
  • 1,009
  • 4
  • 13
  • 42

1 Answers1

1

The problem is the nesting. The hashtable for the properties of the parent object has to be created before it can be passed into the cmdlet that created the parent, so you can't refer to something that doesn't exist yet.

Do it as a 2 step process. Create the parent, then add a member after the fact:

$objServer = New-Object PSObject -Property @{
    Name = "Some Name"
    BaseFilePath = "c:\somepath"
} 
$objServer | Add-Member -NotePropertyName Section1 -NotePropertyValue (
    New-Object PSObject -Property @{ 
        FilePath=$objServer.BaseFilePath + '\' + $objServer.Name + '\section1'; 
        AncestorId="557309"; 
        Title="Section 1"; 
        Enabled=$processFlag1; 
    }
)
briantist
  • 45,546
  • 6
  • 82
  • 127