Showing posts with label PowerShell. Show all posts
Showing posts with label PowerShell. Show all posts

Connect PowerShell to Office 365 cloud

We do quite a few Office 365 migrations and recently found out you can connect PowerShell to the Office 365 cloud and do quite a lot of tasks that way instead of using their web interface. This is going to make our jobs much easier. I will show you how to connect to 365 and some examples of things you can do. Some of the more powerful scripts such as user control require you to install the Office 365 sign in tool and the Microsoft Online PowerShell snap-in.

To be able to run commands that affect user accounts you must install the Microsoft Online Services Module for PowerShell which can be found here which also requires the single sign on tool located here.

To connect to Office 365 with PowerShell run the following 4 commands. You will be prompted for your account credentials.

set-executionpolicy remotesigned
$LiveCred = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $LiveCred -Authentication Basic -AllowRedirection
Import-PSSession $Session
To connect to the user management service issue the following
connect-msolservice
To set a users password to something you know and set them to not have to change it
Set-MsolUserPassword -UserPrincipalName CHANGETO@USERNAME -NewPassword SETTHISTOTHENEWPW -ForceChangePassword $false
To set all users to not have to change password every 90 days
Get-MsolUser | Set-MsolUser –PasswordNeverExpires $True

Get details about user mailboxes on Exchange 2010

Ever wanted to see how much email all of your users have or how much space their deleted items is taking up? This PowerShell command will give you some nice details on all of your mailboxes on an Exchange Server. Replace exchange with your server name.

Get-MailboxStatistics -server exchange | where {$_.ObjectClass -eq "Mailbox"} | Sort-Object TotalItemSize -Descending | ft @{label="User";expression={$_.DisplayName}},@{label="Total Size (MB)";expression={$_.TotalItemSize.Value.ToMB()}},@{label="Items";expression={$_.ItemCount}},@{label="DeletedItems";expression={$_.deletedItemCount}},@{label="DeletedItemSize (KB)";expression={$_.totalDeletedItemSize.value.toKB()}},@{label="Storage Limit";expression={$_.StorageLimitStatus}} -auto

You will get a report like this

 User                         Total Size (MB)  Items DeletedItems DeletedItemSize (KB) Storage Limit
----                              ---------------             -----      ------------   --------------------     -------------
User1                          10466                  96237          490                 2888           NoChecking
User2                            6021                  71813          248                 5219           NoChecking
User3                            4033                  46138          809                 7921           NoChecking
User4                            3843                  37157          945                 4141           NoChecking

How to remove multiple contacts from a users Exchange 2010 mailbox

We recently noticed that we had a user with 516,000 contacts in his mailbox. Many of them duplicated hundreds of times. We figured out this was an issue that other people had seen when switching from one mobile device to another. Mostly it seems from a BlackBerry to an Android. For some reason this has caused some users to experience a massive replication of contacts. I did not delve much into why as this had stopped already but we needed to clean up his current contacts. He had already tried to  manually do it but this was not working.

It turned out the easiest way to clean up the contacts was to have him backup 1 copy of the correct contacts and then run the following PowerShell command.

 Search-Mailbox -Identity "<user name>" -SearchQuery kind:contacts -DeleteContent -TargetMailbox "<logging mailbox>" -TargetFolder "SearchAndDeleteLog" -LogLevel Full

This command will search the <user name> mailbox for all contacts and delete them. This process will be logged into the folder SeachAndDeleteLog in the account you specify in <logging mailbox>

After this completed (about 3 hours) we had him replace his saved contacts.

Search-Mailbox replaces the old Export-Mailbox with deletecontent in Exchange 2010.

More information on Search-Mailbox can be found at http://technet.microsoft.com/en-us/library/dd298173.aspx

You can find information on advanced querying here http://msdn.microsoft.com/en-us/library/aa965711%28v=vs.85%29.aspx

Create multiple distribution groups with powershell and a CSV

So recently I had a need to create over 100 mail enabled enabled security groups for a new application we are rolling out. I really did not want to do this by hand. Powershell it turns out is a great resource for doing this. Create a CSV file with headers (header fields are important!) for example:

