Tuesday, 9 February 2016

What Is an Offline Storage Table (OST) File?

An OST file, or offline storage table (.ost) file, is an offline Outlook Data File used by Microsoft Exchange Server that enables users to work with their messages and mail data even when access to the mail server isn't available. OST files are used in two scenarios: with Microsoft Exchange Server’s Cached Exchange Mode and with the Outlook Connector for Windows Live Hotmail when accessing Hotmail mail.

There are two types of Outlook Data Files used by Outlook. A Personal Storage Table (.pst) is used for most accounts. If you are using a Microsoft Exchange account, your items are usually delivered to and saved on the mail server. To allow you to work with your messages even when you can’t connect to the mail server, a second type of data file that is named an offline Outlook Data File (.ost) is kept on your computer.

The primary differences between the two types of Outlook data files are as follows:

Personal Storage Table (.pst) files are used for POP3, IMAP, and web-based mail accounts. When you want to create archives or back up your Outlook folders and items on your computer, such as Exchange accounts, you must create and use additional .pst files.

Offline Storage Table (.ost) files are used when you have an Exchange account and want to work offline or use or use the default Cached Exchange Mode. This type of data file is also used for accounts that you set up with the Outlook Connector for Outlook.com (formerly Hotmail). Outlook Data Files (.ost) are always copies of items that are saved on a mail server and don’t have to be backed up like Outlook Data Files (.pst).
Read More...

Monday, 8 February 2016

Get all Licensed Office 365 users with PowerShell

It is very common requirement to get all the licensed users within an Office 365 tenant. We can use the Azure AD powershell cmdlet Get-MsolUser to list all the licensed office 365 users.

Note: Before proceed, Install and Configure Azure AD PowerShell

The following command just list the licensed office 365 users
Get-MsolUser -All | Where-Object { $_.isLicensed -eq ”TRUE” } | Select-Object UserPrincipalName, DisplayName, Department
The following command exports all the licensed users to csv file
Get-MsolUser -All | Where-Object { $_.isLicensed -eq ”TRUE” } | Select-Object UserPrincipalName, DisplayName, Department | Export-Csv C:\LicensedUsers.csv  -NoTypeInformation -Encoding UTF8
The above command just tell whether an user is licensed or not, doesn't list what kind of license has been applied to the users. The following powershell script get the detailed license plans and subscriptions that applied to every office 365 users and exports the output to csv file by using Export-CSV cmdlet.
$users = Get-MsolUser -All | Where-Object { $_.isLicensed -eq ”TRUE” }
$users | Foreach-Object{ 
  $licenseDetail = '' 
  $licenses='' 
  if($_.licenses -ne $null) {
ForEach ($license in $_.licenses){
  switch -wildcard ($($license.Accountskuid.tostring())) { 
           '*POWER_BI_STANDALONE' { $licName = 'POWER BI STANDALONE' } 
           '*CRMSTANDARD' { $licName = 'CRM Online' }
           '*O365_BUSINESS_PREMIUM' { $licName = 'Office 365 BUSINESS PREMIUM' } 
           '*ENTERPRISEPACK' { $licName = 'Office 365 (Plan E3)' }  
           default { $licName = $license.Accountskuid.tostring() }
        }         

  if($licenses){  $licenses = ($licenses + ',' + $licName) } else { $licenses = $licName}
ForEach ($row in $($license.servicestatus)) {

if($row.ProvisioningStatus -ne 'Disabled') {          
       switch -wildcard ($($row.ServicePlan.servicename)) { 
           'EXC*' { $thisLicence = 'Exchange Online' }  
           'LYN*' { $thisLicence = 'Skype for Business' } 
           'SHA*' { $thisLicence = 'Sharepoint Online' }       
           default { $thisLicence = $row.ServicePlan.servicename }  
       }         
 if($licenseDetail){ $licenseDetail = ($licenseDetail + ',' + $thisLicence) }  Else { $licenseDetail = $thisLicence}}
}}}
New-Object -TypeName PSObject -Property @{    
    UserName=$_.DisplayName  
    IsLicensed=$_.IsLicensed 
    Licenses=$licenses 
    LicenseDetails=$licenseDetail }
}  | Select UserName,IsLicensed,Licenses,LicenseDetails |
Export-CSV "C:\\Office-365-User-License-Report.csv" -NoTypeInformation -Encoding UTF8
Read More...

Monday, 1 February 2016

Office 365: Get-MsolUser

