In part 1 we looked at how data becomes more accessible when converted to a more appropriate .NET data type.
If you can’t find an existing data type for your data to provide it with structure, you can create your own data types as well.
Let’s assume you need to handle names. Here’s a custom data type called [TeamMember] that can add structure to names:
class TeamMember { [string]$FirstName [string]$LastName TeamMember([string]$Name) { # case correct text $newName = [cultureinfo]::InvariantCulture.TextInfo.ToTitleCase($Name) # automatically find delimiter character $delimiter = $newName.ToCharArray() -match '[,. ]' | Select-Object -First 1 # no delimiter? if ($delimiter.Count -eq 0) { $this.LastName = $Name return } $array = $newName.Split($delimiter) # based on found delimiter switch -Regex ($delimiter) { # dot or space: '[.\s]' { $this.FirstName = $array[0] $this.LastName = $array[1] } # comma '\,' { $this.FirstName = $array[1] $this.LastName = $array[0] } # invalid default { $this.LastName = $Name } } } }
Once you run this code, you defined a new datatype called [TeamMember]. Now it’s simple to convert a string containing a name to a structured data type:
PS> [TeamMember]'tobias weltner' FirstName LastName --------- -------- Tobias Weltner PS> [TeamMember]'tobias.weltner' FirstName LastName --------- -------- Tobias Weltner PS> [TeamMember]'weltner,tobias' FirstName LastName --------- -------- Tobias Weltner
As an added benefit, you get automatic case correction, or in general: your class can incorporate any wizardry you like. When you later use the type, you no longer need to worry about it.
Even better, when you assign this type to a variable, it will auto convert any name to the new structure even in future assignments:
PS> [TeamMember]$name = 'Tobias Weltner' PS> $name FirstName LastName --------- -------- Tobias Weltner PS> $name = 'kloVER,kaRL' PS> $name FirstName LastName --------- -------- Karl Klover
The secret of auto conversion for custom classes is its constructor. When the constructor accepts one argument of type [string], it then can automatically convert any string into the new structure.
The constructor of the class is always named like the class and is indeed accepting [string]:
TeamMember([string]$Name) { ... }