Thursday, February 12, 2015

Use Google Sheets cell content in script


Wouldn't it be nice to collect data using a Google Sheets Form and be able to get each cell value from a script on your phone or computer? It can be done.

I'm assuming the data you need for your script is already in a Google Sheet. It could be collected using a form or similar. To get unauthenticated access to a Google Sheet it needs to be published. Either publish the sheet containing the data or create a and publish new Google Sheet to hold only the data needed for the script. Import the data to that new sheet using =IMPORTRANGE().

To get the URL for the published sheet, have a look at this page: https://developers.google.com/gdata/samples/spreadsheet_sample. Basically you just need the key for the sheet.

The published sheet URL looks something like this:

Cell C2 would look like this:

OK, on to the content. Below is the content I get when requesting cell R1C1. The actual data is between the tags <content type='text'> and </content>

<?xml version='1.0' encoding='UTF-8'?><entry xmlns='http://www.w3.org/2005/Atom' xmlns:batch='http://schemas.google.com/gdata/batch' xmlns:gs='http://schemas.google.com/spreadsheets/2006'><id>https://spreadsheets.google.com/feeds/cells/<key>/od6/public/basic/R1C1</id><updated>2014-12-12T07:35:19.026Z</updated><category scheme='http://schemas.google.com/spreadsheets/2006' term='http://schemas.google.com/spreadsheets/2006#cell'/><title type='text'>A1</title><content type='text'>2</content><link rel='self' type='application/atom+xml' href='https://spreadsheets.google.com/feeds/cells/<key>/od6/public/basic/R1C1'/></entry>

We just need to split the content on <content type='text'> and then split the second part again on </content>. The cell data is in the first part of the second split.