The Get-MsolUser cmdlet is an Azure AD powershell cmdlet. It can be used to get an individual user, or list of users information. An individual user will be retrieved if the ObjectId or UserPrincipalName parameter is used.

Note: Before proceed, Install and Configure Azure AD PowerShell

Retrieve single user:
Get-MsolUser -ObjectId <Guid>
-------------or---------------
Get-MsolUser -UserPrincipalName <UserPrincipalName>
Retrieve all users:
Get-MsolUser -All

Example 1

The following command retrieves all users in the company (up to 500 results).
Get-MsolUser

Example 2

The following command retrieves only first 100 users in the company.
Get-MsolUser -MaxResults 100

Example 3

The following command retrieves all the available users in the company.
Get-MsolUser -All

Example 4

The following command retrieves all the deleted users in the company.
Get-MsolUser -All -ReturnDeletedUsers

Example 5

The following command retrieves the user with the UPN morgan@mts.com
Get-MsolUser -UserPrincipalName morgan@mts.com

Example 6

The following command retrieves all the licensed users
Get-MsolUser -All | Where-Object { $_.isLicensed -eq "TRUE" }

Example 7

The following command retrieves and export all the licensed Office 365 users to csv file.
Get-MsolUser | Where-Object { $_.isLicensed -eq "TRUE" } | Select DisplayName,UserPrincipalName,IsLicensed |
Export-Csv c:\LicensedUsers.csv -NoTypeInformation

Example 8

The following command retrieves all users based on Department filter.
Get-MsolUser -All | Where { $_.Department -like "*Sales*" -or $_.Department -eq "Marketing" } |
Select DisplayName,UserPrincipalName,Department,IsLicensed

Example 9

The following command retrieves and export all the users with when they last changed their passwords in Office 365 to csv file.
Get-MsolUser -All | select DisplayName,UserPrincipalName, LastPasswordChangeTimeStamp | 
Export-CSV C:\LastPasswordChange_Report.csv -NoTypeInformation
Read More...

Sunday, 31 January 2016

Connect PowerShell to Office 365 through Proxy

Working with powershell to manage office 365 is one of the regular job for every Office 365 Admin. This is a follow up post to Connect Office 365 using Remote PowerShell through proxy.

You can use the below command to connect Office 365 using remote powershell:
$365Logon = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $365Logon -Authentication Basic -AllowRedirection
Import-PSSession $Session
The above command will work fine when you connect internet without proxy server, but you will receive the following error when connect via proxy.
[ps.outlook.com] Connecting to remote server failed with the following error message : The WinRM client cannot process the request because the server name cannot be resolved. For more information, see the about_Remote_Troubleshooting Help topic.
    + CategoryInfo          : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [], PSRemotingTransportException
    + FullyQualifiedErrorId : PSSessionOpenFailed
To overcome this problem, we need to use proxy setting options in New-PSSession command. To set the proxy options, use the following procedure:

1. Use the ProxyAccessType, ProxyAuthentication, and ProxyCredential parameters of the New-PSSessionOption cmdlet to create a session option object with the proxy settings for your enterprise. Save the option object is a variable.

2. Use the variable that contains the option object as the value of the SessionOption parameter of a New-PSSession command.
$365Logon = Get-Credential
$proxyOptions = New-PSSessionOption -ProxyAccessType IEConfig
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $365Logon -Authentication Basic -AllowRedirection -SessionOption $proxyOptions
Import-PSSession $Session
If you want to connect Office 365 through Outbound Internet Authenticating Proxy, you have to add addtional parameter -ProxyAuthentication in New-PSSessionOption cmdlet.
$proxyOptions = New-PSSessionOption -ProxyAccessType IEConfig -ProxyAuthentication basic;
For more detailed information: please refer to the HOW TO CONFIGURE REMOTING WITH A PROXY SERVER section in the following article: http://technet.microsoft.com/en-us/library/dd347642.aspx
Read More...

Friday, 29 January 2016

ps.outlook.com - Connecting to remote server failed with the following error message

I am receiving the following error when I try to connect exchange online from powershell.
[ps.outlook.com] Connecting to remote server failed with the following error message : The WinRM client cannot process the request because the server name cannot be resolved. For more information, see the about_Remote_Troubleshooting Help topic.
    + CategoryInfo          : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [], PSRemotingTransportException
    + FullyQualifiedErrorId : PSSessionOpenFailed
I am using below command to connect Office 365 using remote PowerShell:
$365Logon = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $365Logon -Authentication Basic -AllowRedirection
Import-PSSession $Session

Solution 1: Run as Administrator

