I want to programmatically set a public property within a class' constructor in PowerShell V5.0. The test class has many public properties that are to be filled in depending on the object passed to the class' constructor (lovingly referred to as '$something')
I thought it'd save a lot of code if I created an array of public property names which was accessible and iterate through them, as the setting the value of the public properties is just calling the same method on the $something object passed to it.
Tried using the Set-Variable cmdlet on every scope (I thought it'd be local scope). It could be done manually setting each public property in the constructor, but I'd love to be able to shorten it if possible.
Class TestClass
{
[STRING]$PublicProperty
[STRING]$PublicProperty1
... ... ... #Loads more properties
[STRING]$PublicProperty50
#An array that contains name for public properties
[ARRAY]$ArrayOfPublicProperties = @("PublicProperty", "PublicProperty1"...)
TestClass($something)
{
foreach ($property in $this.ArrayOfPublicProperties)
{
Set-Variable -Name "$($property.Name)" -Scope Local -Value $($something.GetValue(#blablabla))
}
}
}
I expect to be able to iterate through the public array (it's gross code, but it works for the situation I'm in and I don't know enough to think of any other ways) and set the variable using the Set-Variable cmdlet. Instead it doesn't set anything. I'm sure I've done something similar in the past, programmatically creating and setting variables etc... idk.
Pls to help