PowerShell example:
$CellA1 = Invoke-WebRequest -UseBasicParsing -Uri https://spreadsheets.google.com/feeds/cells/1DzK0hnq9bexu6h1ryZzPP6-WWk55IEx0xZrtFKK6UZI/od6/public/basic/R1C1
$Value = (($CellA1 -split "<content type=.text.>") -split "</content")[1]
Tasker example:
GetValueFromSheet (4)
A1: HTTP Get [ Server:Port:https://spreadsheets.google.com/ Path:feeds/cells/<key>/od6/public/basic/R1C1 Attributes: Cookies: User Agent: Timeout:10 Mime Type: Output File: Trust Any Certificate:Off ] 
A2: Variable Split [ Name:%HTTPD Splitter:<content type='text'> Delete Base:On ] 
A3: Variable Split [ Name:%HTTPD2 Splitter:</content> Delete Base:On ] 
A4: Variable Set [ Name:%Value To:%HTTPD21 Do Maths:Off Append:Off ] 
The content of A1 in the Google Sheet is now in Tasker variable %Value. You could use this to trigger other Tasker tasks or to present that value on a Zooper Widget, or send it to Pushover. I use it for a few things, and might write a more detailed end-to-end post on that.

Wednesday, February 11, 2015

Change Exchange primary email address to lower case

By default Microsoft Exchange creates email addresses on the form First.Last@domain.com. If you change the email address policy to use lowercase, the existing email addresses are not updated to reflect that change.

It doesn't work to change the primary SMTP address to lower case right away, since email addresses are basically case insensitive. When you set a new primary SMTP address, the old address is kept as an alias email address. Exchange can't set a new primary email address since the same address already exists as an alias. More or less, you get the picture.

I created the following script to make the change


# Get all mailboxes in the users OU (select the OU for which you want to change to lower case
$Mailboxes = Get-Mailbox -OrganizationalUnit "OU=Users,DC=domain,DC=com" -ResultSize Unlimited
# Loop through all mailboxes
ForEach ($Mailbox in $Mailboxes)
{
    # Turn off email address policy
    Set-Mailbox -Identity $Mailbox.Identity -EmailAddressPolicyEnabled $false
    # Set a temporary primary email address
    Set-Mailbox -Identity $Mailbox.Identity -PrimarySmtpAddress "dummy@domain.com"
    # Remove the old primary address which is now a standard email address connected to the mailbox
    Set-Mailbox -Identity $Mailbox.Identity -EmailAddresses @{Remove=$Mailbox.PrimarySmtpAddress}
    # Convert the old primary address to lowercase
    $lowercasesmtp = $Mailbox.PrimarySmtpAddress.ToLower()
    # Set the lowercase email address as primary
    Set-Mailbox -Identity $Mailbox.Identity -PrimarySmtpAddress $lowercasesmtp
    # Remove the temp primary address
    Set-Mailbox -Identity $Mailbox.Identity -EmailAddresses @{Remove='dummy@domain.com'}
    # Turn on the address policy
    Set-Mailbox -Identity $Mailbox.Identity -EmailAddressPolicyEnabled $true
    # Check the result
    Get-Mailbox -Identity $Mailbox.Identity | select Name, *SMTP*, Email*
}

Wednesday, January 21, 2015

Exchange 2013 mailbox quota usage and size report

In Exchange 2013 it can be a bit hard to find mailboxes that are close to their quota limits. You can see it in the Exchange Admin Center, but that is a tedious task if you want to check all mailboxes.
You can also wait for the users to contact you when they get a quota warning, or when they no longer can send email. That's a bit late.
With PowerShell you can easily find out the mailbox size, but the quota limit is either Unlimited, which means that the mailbox database defaults are used, or it can be set at a certain limit.

Find the mailbox quota
get-mailbox mailbox | select-object DisplayName, ProhibitSendQuota, ProhibitSendReceiveQuota

DisplayName ProhibitSendQuota ProhibitSendReceiveQuota
----------- ----------------- ------------------------
User Name   Unlimited         Unlimited

Find the mailbox size and database quota
Get-MailboxStatistics -identity mailbox | select-object Displayname,TotalItemSize,TotalDeletedItemSize,DatabaseIssueWarningQuota,DatabaseProhibitSendQuota

DisplayName               : User Name
TotalItemSize             : 1.125 GB (1,208,281,527 bytes)
TotalDeletedItemSize      : 24.14 MB (25,309,210 bytes)
DatabaseIssueWarningQuota : 5 GB (5,368,709,120 bytes)
DatabaseProhibitSendQuota : 6 GB (6,442,450,944 bytes)


So, the numbers are all there, just not in a nice format...

To make a long story short - here's a PowerShell script that will output all mailboxes with a quota usage over 80%

<#
.SYNOPSIS
    TGet-MailboxSizeQuota.ps1 returns all mailboxes above a certain quota (ProhibitSendQuota) usage.
.DESCRIPTION
    TGet-MailboxSizeQuota.ps1 returns all mailboxes with a quota usage of 80% and above.
    If you want to check for another quota limit, pass the percentage as a parameter.

    TGet-MailboxSizeQuota.ps1 
.EXAMPLE
    TGet-MailboxSizeQuota.ps1
    The above command will return all mailboxes with a quota usage of 80% and above
.EXAMPLE
    TGet-MailboxSizeQuota.ps1 85
    The above command will return all mailboxes with a quota usage of 85% and above
.NOTES
    Author: Peter Haake
    Date:   2015-01-20    
#>
#
# Load the Exchange Management Module
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.SnapIn
# Make sure en-us locale is used no matter what the server/user has configured
# Keep this section if you output decimal numbers
# Slightly modified from From http://occasionalutility.blogspot.com.au/2014/03/everyday-powershell-part-17-using-new.html
[System.Reflection.Assembly]::LoadWithPartialName("System.Threading")>$null
[System.Reflection.Assembly]::LoadWithPartialName("System.Globalization")>$null
[System.Threading.Thread]::CurrentThread.CurrentCulture = [System.Globalization.CultureInfo]::CreateSpecificCulture("en-us")

# Set quotalimit to the first parameter passed. If no parameter is passed, set it at 80%
if ([INT]$args[0] -gt "") {
    $quotalimit = [INT]$args[0]
    }
else {
    $quotalimit = 80
}

# Get all mailboxes
$Mailboxes = @(Get-Mailbox -ResultSize Unlimited | select-object DisplayName, Identity, ProhibitSendQuota, ProhibitSendReceiveQuota)
# Clear the report object variable
$Report =@()

# Loop through all mailboxes
foreach ($usr_mailbox in $Mailboxes)
{
    # Get statistics for all mailboxes
    $usr_mailboxstats = Get-MailboxStatistics -identity $usr_mailbox.Identity | select-object Displayname,Identity,Database,TotalItemSize,TotalDeletedItemSize,DatabaseIssueWarningQuota,DatabaseProhibitSendQuota

    #Convert TotalItemSize to INT64 and remove crap (looks like this initially "1.123 GB (1,205,513,370 bytes)" and comes out as a numeric 1205513370)
    [int64]$usr_mailboxstats_totalitemsize = [convert]::ToInt64(((($usr_mailboxstats.TotalItemSize.ToString().split("(")[-1]).split(")")[0]).split(" ")[0]-replace '[,]',''))
    #Convert TotalDeletedItemSize to INT and remove crap (looks like this initially "1.123 GB (1,205,513,370 bytes)" and comes out as a numeric 1205513370)
    [int64]$usr_mailboxstats_totaldeleteditemsize = [convert]::ToInt64(((($usr_mailboxstats.TotalDeletedItemSize.ToString().split("(")[-1]).split(")")[0]).split(" ")[0]-replace '[,]',''))

    # If the mailbox quota is Unlimited, then the database defaults are used.
    if ($usr_mailbox.ProhibitSendQuota -eq "Unlimited") {
        # Get quota from Database
        [INT64]$usr_quota = [convert]::ToInt64(((($usr_mailboxstats.DatabaseProhibitSendQuota.ToString().split("(")[-1]).split(")")[0]).split(" ")[0]-replace '[,]',''))
        }
    else {
        # Get quota from user mailbox
        [INT64]$usr_quota = [convert]::ToInt64(((($usr_mailbox.ProhibitSendQuota.ToString().split("(")[-1]).split(")")[0]).split(" ")[0]-replace '[,]',''))
    }
    # Calculate the quota percentage
    $usr_quota_percentage = [INT]((($usr_mailboxstats_totalitemsize + $usr_mailboxstats_totaldeleteditemsize) / $usr_quota)*100)

    # Add to report object
    if ($usr_quota_percentage -ge $quotalimit) {
        $usr_reportObject = New-Object PSObject
        $usr_reportObject | Add-Member -MemberType NoteProperty -Name "DisplayName" -Value $usr_mailboxstats.DisplayName
        $usr_reportObject | Add-Member -MemberType NoteProperty -Name "TotalItemSize" -Value $usr_mailboxstats_totalitemsize
        $usr_reportObject | Add-Member -MemberType NoteProperty -Name "TotalDeletedItemSize" -Value $usr_mailboxstats_totaldeleteditemsize
        $usr_reportObject | Add-Member -MemberType NoteProperty -Name "ProhibitSendQuota" -Value $usr_quota
        $usr_reportObject | Add-Member -MemberType NoteProperty -Name "QuotaPercent" -Value $usr_quota_percentage
        $report += $usr_reportObject
    }
}
# Output the report, sorted with the highest quota percentage at the top
$Report | Sort-Object QuotaPercent -Descending

 Output looks something like this

DisplayName  TotalItemSize  TotalDeletedItemSize  ProhibitSendQuota  QuotaPercent
-----------  -------------  --------------------  -----------------  ------------
User Name       8316860830              49373170         9663676416            87
Second User    14581624515              17277483        17179869184            85
Third Person    5472939739              15151742         6442450944            85

Send the output from the script as an email

If you want to schedule the script to run every week or so, it might be convenient to have the output sent to you in an email. Create another script, and call TGet-MailboxSizeQuota.ps1 from that as below:

Send-MailMessage -to email@domain.com -Subject "Quota Report" -SmtpServer mail.server.FQDN -From from@domain.com -Body (C:\Scripts\TGet-MailboxSizeQuota.ps1 | ft | Out-String)

This can easily be added as a scheduled task. Just make sure to run the task under a user account that has enough rights in Exchange.

Friday, December 5, 2014

Getting New-MailboxExportRequest work with date variables in ContentFilter


The following script exported the full mailbox, ignoring the date range in ContentFilter. I couldn't figure it out. Found a lot of people with the same problem. 

$StartDate = (Get-Date).AddDays(-1).Date
$EndDate = (Get-Date).Date
$FilePath = "\\server\export.pst"
New-MailboxExportRequest -Mailbox peter -Name TestExport -FilePath $FilePath -ContentFilter {(Received -gt $StartDate) -and (Received -lt $EndDate)}
I finally found a solution here: http://occasionalutility.blogspot.com.au/2014/03/everyday-powershell-part-17-using-new.html Turns out it will only accept dates in US formats, and since I'm in Sweden it just failed.

The working script looks like this:

[System.Reflection.Assembly]::LoadWithPartialName("System.Threading")
[System.Reflection.Assembly]::LoadWithPartialName("System.Globalization")
[System.Threading.Thread]::CurrentThread.CurrentCulture = [System.Globalization.CultureInfo]::CreateSpecificCulture("en-us") 
$StartDate = (Get-Date).AddDays(-1).Date
$EndDate = (Get-Date).Date
$FilePath = "\\server\petero-"+(Get-Date).AddDays(-1).ToString("yyyy-MM-dd")+".pst"
$filter = "(Received -gt '"+$StartDate+"') -and (Received -lt '"+$EndDate+"')"
New-MailboxExportRequest -Name TestExport -Mailbox peter -ContentFilter $filter -FilePath $FilePath

Thursday, March 28, 2013

Find your phone with Tasker and Pushover




Tasker is a tool to automate almost anything on Android. I use it to adjust volumes on a schedule, turn off pattern lock screen at home, etc. I will write more posts about Tasker, but if you want to try it out there's a 7-day trial version on the Tasker site, and a full, paid version on Play Store. I can recommend the Pocketables Beginner's Guide to Tasker series, the Userguide on Taskers web site and this Tasker Wiki

I already mentioned Pushover in a previous post, but essentially it's a tool to send notification to mobile devices (Android and iOS).

I wanted a way to locate my mobile phone in case it's lost. There are many apps that can do this already, but with Tasker you can do it yourself. I didn't even have to figure out how to do it myself, as a good recipe  is already available on a Tasker Wiki. There are some variants on that site and I ended up with the tasker code below.
To find your phone, send a text message to your lost from from any other mobile phone with <your keyword> in the message. Tasker will trigger, get the phone location using any of the methods available (GPS or WiFi positioning) and send back a text message with a Google Maps URL with your lost phones position mapped out.

Tasker Profile
Profile: LocateSMS (2)
Event: Received Text [ Type:Any Sender:* Content:<your keyword> ]
Enter: LocationPushover (3)

Tasker Task
LocationPushover (3)
A1: Get Location [ Source:Any Timeout (Seconds):120 Continue Task Immediately:Off Keep Tracking:Off ]
A2: Variable Set [ Name:%LOCATION To:%LOCN Do Maths:Off Append:Off ] If [ %LOC ! Set ]
A3: Variable Set [ Name:%LOCATION To:%LOC Do Maths:Off Append:Off ] If [ %LOC Is Set ]
A4: Send SMS [ Number:%SMSRF Message:http://maps.google.com/maps?q=%LOCATION Store In Messaging App:Off ]
A5: Variable Clear [ Name:%LOCATION Pattern Matching:Off ]

This is nice, but since I've started to use Pushover for notifications I wanted to try that out as well. Reading up on the Pushover API I figured the easiest way is to do a HTTP Post from Tasker with a properly formatted Path. Since I want to send a URL in the notification message I need to URL encode it, otherwise Pushover API would try to interpret the /, ? and & as part of the API URI. I URL encoded the Google Maps 

URL part and ended up with a new step four in the Tasker Task.

A4: HTTP Post [ Server:Port:https://api.pushover.net Path:/1/messages.json?user=<user token>&token=<app token>&title=Phone+location&message=http%3A%2F%2Fmaps.google.com%2Fmaps%3Fq%3D%LOCATION Data / File: Cookies: Timeout:10 Content Type:application/x-www-form-urlencoded Output File: ]
URL Encoding is easy. A good guide is available at the w3schools.com website. This URL:
http://maps.google.com/maps?q=%LOCATION
is turned into this:
http%3A%2F%2Fmaps.google.com%2Fmaps%3Fq%3D%LOCATION

In addition to the Tasker script, I created a new Pushover application, added a Google Maps icon and that was it. When I send a text with my keyword I get the following Pushover notification on all my devices.


If you want to use the code above, you just need to change <your keyword> to a keyword of your choice. This is the word you need to text to your lost phone to trigger the Tasker Profile and Task. In the code you also need to replace <user token> and <app token> if you want to use Pushover.

Wednesday, March 27, 2013

Get notified when your computer reboots using Pushover


Pushover is a platform for sending and receiving push notifications to mobile devices (Android and iOS). Pushover is free, but requires the installation of a paid app on your Android or iOS device. After you set up your account on Pushover you get a user token that is used to identify you as the sender of a notification.
To send notifications, create a new application on the Pushover site. Give it a name, select type and upload an icon. After the application is registered you get an application token that identifies your application.

OK, so I wanted a notification sent to my phone whenever my computer restarted. Since it's a Windows 8 computer I decided to go for PowerShell 3.0 and created the following script:
$uri = "https://api.pushover.net/1/messages.json"
$parameters = @{
  token = "<app token>"
  user = "<user token>"
  title = "Reboot"
  message = "Your computer just rebooted"
}
$parameters | Invoke-RestMethod -Uri $uri -Method Post
Nothing special about the script, basically it's a slight modification of an example script found on the Pushover FAQ. Just replace <app token> and <user token> with your own tokens.

Next, I need to have the script run when the computer starts, and run before anyone logs on. That's the point, right, if I'm at the computer I don't need a notification telling me the computer restarted.
Run the Local Group Policy Editor (gpedit.msc) tool as administrator and drill down to Local Computer Policy -> Computer Configuration -> Windows Settings -> Scripts and open Startup.


Go to the PowerShell Scripts tab and click Add. Click Browse next to Script Name and locate your script. Click OK, OK and then close the policy editor.

All done!

Monday, March 25, 2013

PowerShell Books


Just found PowerShellBooks.com (http://bit.ly/11Cf4Dw) that lists a number of PowerShell books, and also provides three books for free download in PDF format.