To troubleshoot the error message “Connecting to remote server failed with the following error message: The client cannot connect to the destination specified in the request”, You have to run the Windows PowerShell with elevated privilege ( right click the Windows PowerShell and click “Run as Administrator”).

Solution 2: Connect Office 365 via Proxy Server

This issue also can occur if the Windows PowerShell remoting is affected by proxy settings. To resolve this problem, use proxy setting options in your remote command. The following settings are available: ProxyAccessType, ProxyAuthentication, ProxyCredential

To set these options for a particular command, use the following procedure:

1. Use the ProxyAccessType, ProxyAuthentication, and ProxyCredential parameters of the New-PSSessionOption cmdlet to create a session option object with the proxy settings for your enterprise. Save the option object is a variable.

2. Use the variable that contains the option object as the value of the SessionOption parameter of a New-PSSession command.
$365Logon = Get-Credential

$proxyOptions = New-PSSessionOption -ProxyAccessType IEConfig

$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $365Logon -Authentication Basic -AllowRedirection -SessionOption $proxyOptions

Import-PSSession $Session

For more detailed information: please refer to the HOW TO CONFIGURE REMOTING WITH A PROXY SERVER section in the following article: http://technet.microsoft.com/en-us/library/dd347642.aspx 

Source : https://community.office365.com/en-us/f/148/t/19593
Read More...

Thursday, 28 January 2016

Office 365 set password to never expire with powershell

We can use the Azure AD powershell cmdlet Set-MsolUser to set a user on Office 365 to Password Never Expire with the attribute -PasswordNeverExpires.

Note: Before proceed, Install and Configure Azure AD PowerShell

Use the below powershell command to set an user password to never expire:
Set-MsolUser -UserPrincipalName $userid -PasswordNeverExpires $true 
You can get an Azure AD user's PasswordNeverExpires state using below command:
Get-MSOLUser -UserPrincipalName $userid | Select UserPrincipalname, PasswordNeverExpires
Now, you can also enable password never expire flag for bulk office 365 users. You can read users from a csv file using Powershell cmdlet Import-CSV. Consider the CSV file Office365Users.csv which contains set of office 365 users with the column "UserPrincipalname".
Import-Csv "C:\Office365Users.csv" | ForEach-Object {
 $upn = $_."UserPrincipalName"
 Set-MsolUser -UserPrincipalName $upn -PasswordNeverExpires $true
}
The following command lists all the Azure AD users whose password never expire flag enabled.
Get-MSOLUser -All |  Where-Object { $_.PasswordNeverExpires } | Select UserPrincipalname, PasswordNeverExpires
Read More...

Set Office 365 Distribution Group Delivery Restrictions via PowerShell

Setting delivery restrictions on exchange online distribution groups is quite a common task.Before proceed, Connect Exchange Online Remote PowerShell.

We can use the powershell cmdlet Set-DistributionGroup to configure delivery restriction with the parameter -AcceptMessagesOnlyFrom. It’s easy to create a powershell command to add multiple office 365 users to the -AcceptMessagesOnlyFrom attribute on the DL object but when doing this you’ll find that only the last one in the list has been added. This is because the attribute is an array. You can view this using the following command.
Get-DistributionGroup -Identity "<group-name<" | Select -expand AcceptMessagesOnlyFrom | FT Name
To add a new office 365 user to this list you have to get the already existing list and then add the new user to this list and set this new list to the attribute -AcceptMessagesOnlyFrom.
$lst = (Get-DistributionGroup "<group-name>").AcceptMessagesOnlyFrom 

$lst.Add("<user-name>")

Set-DistributionGroup "<group-name>" -AcceptMessagesOnlyFrom($lst)
You can also remove an user by removing user from the attribute -AcceptMessagesOnlyFrom.
$lst = (Get-DistributionGroup "<group-name>").AcceptMessagesOnlyFrom 

$lst.Remove("<user-name>")

Set-DistributionGroup "<group-name>" -AcceptMessagesOnlyFrom($lst)
Like wise, you can also add multiple office 365 users by importing users from text file. First create the text file Users.txt which includes one user name in each line
$UserList = Get-Content "C:\Users.txt"

$lst = (Get-DistributionGroup "<group-name>").AcceptMessagesOnlyFrom 

ForEach ($user in $UserList)
{
  $lst.Add($user)
}

Set-DistributionGroup "<group-name>" -AcceptMessagesOnlyFrom($lst)
Read More...

Wednesday, 27 January 2016

Check if machine is 64 bit or 32 bit in C# ?

