Archive for the 'email' Category

Manage Email addresses without Exchange cmdlets

AD cmdlets 1.4 added new cmdlets and parameters which let you manage email addresses in your environment even if you do not have Exchange Management Shell. This is very handy if you are on Exchange 2003, do not have Exchange cmdlets installed, or just don’t want to switch between snapins.

Here’s the quick overview of what we have added:

Retrieving accounts by any proxy addresses:

Now Get-QADObject, Get-QADGroup, and Get-QADUser all have PrimaryProxyAddress, ProxyAddress and SecondaryProxyAddress parameters which can let you be more specific in your queries and thus retrieve objects much faster (compared to just supplying the address as identity parameter and relying on default resolution).

For example, you could do:

Get-QADUser -ProxyAddress 'x400:C=US;A= ;P=Quest Software;O=Aliso Viejo;S=Sotnikov;G=Dmitry;I=A;'

or

Get-QADUser -SecondaryProxyAddress '*Sotnikov@algorithm.aelita.com'

Adding email addresses:

Just use Add-QADProxyAddress and specify various parameters for specifics (pair with Clear-QADProxyAddress to replace previous addresses):

Get-QADUser company\jsmith |
  Add-QADProxyAddress -Address 'smtp:jsmith@company.com' |
  Add-QADProxyAddress -Type SMTP -Address 'john.smith@company.com' -Primary |
  Add-QADProxyAddress -CustomType 'sip' -Address 'john.smith@company.com'

Removing all addresses:

Did I mention Clear-QADProxyAddress?

Get-QADUser company\jsmith |
  Clear-QADProxyAddress |
  Add-QADProxyAddress -Address 'smtp:jsmith@company.com' |
  Add-QADProxyAddress -Type SMTP -Address 'john.smith@company.com' -Primary |
  Add-QADProxyAddress -CustomType 'sip' -Address 'john.smith@company.com'

Removing individual addresses:

Use Remove-QADProxyAddress and it’s parameters to operate on a specific address or a set of addresses:

Get-QADUser |
  Remove-QADProxyAddress -Pattern '*@company.com'

Modifying addresses:

Set-QADProxyAddress lets you pick and replace specific addresses:

Get-QADUser |
  Set-QADProxyAddress -From '*@source.com' -MakePrimary

or

Get-QADUser |
  Set-QADProxyAddress -From '*@before.com' -To '*@after.com'

Enabling or disabling email address policy:

Enable-QADEmailAddressPolicy and Disable-QADEmailAddressPolicy are your respective friends and can be applied to individual objects. For example:

Get-QADUser DomainName\UserName | Disable-QADEmailAddressPolicy
Get-QADUser -City London | Enable-QADEmailAddressPolicy

Happy scripting!

Monitor web-site availability

Did you know that you can use PowerShell to monitor your website and send you alarms when something goes wrong? We had availability issues with our community site and I was quite surprised that the 20-line (!) PowerShell script did the job!

Basically, all I had to do was use the Net.WebClient object and its DownloadString method to query the page (with some proxy handling code I got from Alexey Chuikov), and trap any exception which it generates when something goes wrong. The trap is using our internal relay server to send me and everyone who is involved in the site administration the email.

Here’s the code:

##########################################################
# Test-Site - script to test web site availability
# and notify in case of any issues
# (c) Dmitry Sotnikov
# https://dmitrysotnikov.wordpress.com
##########################################################

