Author Posts

August 16, 2017 at 3:24 pm

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
}

August 16, 2017 at 7:47 pm

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

$newobject = [pscustomobject]@{name='me';address='here'}
$newobject


name address
---- -------
me   here

August 16, 2017 at 9:23 pm

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.

August 16, 2017 at 9:48 pm

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.

August 16, 2017 at 10:45 pm

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