We can easily check this by using IntPtr size. If IntPtr.size is 4 then machine running on 32 BIT OS and if it is 8 then machine is 64 BIT OS.
if (IntPtr.Size == 8)
// 64Bit
else
// 32bit
If your program has been build in x86 platform (32 bit) and it is working on 64 bit machine, then you need to add some more checks.
public static bool Is64BitOperatingSystem = (IntPtr.Size == 8) || InternalCheckIsWow64();

[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsWow64Process(
    [In] IntPtr hProcess,
    [Out] out bool wow64Process
);

static bool InternalCheckIsWow64()
{
    if ((Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor >= 1) ||
        Environment.OSVersion.Version.Major >= 6)
    {
        using (Process p = Process.GetCurrentProcess())
        {
            bool retVal;
            if (!IsWow64Process(p.Handle, out retVal))
            {
                return false;
            }
            return retVal;
        }
    }
    else
    {
        return false;
    }
}
Read More...

Check string is ip address in c#

In C#, we can validate a given string is a valid ip address or not by using IPAddress.TryParse method. The below C# function check and returns whether the given string value is valid ip address or not.
private static bool IsIPAddress(string ipAddress)
{
    bool retVal = false;

    try
    {
        IPAddress address;
        retVal = IPAddress.TryParse(ipAddress, out address);
    }
    catch (Exception ex)
    {
    }
    return retVal;
}
We can also check AddressFamily of the given ip address.
IPAddress address;
if (IPAddress.TryParse(ipAddress, out address))
{
    switch (address.AddressFamily)
    {
        case System.Net.Sockets.AddressFamily.InterNetwork:
            // This is IPv4 address
            break;
        case System.Net.Sockets.AddressFamily.InterNetworkV6:
            // This is IPv6 address
            break;
        default:
            break;
    }
}
Read More...

Sunday, 24 January 2016

Get currently logged in user c#

We can easily find current username in C# by using either by Environment class or WindowsIdentity.
Environment.UserName
- Return username without domain part
System.Security.Principal.WindowsIdentity.GetCurrent().Name
- Return username with domain part : 'DomainName\Username'

You need to add reference to System.Security.Principal to use WindowsIdentity class.
using System;
using System.Security.Principal;

namespace GetUserInfo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("UserName: " + Environment.UserName);
            Console.WriteLine("IdentityName: " + WindowsIdentity.GetCurrent().Name);
        }
    }
}
Read More...

Friday, 22 January 2016

Get Active Directory User's GUID and SID in C#

We can find an Active Directory User’s GUID and SID in C# by using the UserPrincipal class which exists under the namespace System.DirectoryServices.AccountManagement and it is available only from .NET 3.5.

Step 1 : Create a new Console Application project in Visual Studio.
Step 2 : Add a a.NET reference System.DirectoryServices.AccountManagement
Step 3 : Then use the below C# code to find an AD user's DisplayName, GUID, SID and UserPrincipalName.
using System;
using System.DirectoryServices.AccountManagement;

namespace GetADUserInfo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Set up domain context
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
            // Find user
            UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "<Username>");
            if (user != null)
            {
                Console.WriteLine("Name: " + user.DisplayName);
                Console.WriteLine("GUID: " + user.Guid);
                Console.WriteLine(" SID: " + user.Sid);
                Console.WriteLine("UPN: " + user.UserPrincipalName);
            }
        }
    }
}
Read More...

Get the Current User’s Active Directory GUID and SID in C#

You can get an Active Directory User’s GUID and SID in C# by using UserPrincipal class. The UserPrincipal class exists under the namespace System.DirectoryServices.AccountManagement and it is available only from .NET 3.5.

# 1 – Create a new Console Application project in Visual Studio.

# 2 – Add a a.NET reference System.DirectoryServices.AccountManagement

# 3 – Then use the below code to get currently logged in user's Name, GUID, SID and UserPrincipalName.
using System;
using System.DirectoryServices.AccountManagement;
 
namespace ADUserInfo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Name: " + UserPrincipal.Current.Name);
            Console.WriteLine("GUID: " + UserPrincipal.Current.Guid);
            Console.WriteLine(" SID: " + UserPrincipal.Current.Sid);
            Console.WriteLine("UPN: " + UserPrincipal.Current.UserPrincipalName);
        }
    }
}
Read More...

Thursday, 21 January 2016

Set Send As Permission Office 365 using Powershell

We can set or grant send as permission for an office 365 mailbox using the powershell cmdlet Add-RecipientPermission .

Note: Before proceed, Connect Exchange Online Remote PowerShell.

