Reputation: 319
I have a powershell script that I am trying to send an email. The problem is that I want to be able to call the script and pass in some parameters including smtp server, email address, user name and password. The problem is that the powershell script does not like taking the password in on the command line. I have to hard code the password. Is there any way around this? One more bit of information is that sometimes this works. The problem is that when I hit the database from this script, that is when the password gets in the way. But I don't use the password in the database at all. Can anyone shed any light on this?
$smtpServer = $args[0]
$EmailTo = $args[1]
$UserName = $args[2]
$Password = $args[3]
$Subject = "Some Subject"
$EmailFrom = "[email protected]"
$Body = "Bunch of data here"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("MyUserName", "MyPassword")
#$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("MyUserName", "MyPassword") --this won't work
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
Upvotes: 0
Views: 1054
Reputation: 1118
You can pass a password at the command-line in plain text, but it needs to be converted to a SecureString object, and then it can be used by NetworkCredentials.
http://myitforum.com/cs2/blogs/yli628/archive/2007/09/22/how-to-enter-password-as-secure-string.aspx
You can also change Get-Credential to work "command-line only", but then you still need to split out what is the username and what is the password:
http://www.powershellmagazine.com/2013/02/11/pstip-get-credential-at-the-command-line/
In the past, I seem to remember one of these solutions seeming to have problems with "DOMAIN\username" type credentials, specifically with the "DOMAIN\" possible getting dropped due to the "\".
Upvotes: 2