Dynamic object Creation

This topic contains 4 replies, has 3 voices, and was last updated by  js 4 months ago.

  • Author
    Posts
  • #77395

    Thom Schumacher
    Participant

    I know that invoke-expression is a cmdlet I try my best to stay away from. This is the only way though that I can seem to create an object that I need to create dynamically during execution. Is there a better way?

       Function New-DynamicObject
    { 
    param([string]$name)
     $newObject = (Invoke-Expression "[$name]::New()")
     $newObject
    }
    
  • #77401

    js
    Participant

    I'm not sure what you mean, like this?

    $newobject = [pscustomobject]@{name='me';address='here'}
    $newobject
    
    
    name address
    ---- -------
    me   here
    
  • #77418

    Thom Schumacher
    Participant

    you can create an object like this:

    [int]$test = '1'

    If I'm running code and I find while I'm running that I need to create a type called [somedevelopers.class] once I've imported their dot net class.. I'd need to do
    $test = [somedevelopers.class]::new()

    I want to be able to detect that class name and then dynamically create the class. if you try to create a class with
    [$variableNameThatContainsTheDevClass] then you'll get an error from powershell.

    So the only way I can create that class dynamically is to do what I've shown above. Was curious if anyone else had a better or different way of doing the same thing.

    • #77421

      Olaf Soyk
      Participant

      I'm not sure that I've got you right. What is it what you're trying to achieve? The simplest way to create an object in Powershell I can think of is this:

      $MyCoolObject = 'Something completely arbitrary' | Select-Object -Property Name,Age

      Now you have an object with the name $MyCoolObject and the properties Name and Age.

    • #77439

      js
      Participant

      So you want to store type names in variables? How about:

      $type = 'int'                                                 
      $a = new-object $type   
      $a.gettype()                                                  
      
      
      IsPublic IsSerial Name                                     BaseType            
      -------- -------- ----                                     --------            
      True     True     Int32                                    System.ValueType    
      

You must be logged in to reply to this topic.