Office 365 – How to connect with Powershell

office365 powershell

In Office 365 you can do and automate a lot with Windows Powershell. Now this small post shows you how you can connect to Office 365 with Powershell.

  1. Install the Microsoft Online Services Sign-In Assistant
    32-bit
    64-bit
  2. Install the Microsoft Online Services Module for Windows PowerShell
    32-bit
    64-bit
  3. Open Powershell and import the MsOnline Module or use the desktop shortcut which was created by the installer.
    Import-Module MsOnline
  4. Connect to your Microsoft Office 365 account
    Connect-MsolService

    Use your Office 365 LiveID to login (for example bob@bobscompany.onmicrosoft.com)

  5. Now you can start working with Windows Powershell in your Office 365 account, if you need some more help about the available Powershell cmdlets you can list them with
    Get-Command -Module MsOnline

Powershell: How to export Windows Eventlogs with Powershell

Powershell Header

This is a little dirty Windows Powershell script which exports or backups Windows Eventlogs. The script creates a .evt file which can be used with the Windows Eventlog Viewer.

# Config
$logFileName = "Application" # Add Name of the Logfile (System, Application, etc)
$path = "C:\temp\" # Add Path, needs to end with a backsplash

# do not edit
$exportFileName = $logFileName + (get-date -f yyyyMMdd) + ".evt"
$logFile = Get-WmiObject Win32_NTEventlogFile | Where-Object {$_.logfilename -eq $logFileName}
$logFile.backupeventlog($path + $exportFileName)

And with the next code it cleans up older exported Eventlogs.

# Deletes all .evt logfiles in $path
# Be careful, this script removes all files with the extension .evt not just the selfcreated logfiles
$Daysback = "-7"

$CurrentDate = Get-Date
$DatetoDelete = $CurrentDate.AddDays($Daysback)
Get-ChildItem $Path | Where-Object { ($_.LastWriteTime -lt $DatetoDelete) -and ($_.Extension -eq ".evt") } | Remove-Item

UPDATE: If you wanna clean the Eventlog after the export you can do that by using the Clear-Eventlog cmdlet. (Thanks to Michel from server-talk.eu)

Clear-Eventlog -LogName $logFileName

And here the whole “script”

# Config
$logFileName = "Application" # Add Name of the Logfile (System, Application, etc)
$path = "C:\temp\" # Add Path, needs to end with a backsplash

# do not edit
$exportFileName = $logFileName + (get-date -f yyyyMMdd) + ".evt"
$logFile = Get-WmiObject Win32_NTEventlogFile | Where-Object {$_.logfilename -eq $logFileName}
$logFile.backupeventlog($path + $exportFileName)

# Deletes all .evt logfiles in $path
# Be careful, this script removes all files with the extension .evt not just the selfcreated logfiles
$Daysback = "-7"

$CurrentDate = Get-Date
$DatetoDelete = $CurrentDate.AddDays($Daysback)
Get-ChildItem $Path | Where-Object { ($_.LastWriteTime -lt $DatetoDelete) -and ($_.Extension -eq ".evt") } | Remove-Item
Clear-Eventlog -LogName $logFileName

Microsoft Office 365

office365

In the last days I started to work with the Microsoft beta of Office 365. After testing it for a while I think this could be a great solution for small & medium businesses. And its a really hard competitor to Google Apps. There are a lot of advantage which Office 365 has agains Google Apps and I think because it is a Microsoft Solution for a lot of companys this is the better way to go, if they already used Microsoft Products or have a Microsoft enviroment.

  • More options and features instead of  Google Apps, for example in Exchange or Forfront which protects Exchange and SharePoint Online for free.
  • Microsoft Solutions – the most people and companys already use them.
  • Powershell - This is a really cool feature. You can administrate  the whole Office365 online serivce with Windows Powershell.

In the next few weeks I will post some blog post about how to use Office 365 and some Powershell How To posts.

Powershell: Create a tempfile with Powershell

Powershell Header

Sometimes you need to save some data in to a tempfile. And instead of creating a ownen file for this you could use the .NET function to create a really tempfile in the tempfile directory.

This is the how you can create a new tempfile:

$tempFile = [System.IO.Path]::GetTempFileName()

And now you can parse data into this file.

Powershell: Run MySQL Querys with Powershell

Powershell Header
In our Hosting enviroment we are now using MS SQL Servers for our back-end. But there are still some MySQL Server left which store some data. Now since we do a lot of automation with Windows Powersehll I wrote a function to run MySQL querys with Powershell.

First you have to install the MySQL .NET Connector or just copy the MySql.Data.dll from the MySQL.

You can now load this:

With DLL File:

 [void][system.reflection.Assembly]::LoadFrom("C:\myscript\MySQL.Data.dll")

or if you have installed the MySQL .NET Connector:

 [void][System.Reflection.Assembly]::LoadWithPartialName("MySql.Data") 

Now basiclly this function does everything for you:

