How important is parameter order when calling powershell cmdlets? - powershell

In PowerShell (PS), 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] <String[]> [-Subject] <String> [[-Body] <String> ] [[-SmtpServer] <String> ] -From <String> [-Attachments <String[]> ] [-Bcc <String[]> ] [-BodyAsHtml] [-Cc <String[]> ] [-Credential <PSCredential> ] [-DeliveryNotificationOption <DeliveryNotificationOptions> ] [-Encoding <Encoding> ] [-Port <Int32> ] [-Priority <MailPriority> ] [-UseSsl] [ <CommonParameters>]
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.

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.

Related

Send emails with Powershell mailto with formated text

My current script creates (after an account modification) a .ps1 file that is send to another computer and there it is executed opening a new Gmail tab with some information hosted in several variables. I need this email to have format like bold, hyper-link, etc.
Im using the start-process 'mailto' for this but i can not find the way to give this email a format (believe me, i have tried), is this even possible?
I appreciate any insights on this.
My current script creates (after an account modification) a .ps1 file that is send to another computer and there it is executed opening a new Gmail tab with some information hosted in several variables. I need this email to have format like bold, hyper-link, etc.
Im using the start-process 'mailto' for this but i can not find the way to give this email a format (believe me, i have tried), is this even possible?
Additional information:
Code:
$outPut = 'Start-Process'
$outPut+= '"mailto:'+$userMail+"?Subject=Password Reset"+"&Body=Hi, your password is $Password"
$outPut+= '";'
$mailFile = "Path" + $user.SAM + ".ps1"
$outPut | Out-File $mailFile
So, this takes the information this way and stored it in a ps1 file, then executed, opening a new Gmail tab with proper data.
I need that some words has format, bold for the password or hyper-link for guideness link...
Regards!
You haven't provided any indication of what you are doing. But the way to send emails via PowerShell is with the Send-MailMessage cmdlet. If you are using Send-MailMessage and formatting the body of the message with HTML, you just need to make sure you are using the -BodyAsHtml argument.
Here's an example:
$html = "<body><h1>Heading</h1><p>paragraph.</p></body>"
Send-MailMessage -To "bob#fake.com" -From "me#fake.com" -Subject "Test" -Body $html -BodyAsHtml

Adding a variable to a -Body when sending an email

I'm creating a PowerShell script to make our starters and leavers process smoother. We have a separate team who needs to add certain accounts.
What I'd like to do is take the variable that is declared at the start of the script, the new users name, and put it in an email asking for this other department to set them up.
$username = "joe"
Send-MailMessage -SmtpServer smtp.office365.com -From "it#support.com" -To "other#department.com" -Subject 'Starter/Leaver ' -Body "Hi department, `n `nPlease can you add/remove" $username "from the necessary account please `n `nThanks"
I get an error saying:
Send-MailMessage : A positional parameter cannot be found that accepts argument "joe"
The issue here is that the string object sent to -Body is broken because of the quoting. You can just surround the entire body with one set of quotes to achieve the desired result.
$username = "joe"
Send-MailMessage -SmtpServer smtp.office365.com -From "it#support.com" -To "other#department.com" -Subject 'Starter/Leaver ' -Body "Hi department, `n`nPlease can you add/remove $username from the necessary account please `n`nThanks"
Neater Alternative:
I know this answer is not as concise, but it is more readable and adds some flexibility. It uses a here-string to create the body, which doesn't require having to add all of the line feed characters. It also uses splatting to execute the command. With splatting, you can just update the hash table when you need to change something.
$Body = #"
Hi department,
Please can you add/remove $username from the necessary account please
Thanks
"#
$Message = #{ SmtpServer = 'smtp.office365.com'
From = "it#support.com"
To = "other#department.com"
Subject = 'Starter/Leaver'
Body = $Body
}
Send-MailMessage #Message
When running a PowerShell command, parameters are space-delimited. In the case of Send-MailMessage positional parameters are also allowed, which means you don't have to provide the parameter name when passing in a value. In your attempt, your first quote pair was passed to the -Body parameter. After the first closing quote, a space followed by $username is interpreted. Because positional parameters are enabled for the command, PowerShell attempts to assign $username to a parameter and fails. Of course this also means that if you intend to include a space in your string, it must be surrounded by quotes.
Additional Reading:
See About Parameters for an overview of how parameters work.
See About Splatting for information on splatting.

Using pipeline object to populate mail -to and -attachment

