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

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

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

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)

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;
    }
}

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;
    }
}

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);
        }
    }
}

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);
            }
        }
    }
}

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);
        }
    }
}

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')}

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

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 

Monday, 18 January 2016

Nuget-Install-Package : The specified path, file name, or both are too long

Problem:

Today, I have downloaded a graph api sample project from Microsoft site, then opened the project solution from Downloads folder, now I am receiving the build error 'The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters'.

Then I have tried to download the file 'Microsoft.IdentityModel.Clients.ActiveDirectory.dll' by using Package Manager Console. But I got the same error.
PM> Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -Version 1.0.3
Install-Package : The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.
At line:1 char:16
+ Install-Package <<<<  Microsoft.IdentityModel.Clients.ActiveDirectory -Version 1.0.3
    + CategoryInfo          : NotSpecified: (:) [Install-Package], PathTooLongException
    + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand

Solution:

After analyzed some time, find my project path is long enough that when the package is installed, adding the package folder fails because it reached the qualified name length limit.

My actual project path:

C:\Users\Administrator\Downloads\grapghapi-active-directory-dotnet-webapi-onbehalfof\active-directory-dotnet-webapi-onbehalfof-master
The above path is too long and it reached the qualified name length limit. So, I have renamed the project folder name and moved project folder from Downloads folder to C Drive.

My new project path:

C:\graph-api-sample
Now, the too long path problem solved for me.

Tuesday, 12 January 2016

How to Install and Connect Azure AD PowerShell

Azure Active Directory PowerShell is a module that provides cmdlets to manage Office 365 Users and all other Azure AD objects with Windows PowerShell. You can use the cmdlets to create, delete, and manage objects and services delivered through the Azure platform.

Step 1: Install Azure AD PowerShell Module

First, you have to install Microsoft Online Services Sign-In Assistant, the Sign-In Assistant provides end user sign-in capabilities to Microsoft Online Services.

#1 Install Microsoft Online Services Sign-In Assistant for IT Professionals RTW

#2 Then install the Azure Active Directory Module for Windows PowerShell.

    - For 64-bit machine
    - For 32-bit machine

Step 2: Connect to Azure AD

Once you have installed all the required components, you must first import Azure AD powershell module by running the following command.
Import-Module MSOnline
Then connect to your online service. Run the below script to connect Azure AD online service.
$msolCred = Get-Credential
Connect-MsolService –Credential $msolCred
Now, you can manange your connected online Azure AD service through Azure AD PowerShell cmdlets, such as Get-MsolUser, Set-MsolUserPassword, etc..

Example:

The following command retrieves the office 365 user with the UPN admin@mtspace.com
Get-MsolUser -UserPrincipalName admin@mtspace.com