Run the following command to grant send as permission to Morgan on the user Kevin’s mailbox.
Add-RecipientPermission Kevin -Trustee Morgan -AccessRights SendAs -Confirm:$False
Trustee - The mailbox that should be granted the send as permission.

Set Send As Permissions for Bulk Mailboxes from Text file

Use the below powershell script to configure Send As permission for bulk office 365 mailboxes from text file. First create the text file Mailboxes.txt which includes one mailbox in each line.
Get-Content C:\Mailboxes.txt | ForEach-Object{
 $mailbox = $_
 Add-RecipientPermission $mailbox -Trustee <user> -AccessRights SendAs -Confirm:$False
}

Grant Send As access to all Mailboxes in Office 365

Use the below powershell script to configure send as permission for all the mailbox users in your Office 365.
$MBXS = Get-Recipient -RecipientType UsermMilbox 
ForEach ($MBX in $MBXS) 
{ 
Add-RecipientPermission $MBX.name -AccessRights SendAs –Trustee <user> -Confirm:$False 
} 

List all send as permissions

If you want to list all the configured send as permissions, use the below command.
Get-RecipientPermission | Where {($_.Trustee -ne 'nt authority\self') -and ($_.Trustee -ne 'null sid')}
Read More...

Wednesday, 20 January 2016

Graph API: Insufficient privileges to complete the operation

I have created an Azure AD application and used in my own application to connect Azure AD Graph API. When I call update graph api to reset password of a cloud AD user, I am receiving the error 'Insufficient privileges to complete the operation'.

My graph api uri:

https://graph.windows.net/he4g3ccc-dbc5-4625-8336-11e0e3ea8b7j/users/myuser@mts.onmicrosoft.com?api-version=1.6

Received below error:

  "odata.error": {  
   "code": "Authorization_RequestDenied",
    "message": {      
    "lang": "en",
    "value": "Insufficient privileges to complete the operation."  
  }}

Solution 1:

If you are receiving this error when you call the API that includes only read permissions, you have to set permissions in Azure Management Portal.

- Go to Azure Management Portal and click Active Directory.
- Select your custom AD directory.
- Click Applications and select your Application.
- Click CONFIGURE and scroll down to the section 'Permissions to other applications'.
- Provide required Application Permissions and Delegated Permissions for Windows Azure Active Directory.
- Finally save the changes.

Solution 2:

If you are receiving this error when you call the API that includes delete or reset password operations, it requires the Admin role "Company Administrator". Right now you can do this only through Windows Azure ActiveDirectory Powershell module. You can find the service principal using Get-MsolServicePrincipal –AppPrincipalId and then use Add-MsolRoleMember to add it to “Company Administrator” role.

#1. Get clientid of your web application - you can get it from azure web/configuration, or in PowerShell by running below command.
Get-MsolServicePrincipal | ft DisplayName, AppPrincipalId -AutoSize
# 2. Put your web app guid and use it to get MsolServicePrincipal and use Add-MsolRoleMember to add it to “Company Administrator” role.
$clientIdApp = '1a27ce25-025a-46e8-b679-1f3e560cfad4'
$webApp = Get-MsolServicePrincipal –AppPrincipalId $clientIdApp

Add-MsolRoleMember -RoleName "Company Administrator" -RoleMemberType ServicePrincipal -RoleMemberObjectId $webApp.ObjectId
Read More...

Tuesday, 19 January 2016

How to Connect Exchange Online using remote PowerShell

Exchange Online PowerShell module provides cmdlets to manage Office 365 cloud objects such as mailbox, groups, etc...

#1 Connect to Exchange Online:

#1 Open Windows PowerShell and run the following command and type your Office 365 admin user name and password, and then click OK.
$365Logon = Get-Credential
#2 Run the following command to create new office 365 powershell session.
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $365Logon -Authentication Basic -AllowRedirection
#3 Then, run the following command to import new exchange online powershell session.
Import-PSSession $Session

#2 Use PowerShell Cmdlets with Office 365:

Once you have imported the cloud Exchange powershell module, you can now run the all available cmdlets. Let’s start with simple cmdlet:
Get-Mailbox
The above cmdlet, lists office 365 mailboxes.

#3 Remove Remote PS Session:

Once you have completed all the works with remote office 365 powershell, you have to remove the session using below command
Remove-PSSession $Session
Note : If you are newbie to powershell, don’t forget to set your execution policy to unrestricted or you might get an error when you try run the script. Use the below command to set your execution policy:
Set-ExecutionPolicy RemoteSigned 
Read More...