Function Run-MySQLQuery {
<#
.SYNOPSIS
   run-MySQLQuery

.DESCRIPTION
   By default, this script will:
    - Will open a MySQL Connection
	- Will Send a Command to a MySQL Server
	- Will close the MySQL Connection
	This function uses the MySQL .NET Connector or MySQL.Data.dll file

.PARAMETER ConnectionString
    Adds the MySQL Connection String for the specific MySQL Server

.PARAMETER Query

    The MySQL Query which should be send to the MySQL Server

.EXAMPLE
    C:\PS> run-MySQLQuery -ConnectionString "Server=localhost;Uid=root;Pwd=p@ssword;database=project;" -Query "SELECT * FROM firsttest" 

    Description
    -----------
    This command run the MySQL Query "SELECT * FROM firsttest"
	to the MySQL Server "localhost" with the Credentials User: Root and password: p@ssword and selects the database project

.EXAMPLE
    C:\PS> run-MySQLQuery -ConnectionString "Server=localhost;Uid=root;Pwd=p@ssword;database=project;" -Query "UPDATE firsttest SET firstname='Thomas' WHERE Firstname like 'PAUL'" 

    Description
    -----------
    This command run the MySQL Query "UPDATE project.firsttest SET firstname='Thomas' WHERE Firstname like 'PAUL'"
	to the MySQL Server "localhost" with the Credentials User: Root and password: p@ssword

.EXAMPLE
    C:\PS> run-MySQLQuery -ConnectionString "Server=localhost;Uid=root;Pwd=p@ssword;" -Query "UPDATE project.firsttest SET firstname='Thomas' WHERE Firstname like 'PAUL'" 

    Description
    -----------
    This command run the MySQL Query "UPDATE project.firsttest SET firstname='Thomas' WHERE Firstname like 'PAUL'"
	to the MySQL Server "localhost" with the Credentials User: Root and password: p@ssword and selects the database project

#>
	Param(
        [Parameter(
            Mandatory = $true,
            ParameterSetName = '',
            ValueFromPipeline = $true)]
            [string]$query,
		[Parameter(
            Mandatory = $true,
            ParameterSetName = '',
            ValueFromPipeline = $true)]
            [string]$connectionString
        )
	Begin {
		Write-Verbose "Starting Begin Section"
    }
	Process {
		Write-Verbose "Starting Process Section"
		try {
			# load MySQL driver and create connection
			Write-Verbose "Create Database Connection"
			# You could also could use a direct Link to the DLL File
			# $mySQLDataDLL = "C:\scripts\mysql\MySQL.Data.dll"
			# [void][system.reflection.Assembly]::LoadFrom($mySQLDataDLL)
			[void][System.Reflection.Assembly]::LoadWithPartialName("MySql.Data")
			$connection = New-Object MySql.Data.MySqlClient.MySqlConnection
			$connection.ConnectionString = $ConnectionString
			Write-Verbose "Open Database Connection"
			$connection.Open()

			# Run MySQL Querys
			Write-Verbose "Run MySQL Querys"
			$command = New-Object MySql.Data.MySqlClient.MySqlCommand($query, $connection)
			$dataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($command)
			$dataSet = New-Object System.Data.DataSet
			$recordCount = $dataAdapter.Fill($dataSet, "data")
			$dataSet.Tables["data"] | Format-Table
		}
		catch {
			Write-Host "Could not run MySQL Query" $Error[0]
		}
		Finally {
			Write-Verbose "Close Connection"
			$connection.Close()
		}
    }
	End {
		Write-Verbose "Starting End Section"
	}
}

You can use this Powershell function like this:

run-MySQLQuery -ConnectionString "Server=localhost;Uid=root;Pwd=p@ssword;database=project;" -Query "SELECT * FROM firsttest"

If you wanna run more than one command you could do something like this:

$connString = "Server=localhost;Uid=root;Pwd=p@ssword;database=project;"

[array]$sQLDings += "SELECT * from project.firsttest"
[array]$sQLDings += "UPDATE project.firsttest SET firstname='Thomas' WHERE Firstname like 'Paul'"
[array]$sQLDings += "SELECT * from project.firsttest"

foreach($sQLquery in $SQLDings) {
	run-MySQLQuery -connectionString $connString -query $sQLquery
}

If you need more information about Powershell and MySQL Mark Alexander Bain wrote a blog post about this.

And if you need a local MySQL Server on your machine to test this, you could use Microsoft Platform Installer to install MySQL and other cool Webtools.

Powershell: Copy Logfiles with Date and Content

Powershell Header

Some days ago I made a blog post about Select-String in Powershell. I created a “script” or a better a command to check logfiles for a specitifc text and copy the logfile to another place.

Get-ChildItem C:\temp -Filter *.log -Recurse | Select-String "Contoso" |  Copy-Item -Destination C:\temp2

Now I added also a Startdate and a Enddate for the logfiles you wanna search in.

$Startdate = (get-date -year 2011 -month 3 -day 25)
$Enddate = (get-date -year 2011 -month 3 -day 30)

Get-ChildItem C:\temp -Filter *.log -Recurse | Where-Object {($_.LastWriteTime.Date -ge $Startdate.Date) -and ($_.LastWriteTime.Date -le $Enddate.Date)} | Select-String "Contoso" |  Copy-Item -Destination C:\temp2