Question

in Powershell, is it important to use cmdlet parameters in the order in which they're defined in the official syntax?

I'm adding the -cc parameter to send-mailMessage in an existing script. I added -cc immediately after -To and it works just fine, so I'm inclined to leave well enough alone. But the cmdlet's only parameter set is defined as follows in the help text:

Send-MailMessage [-To] [-Subject] [[-Body] ] [[-SmtpServer] ] -From [-Attachments ] [-Bcc ] [-BodyAsHtml] [-Cc ] [-Credential ] [-DeliveryNotificationOption ] [-Encoding ] [-Port ] [-Priority ] [-UseSsl] [ ]

So I assume best practice would be to run a command like this (cc after subject, body, smtpserver, and from, following the help text):

send-mailmessage -to $mailTo -subject $mailSubj -body $msgbody -smtpserver smtp.domain.tld -from $mailFrom -cc $mailCC

...instead of like this (cc before many of those other parameters):

send-mailmessage -to $mailTo -cc $mailCC -subject $mailSubj -body $msgbody -smtpserver smtp.domain.tld -from $mailFrom

In general I haven't been super careful about this, and stuff works. So surely it'd be overkill (not to mention error-prone) to go back and adjust functional existing scripts along these lines. But maybe it's worth respecting the parameter order going forward, in future scripts? Or not worth the trouble? What say you?

Of course you don't want to make a bad assumption about which parameter is the default and then omit the parameter name; I can also imagine this sort of thing getting messy with custom functions or etc. But my question is about the simpler case, when the parameters of an in-the-box cmdlet are explicitly named, as with the send-mailMessage examples above.

Was it helpful?

Solution

If you are naming your parameters when invoking a cmdlet (e.g.Get-ChildItem -Path *.txt) then it doesn't matter what order you specify them in. Everything is exactly specified by name, so the order in which params were provided is not needed to resolve the arguments.

If you are NOT naming your parameters (e.g. Get-ChildItem *.txt) then it does matter. The cmdlet author can specify that certain parameters can/should be expected, without names, in a certain order. The Powershell engine will try its best to honor that, and in general it will try to pair un-named arguments to any parameters which have not yet been assigned.

Check out this page on parameter types for some more technical info.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top