Object instantiation with predefined properties

117 views Asked by At

I am studying the mailkit library, I found just such a construction in one line in c#

msg.Body = new TextPart("html") { Text = "<b>html content</b>" };

on Powershell I can do as many as three lines

$TextPart = [MimeKit.TextPart]::new("html")
$TextPart.Text = "<b>html content</b>"
$msg.Body = $TextPart

Is it possible in powershell to also write this on one line?

2

There are 2 answers

0
Daniel On BEST ANSWER

It is possible to also simplify this in PowerShell

$msg.Body = New-Object MimeKit.TextPart -ArgumentList 'html' -Property @{Text = '<b>html content</b>' }

The -Property parameter of New-Object will accept a hashtable of property names:property values where you can specify as many properties as you like.

0
mklement0 On

To complement Daniel's helpful answer with a more convenient PSv3+ alternative, where you can cast a hashtable @{ ... } or custom object ([pscustomobject] @{ ... }) to the target type:

[MimeKit.TextPart] @{ Text = '<b>html content</b>' }

See this answer for a comprehensive discussion of the prerequisites for and constraints on this technique (equally applies to use of New-Object).