name,OU,email
group1,mydomain.com/distrogroups/ou1,group1@mydomain.com
group2,mydomain.com/distrogroups/ou1,group2@mydomain.com
group3,mydomain.com/distrogroups/ou2,group3@mydomain.com

Then if your file is c:\newgroups.csv run the following Powershell command

Import-CSV "C:\newgroups.csv" | % { New-DistributionGroup -Name $_.name -OrganizationalUnit $_.OU -PrimarySmtpAddress $_.email -Type Security }

This will import your CSV file and parse it line by line replacing each $_ value with the correct value under the header for that line. There is one extra value at the end (-Type Security) that makes every group a mail enabled security group which can be omitted to create distribution only groups.

You can add or remove fields as needed just add or remove the $_ value and create a new header line. You can find a list of acceptable fields by entering Get-Help New-DistributionGroup -Detailed at an exchange Powershell prompt. You can name the header fields whatever you want.

If you just want to create AD groups you can use the following

Import-CSV "C:\newgroups.csv" | % { New-ADGroup -Name $_.name -groupscope Global }

Monitoring Cluster Shared Volumes without SCOM

Recently we had one of our SAN volumes attached to our VM cluster run out of space. This was a bit of a surprise since I had thought our SAN would warn us when a volume was getting low but it turns out it won't. Luckily all that happened was our virtual guest paused itself so there was no data loss but this was a production server so we needed to make sure this would not continue to happen. Hunting for a way to monitor Cluster Shared Volume (CSV) status I really could not find a way other than Microsoft System Center Operations Manager (SCOM) which is not an option for us. So instead I started looking at scripting something in Powershell.  I knew I could get the available disk space via the VMM cluster console so a script should be possible.

I was able to put this script together thanks to several great examples from others. It will check the CSV status and if it falls below a certain threshold it will send an email to the address specified. You will need to modify a few of the lines below for email server, to address, etc.

    #Load the FailoverClusters module
    Import-Module FailoverClusters

    $warninglevel = 15  # The percent to send warning at
    $objs = @()
    $nl = [Environment]::NewLine

    $csv_status = Get-ClusterSharedVolume
    foreach ( $csv in $csv_status )
    {
       $expanded_csv_info = $csv | select -Property Name -ExpandProperty SharedVolumeInfo
       foreach ( $csvinfo in $expanded_csv_info )
       {
          $obj = New-Object PSObject -Property @{
             Name        = $csvinfo.Name
             Path        = $csvinfo.FriendlyVolumeName
             Size        = $csvinfo.Partition.Size
             FreeSpace   = $csvinfo.Partition.FreeSpace
             UsedSpace   = $csvinfo.Partition.UsedSpace
             PercentFree = $csvinfo.Partition.PercentFree
          }
          if ($csvinfo.Partition.PercentFree -lt $warninglevel) { $objs += $obj }
       }
    }


    if ($objs.count -gt 0) {
        $smtpServer = "mailserver"
        $msg = new-object Net.Mail.MailMessage
        $smtp = new-object Net.Mail.SmtpClient($smtpServer)
        $msg.From = "from address"
        $msg.To.Add("to address")
        $msg.Priority = "high"
        $msg.Subject = "Warning Cluster Volume low on space"
        #Preamble text
        $msg.body = "Enter any explanatory message here or delete this line"              
        #Next line is what puts in the volume information
        $msg.body += $objs | ft -auto Name,Path,@{ Label = "Size(GB)" ; Expression = { "{0:N2}" -f ($_.Size/1024/1024/1024) } },@{ Label = "Free(GB)" ; Expression = { "{0:N2}" -f ($_.FreeSpace/1024/1024/1024) } },@{ Label = "Used(GB)" ; Expression = { "{0:N2}" -f ($_.UsedSpace/1024/1024/1024) } },@{ Label = "PercentFree" ; Expression = { "{0:N2}" -f ($_.PercentFree) } } | Out-String
        $smtp.Send($msg)

    }

To make this work create the script in a ps1 file. Modify the settings that need to be modified and adjust your warning threshold to a percent you like. Create a scheduled job to run it at whatever interval you wish. I run mine every 15 minutes. When creating the job make sure the program you run is powershell.exe then give it a command line option of your script name.