I need to be able to have a class in powershell where I can create the names of the properties of that class dynamically. For example,
$binFiles = Get-ChildItem $files -Include *.BIN -recurse
$binFiles.Name
This would print something like:
File1.BIN
ThisFile.BIN
...
FileOther.BIN
I want these file names to be the names of the properties in my class that I will create multiple times. Is this even possible?
Class myItem {
[String]$"File1.BIN"
[String]$"ThisFile.BIN"
....
[String]$"FileOther.BIN"
}
You can use Invoke-Expression
(the solution is PSv5+, due to using custom PS classes):
Invoke-Expression @"
Class myItem {
$((Get-ChildItem $files -Include *.BIN -recurse).ForEach({"[string] `${$($_.Name)}`n "}))
}
"@
Note: While this particular use of Invoke-Expression
is safe, because you fully control the string being evaluated, Invoke-Expression
should generally be avoided.
The here-string produces the class definition as a string, which Invoke-Expression
then evaluates, which defines class [myItem]
for later use (e.g., $instance = [myItem]::new()
).
Note:
Invoke-Expression
.Invoke-Expression
call.[2]
The here-string produced above looks something like this - note the need to enclose the property names in {...}
, because they contain .
:
Class myItem {
[string] ${File1.Bin}
[string] ${File2.Bin}
# ...
}
[1] A class is immutable once defined, although you could add properties dynamically to its instances using PowerShell's ETS (extended type system), typically via the Add-Member
cmdlet.
Adding instance properties on demand would enable TheMadTechnician's suggestion of alternatively defining the class without properties and only an (instance) method that populates / updates a given instance's properties on demand.
[2] Technically, the recreated class is a distinct .NET type, though that typically won't matter, given that referring to it via a type literal - [myItem]
in this case - works the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With