2

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?

mklement0
  • 382,024
  • 64
  • 607
  • 775

2 Answers2

2

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.

Daniel
  • 4,792
  • 2
  • 7
  • 20
2

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).

mklement0
  • 382,024
  • 64
  • 607
  • 775