First ever Powershell script so any advice or recommendations are appreciated. I'm parsing a .csv into smaller .csv's to send out information about servers to recipients and i'm running into a problem in my foreach. How do I get this to work?
One interesting thing is that in Send-MailMessage, -to should not accept pipeline objects, It still throws an error, but it still sends the emails. However the attachment will never send.
#had to set this as a variable because # was throwing splatting errors
$Mail = "#Email.com"
#Import csv and split information, exports UID.csv
Import-csv C:\path\info.csv | Group-Object UID |
ForEach-Object {
$_.Group | Export-csv "C:\path\$($_.Name).csv" -NoTypeInformation
}
#Import file again to get unique list of UID and send mail with
#respective UID.csv
Import-csv C:\path\info.csv | Group-Object UID |
ForEach-Object {
$_.UID | Send-MailMessage -From "<Me#email.com>" -To "<$($_.Name)$Mail>" `
-Attachments "C:\path\$($_.Name).csv" `
-Subject "Testing" -Body "Please Ignore This" -Priority High `
-SmtpServer smtp.server.com
}
in Send-MailMessage, -to should not accept pipeline objects
In principle it does, namely if the pipeline objects have a .To property (which is not the case for you).
However, with your current approach, you don't need pipeline input at all, given that you're supplying all input as arguments.
Additionally, your pipeline input is incorrect, because $_.UID sends $null through the pipeline, given that $_ - a group-info object output by Group-Object - doesn't have a .UID property.
Using delay-bind script blocks ({ ... }), you can simplify your command as follows, obviating the need for a ForEach-Object call:
Import-csv C:\path\info.csv | Group-Object UID |
Send-MailMessage -From "<Me#email.com>" -To { "<$($_.Name)#Email.com>" } `
-Attachments { "C:\path\$($_.Name).csv" } `
-Subject "Testing" -Body "Please Ignore This" -Priority High `
-SmtpServer smtp.server.com
In short, the script blocks passed to -To and Attachments are evaluated for each input object, and their output determines the parameter value in each iteration. In the script block, $_ represents the pipeline object at hand, as usual.
Note that such delay-bind script blocks can only be used with parameters that are designed to accept pipeline input (irrespective of whether by value (whole object) or by a specific property's value).

Send-MailMessage -From - bad formatting

Quite simple question. I'm sending an email with send-mailmessage, which works fine. But i'm not entirely happy with the format of the sender.
Send-MailMessage -to "User01 <User01#example.com>" -from "USER02 <USER02#example.com>" -subject "Test mail" -SmtpServer 'mysmtp'
When receiving the Mail (IBM Lotus Notes) the sender is shown as "user02" in lower case, although i'm running the command with the sender in upper case - as shown above.
Is there by purpose any simple way to solve my little problem? Should be shown as "USER02" not as "user02". Reason of Powershell or cause of Lotus Notes?

Scheduling Powershell changes ObjectType

I've written a little script that checks for differences between 2 text files.
$new = get-content $outPutFile
$old = get-content $outPutFileYesterday
$result = $null
$result = Compare-Object $old $new
$resultHTML = $result.GetEnumerator() | ConvertTo-Html
Send-MailMessage -SmtpServer 10.14.23.4 -From me#mail.com -To $toAddress -Subject "DiffTest" -Body "$resultHTML" -BodyAsHtml
When I run it from an active PowerShell prompt, all is well. However, when I try to schedule it to run daily I get this error on the run-time (the block above is in a try catch that mails any execution errors):
Method invocation failed because [System.Management.Automation.PSCustomObject] doesn't contain a method named 'GetEnumerator'.
How can I fix this?
The script may run in a different user context when scheduled, potentially with a different set of read/write permissions on the filesystem.
However, In PowerShell arrays are automatically enumerated when used in expressions, so you don't need to
call the GetEnumerator() method before passing it to ConvertTo-Html.
You could start by changing your script to:
$resultHTML = $result | ConvertTo-Html
and see how it impacts the result.
Compare-Object either returns:
$null: if the ReferenceObject and the DifferenceObject are equal
an object of type PSCustomObject: if only one item differs (1)
an array of objects: if multiple differences have been found
Of these return values only the last one (the array) has a GetEnumerator() method. ConvertTo-Html produces the expected output when fed either of these return values, so you can safely drop the .GetEnumerator() part (as mentioned by Enrico). Another option is to wrap the $result in an array, which would change line 6 of your script to:
$resultHTML = #($result).GetEnumerator() | ConvertTo-Html
(1) This is the return value for compare-object in your script