0

got a class that I need to initiate an uncertain nr. of times, depending on how many days you need in this week, so from 1 - 7 (hard coded variable with 3 for testing purpose)

But how can I call the class constructor with a dynamic variable? the error says:

The assignment expression is not valid. The input to an assignment operator must be an object that is able to accept assignments, such as a variable or a property.

I assume its, because it sees the $($tmp) as a string and not a variable, tried the get-variable -valueonly command but no luck.

Kind regads Per Andersen

the code:

class Day
{
    [string] $Init

    
    [void] SetInit($Init)
    {
        $this.Init += $Init;
    }
}
$count = 3 #(will be changed to dynamic number when all is rdy)

for ($i=1; $i -le $count; $i++)
{
    $tmp = "`$NewDay$i"
    $($tmp) = [Day]::new();
}

ps removed some code to make it easy to read, but same problem.

Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37
  • 1
    What is the purpose of the `Day` class? What problem is it meant to solve? Are you hoping to use an instance of it to... generate strings? – Mathias R. Jessen Mar 23 '22 at 12:31
  • 1
    Perhaps what you're looking for is _variable indirection_, where you refer to a variable _indirectly_, via its name stored in a different variable or provided by an expression. PowerShell enables this via the [`Get-Variable`](https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/get-variable) and [`Set-Variable`](https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/set-variable) cmdlets - see [this answer](https://stackoverflow.com/a/68214332/45375). In your case, perhaps: `Set-Variable "NewDay$i" ([Day]::new()` – mklement0 Mar 23 '22 at 12:49
  • @Mathais, I'm trying to initiating an unknow number of days for a schedule, it might be I need 5 or only 2, not known at the programming time. I know I could just call a function with the desired number, and solve it with an if and then hardcode then class call from 1 to 5, but would not be the most "elegant" solution, and would be harder to maintain, if you decided to go for higher numbers. – Per Andersen Mar 24 '22 at 08:10
  • @mklement0 tried that, but couldnt get it to work, ;( – Per Andersen Mar 24 '22 at 08:10
  • @mklement0 but will try a bit more, or will go to the if's as mentioned to Mathias if all else fails. – Per Andersen Mar 24 '22 at 08:30

0 Answers0