Josh-CO Dev

Solving the worlds problems one line of code at a time.


Leave a comment

Powershell – Sending an Email

Another task that I am commonly automating in Powershell is the sending of emails. As long as you have some SMTP credentials, this is relatively easy. Please note that I have removed any sensitive information.

#this function is responsible for all mail handling
#Params:
#$to - the email address of the recipient
#$subject - the subject of the email
#$body - the body of the email
function sendMail($to, $subject, $body)
{
     Write-Host "Sending Email"

     #SMTP server name
     $smtpServer = "xxx.xxxxxxx.com"     

     #Creating a Mail object
     $msg = new-object Net.Mail.MailMessage

     #Creating SMTP server object
     $smtp = new-object Net.Mail.SmtpClient($smtpServer)

     #Email structure
	 #all emails will come from the XXXXXX mailbox. 
     $msg.From = "no-reply@noreply.com"
     $msg.ReplyTo = "no-reply@noreply.com"
     $msg.To.Add($to)
     $msg.subject = $subject
     $msg.body = $body

     #send the mail
     $smtp.Send($msg)
}


Leave a comment

Powershell – Set a Proxy

I’ve been using Powershell A LOT lately and I thought I would start sharing some code snippets of things that I have had to learn along the way. The first thing is how to set up powershell to use a proxy. A lot of the scripts I have been writing involve going out to the web and scrubbing HTML as a data source. It is pretty simple. Just add this to your script (I always put it at the top out of habit, not sure if this is necessary).

#Set our proxy information. We are hardcoding the proxy server, but the credentials will pull from the OS
$global:PSDefaultParameterValues = @{
        'Invoke-RestMethod:Proxy'='http://proxyServer:proxyPort'
        'Invoke-WebRequest:Proxy'='http://proxyServer:proxyPort'
        '*:ProxyUseDefaultCredentials'=$true
    }