I am trying to create object using the foreach loop in PowerShell. Tried using "while" loop, it failed as well. Apparently, the looping methods are not allowing me to create objects...
Without further ado...
I have two scripts - Class.psm1 and Main.ps1.
On Class.psm1
Class Car {
[string]$brand
[string]$model
[string]$color
#Constructor
Car ([string]$brand) {
$this.brand = $brand
switch -wildcard ($this.brand) {
('Toyota') {$this.model = 'ABC'; $this.color = 'red'; break}
('Honda') {$this.model = 'FGH'; $this.color = 'blue'; break}
}
}
}
And on Main.ps1
Using module ".\Class.psm1"
$AllCars = {'Toyota', 'Honda'}
[array]$Objects = @()
foreach ($car in $AllCars) {
$temp = New-Object Car("$car")
$Objects += $temp
}
The output from Main.ps1, is that $Objects are just returning back "Toyota" and "Honda", instead of objects (and the properties it supposed to have).
However, if I were to just create the object individually, it will works fine.
For example:
$temp = New-Object Car('Toyota')
$Objects += $temp
$temp = New-Object Car('Honda')
$Objects += $temp
However, this is too manual work or rather unpractical.
May I know in which area did the codes went wrong...? How do I create the objects within the loop?
Class.psm1- all properties and parameters need$in front of the name