powershellsyntaxobject-initializers

Object instantiation with predefined properties


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?


Solution

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