function Test-Site {
    param($URL)
    trap{
        "Failed. Details: $($_.Exception)"
        $emailFrom = "my.email@address.com"
        # Use commas for multiple addresses
        $emailTo = "my.email@address.com,another.admin@address.com"
        $subject = "PowerGUI.org down"
        $body = "PowerGUI web site is down. Details: $($_.Exception)"
        $smtpServer = "smtp.server.to.use.for.relay"
        $smtp = new-object Net.Mail.SmtpClient($smtpServer)
        $smtp.Send($emailFrom, $emailTo, $subject, $body)    
        exit 1
    }
    $webclient = New-Object Net.WebClient
    # The next 5 lines are required if your network has a proxy server
    $webclient.Credentials = [System.Net.CredentialCache]::DefaultCredentials
    if($webclient.Proxy -ne $null)     {
        $webclient.Proxy.Credentials = `
                [System.Net.CredentialCache]::DefaultNetworkCredentials
    }
    # This is the main call
    $webclient.DownloadString($URL) | Out-Null
} 

Test-Site "http://powergui.org"

To test it you can obviously just put an invalid URL into the call.

Once I had the script running, I just set up a scheduled task in Windows Task Scheduler to run the script every 15 minutes:
Windows Task Scheduler with a PowerShell task

One trick I learned from MoW and used in the task, was using the -command parameter (rather than just supplying the script) and including the exit $LASTEXITCODE into the command, so the exit code from the PowerShell script gets registered as the scheduled task result.

So here’s the command-line I have scheduled:

c:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -Noninteractive -command ". c:\scripts\test-site.ps1; exit $LASTEXITCODE"

Works flawlessly! And can save you tons of money on a monitoring solution. Talk about ROI from learning PowerShell! 😉

Tags: , , , , , , , ,

Execute PowerShell Scripts from Your Smartphone

Suppose you are on vacation/commute/away from your desk and get an emergency IT request. Would not it be cool to just text the PowerShell commands from your phone to your desk, have PowerShell over there execute the script, and send you back the results? 😉

Turns out this is very easy to do. All you need is Outlook, a simple rule in it, a simple PowerShell script and Outlook macro.

Here’s how this all works:

  1. You set up an Outlook rule to check for incoming email with a specific keyword (e.g. $PowerShell$) in the subject and sent from your specific email address.
  2. You send the PowerShell script in the email body and put the keyword in the subject.
  3. The Outlook rule starts an Outlook script and a PowerShell script.
  4. The Outlook script saves the email as a text file and waits for the transcript.
  5. The PowerShell script executes the script exported by Outlook.
  6. Outlook sends the result back.

That is it!

No to the details on how to set this up!
1. Outlook script:
a. In Outlook (I am using 2007 but this should work on the previous ones just fine), click Tools/Macro/Visual Basic Editor.
b. Paste this script into the editor:

' (C) Dmitry Sotnikov
' https://dmitrysotnikov.wordpress.com
' Add this to your Outlook macros project
' Then associate SaveAsText with a rule procesing
' emails from your address with a keyword in subject

' This is to have a Sleep function in Outlook
Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

' The main function saving the script email as text
' and sending back the transcript
Sub SaveAsText(MyMail As MailItem)
    ' Export email (with PowerShell script in body) as a text file
    MyMail.SaveAs "c:\scripts\outlook.ps1", olTXT
    
    ' Create a response email
    Dim reMail As Outlook.MailItem
    Set reMail = MyMail.Reply
    
    ' wait till transcript is available
    Set fs = CreateObject("Scripting.FileSystemObject")
    While Not fs.FileExists("C:\Scripts\email_transcript.txt")
        Sleep 1000
    Wend
    
    ' attach the transcript and send it back
    reMail.Attachments.Add "C:\Scripts\email_transcript.txt"
    reMail.Send
End Sub

c. Close the Editor.

2. Create a PowerShell script which processes the script (removes the message header, executes, saves transcript). I called it execute_email.ps1 and saved to c:\scripts. Here’s the script:

# (C) Dmitry Sotnikov
# https://dmitrysotnikov.wordpress.com
# This is a PowerShell companion script for Outlook
# macro processing PowerShell commands from email

# Delete any previous transcripts and start a new one
Remove-Item "c:\Scripts\email_transcript.txt" -ErrorAction SilentlyContinue
Start-Transcript "c:\Scripts\email_transcript_temp.txt"

# wait till Outlook saves the script email
while ( -not (Test-Path "c:\Scripts\outlook.ps1")) {
    Start-Sleep -Seconds 1
}

# Read the script, skip the header lines, execute the rest
Get-Content "c:\Scripts\outlook.ps1" | Where { $i++ -gt 4 } > "c:\Scripts\justscript.ps1"
. "c:\Scripts\justscript.ps1"

# Remove the old script
Remove-Item "c:\Scripts\outlook.ps1" -ErrorAction SilentlyContinue
Remove-Item "c:\Scripts\justscript.ps1" -ErrorAction SilentlyContinue

# Stop transcript and make it available for Outlook to send back
Stop-Transcript
Rename-Item "c:\Scripts\email_transcript_temp.txt" -NewName "email_transcript.txt"

3. Create a cmd file which starts PowerShell and executes the script. I called it execute_email.cmd, saved to the same folder c:\scripts and it just have one single line:
powershell.exe "c:\scripts\execute_email.ps1"

4. In Outlook click Tools/Rules and Alerts and create the rule, which executes the Outlook macro and the cmd:

Outlook rule to export PowerShell script, execute it, and send back the transcript

You have just created a remote execution system working from any phone or internet kiosk!

Let’s test it. For example, let’s say I need to add someone to a group. I just send the script to my email address:

A sample email with a PowerShell script

Outlook at my desk gets the email, saves it as text, kicks PowerShell execution, and sends me back the transcript.

Just make sure you change the keyword for something no one can guess, take your smartphone with you and go home. There’s no need to be sitting by your desk anymore. 😉

Acknowledgments: this is based on a great Lifehacker forum post on shutting down a computer based on a message. They also have posts on using other email clients such as Thunderbird or Mac Mail.app.

For your convenience I am also attaching the script files:

[UPDATE] Important: Just to make it clear: return address does not guarantee security and can be easily faked. Make sure you keep the keyword in secret or implement other means of additional protection – see one of my comments below. (So weird that Outlook does not allow to execute rules only if the email signature is verified. This could be another additional way to protect the system.)

[UPDATE 2] There’s also now a commercial alternative solution – PowerGUI Pro MobileShell – which gives in-browser PowerShell prompt from any computer or mobile device to a server in your IT environment.

Tags: , , ,


My Recent Tweets

Legal

The posts on this blog are provided “as is” with no warranties and confer no rights. The opinions expressed on this site are mine and mine alone, and do not necessarily represent those of my employer - WSO2 or anyone else for that matter. All trademarks acknowledged.

© 2007-2014 Dmitry Sotnikov

May 2021
M T W T F S S
 12
3456789
10111213141516
17181920212223
24252627282930
31  

%d bloggers like this: