Friday, 19 January 2018

Remove user from local Administrator group using PowerShell

In this post I am going to share PowerShell script to remove local user account or AD domain users from local Administrators group.

Remove user account from local Administrators group :

The following powershell commands remove the given AD user account from local Admins group.
$user = "DomainName/Morgan";
$group = "Administrators";
$groupObj =[ADSI]"WinNT://./$group,group" 
$userObj = [ADSI]"WinNT://$user,user"
If you want to remove non-domain local user account, you need to just pass the username as shown below:
$user = "ComputerName/Morgan";

Remove multiple users from local Administrators group :

Use the below PowerShell script to remove set of Active Directory user accounts from local Admins group. First create the text file users.txt which includes one user name in each line.
$group = "Administrators";
$groupObj =[ADSI]"WinNT://./$group,group" 
ForEach ($user in (Get-Content "C:\users.txt"))
   $userObj = [ADSI]"WinNT://$user,user"

Remove user from local Admins group on Remote computer :

We need to provide the remote computer name to remove local Administrators group member on a remote computer.
$computer = "hp-pc";
$domainUser = "DomainName/Morgan";
$groupObj =[ADSI]"WinNT://$computer/Administrators,group" 
$userObj = [ADSI]"WinNT://$domainUser,user"

Thursday, 18 January 2018

PowerShell : Add a user to the local Administrators group

By default the local Administrators group will be reserved for local admins. However, in some cases, you might want to grant an end user administrator privileges on his machine so that he can able to install a driver or an application, in this case we can easily use PowerShell commands to add local user or AD domain users to local Administrators group in local machine and remote computer.

Add a user account to the local Administrators group :

The following powershell commands add the given user account to local Admin group.
$user = "ComputerName/Morgan";
$group = "Administrators";
$groupObj =[ADSI]"WinNT://./$group,group" 
$userObj = [ADSI]"WinNT://$user,user"

Add a AD domain user account to the local Admin group :

We can use the above same commands to add domain user account by just passing the domain user.
$domainUser = "DomainName/Morgan";
$group = "Administrators";
$groupObj =[ADSI]"WinNT://./$group,group" 
$userObj = [ADSI]"WinNT://$domainUser,user"

Add a domain user account to the local Administrators group on a Remote computer:

We need to just pass the remote machine name to add an Active Directory user to the local Administrators group on a remote Windows computer with PowerShell.
$computer = "hp-pc";
$domainUser = "DomainName/Morgan";
$group = "Administrators";
$groupObj =[ADSI]"WinNT://$computer/$group,group" 
$userObj = [ADSI]"WinNT://$domainUser,user"

Fix: The Security database on the server does not have a computer account for this workstation trust relationship

Problem :

Users might have received following error when they attempting to log on to a Active Directory domain joined machine.
The Security database on the server does not have a computer account for this workstation trust relationship

Fix/Solution :

Usually this error occurs if the problematic computer object in AD is disabled or deleted. You can either dis-join and re-join or reset the problematic computer object in AD if you have required Admin access.

Also check whether your local machine time is synced with DC server.

If you can't resolve the issue using above stated method, you can follow the below steps:
  1. Open ADUC console (Active Directory Users and Computers)
  2. Click the menu View and make sure that Advanced Features is checked.
  3. Navigate to the organizational unit (OU) where the the problematic computer account resides.
  4. Open the Properties for the computer object
  5.  Choose the Attribute Editor tab in the Properties dialog box
  6. Check the attributes dNSHostName & servicePrincipalName and make sure that the entry matches the host name that you have configured in your problem computer object (Start -> Computer -> Properties -> Full Computer Name)
    If you find that both entries are not matched, you can change the correct value.
  7. Restart the computer to reflect changes quickly and try to login again.

Tuesday, 9 January 2018

Search Office 365 Mailbox : Delete, Copy and Move Messages using PowerShell

In this post I am going to share PowerShell script to search mailbox and delete, copy and move searched messages from one mailbox to another mailbox. We can use the exchange powershell cmdlet Search-Mailbox to search a mailbox and copy the results to a specified target mailbox and this cmdlet is available for both Exchange On-Premises and Exchange Online environment.

Before proceed, first we need to connect Exchange Online powershel module by running below commands:
$o365Cred = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri -Credential $o365Cred -Authentication Basic -AllowRedirection
Import-PSSession $Session


Delete searched messages from mailbox

To delete messages we need to use DeleteContent switch, to use the DeleteContent switch you have to be assigned the Mailbox Import Export management role. By default, this role isn't assigned to any role group. Typically, you assign a role to a built-in or custom role group. Or you can assign a role to a user, or a universal security group. The below example add the role to the Organization Management role group:
New-ManagementRoleAssignment -Name "Import_Export_Organization_Management" -SecurityGroup "Organization Management" -Role "Mailbox Import Export"
Note: You have to create a new Exchange Online PowerShell session to get new role permissions.

This example searches Alex Wilber's mailbox for messages that contain the phrase "test message" in the subject and deletes the messages from the source mailbox.
Search-Mailbox -Identity "Alex Wilber" -SearchQuery {Subject:"test message" } -DeleteContent

Copy messages between mailboxes

This example searches Alex Wilber's mailbox for messages that contain the subject "sales report" in the subject and copy the result messages to Allan Deyoung's mailbox in the target folder "Sales".
Search-Mailbox -Identity "Alex Wilber" -SearchQuery {Subject:"sales report" } -TargetMailbox "Allan Deyoung" -TargetFolder "Sales"

Move messages from source mailbox to target mailbox

Move operation is nothing but the copy action along with removing messages from source mailbox. This example search and move messages from Alex Wilber's mailbox to Allan Deyoung's mailbox.
Search-Mailbox -Identity "Alex Wilber" -SearchQuery {Subject:"sales report" } -TargetMailbox "Allan Deyoung" -TargetFolder "Sales" -DeleteContent

Friday, 5 January 2018

How to Connect Microsoft Graph API using PowerShell

In this post I am going to explain how to consume Microsoft Graph endpoints in Powershell and provide sample query to fetch current user information from Azure AD. To call Microsoft Graph API, we must first acquire an access token from Azure Active Directory (Azure AD), we can get access token either after registering new Azure AD application or by using the apps that was pre-registered by Microsoft (for ex: Well Known PowerShell App Id).

Steps to register a Native Azure Application (ClientId):

  1. Login to Azure Portal
  2. Navigate to "Azure Active Directory" > "App Registrations"
  3. Click "New Application Registration"
  4. Give a friendly name for your application, select application type as "Native", and enter a redirect URL in the format urn:foo (ex: "urn:ietf:wg:oauth:2.0:oob") and create the app.
  5. Click on the App > Settings > Required Permissions
  6. Click Add (+) > Select an API > choose the "Microsoft Graph" API and click Select.
  7. Grant the required permissions for the App (ex: "Read and write all users' full profiles", "Read and write all groups").
  8. Go to Settings > Properties > Copy the Application ID and use that id for ClientId parameter in the below script.
  9. Go to Settings > Redirect URIs > Copy the Redirect Uri and use that for the RedirectUri parameter in the below script.
We are going to acquire access token by using the Active Directory Authentication Library (ADAL). To use ADAL library we need to install Azure AD PowerShell Module. If your main OS is Windows 10 or if you have PowerShellGet installed, you can run the following command to install the Azure AD PowerShell module.
Install-Module AzureAD -SkipPublisherCheck -AllowClobber -Force

Function - GetAccessToken

The below powershell function will use the Well Known Powershell Client Id (1950a258-227b-4e31-a9cf-717495945fc2) if you have not passed the ClientId parameter.
Function GetAccessToken {
    param (
        [Parameter(Position=0, Mandatory=$false)]
        [string] $ClientId,
        [Parameter(Position=1, Mandatory=$false)]
        [string] $RedirectUri,
        [Parameter(Position=2, Mandatory=$false)] 
        [string] $Office365Username, 
        [Parameter(Position=3, Mandatory=$false)]
        [string] $Office365Password    
    # Set ADAL (Microsoft.IdentityModel.Clients.ActiveDirectory.dll) assembly path from Azure AD module location
    try {
    $AADModule = Import-Module -Name AzureAD -ErrorAction Stop -PassThru
    catch {
    throw 'The AzureAD PowerShell module not installed'
    $adalPath = Join-Path $AADModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
    $adalformPath = Join-Path $AADModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.Platform.dll"
    [System.Reflection.Assembly]::LoadFrom($adalPath) | Out-Null
    [System.Reflection.Assembly]::LoadFrom($adalformPath) | Out-Null   

    # If client not proivded, we are setting the id of an Azure AD app which is pre-registered by Microsoft
    if([string]::IsNullOrEmpty($ClientId) -eq $true)
    # This is a well known and pre-registered Azure AD client id of PowerShell client. 
    $ClientId = "1950a258-227b-4e31-a9cf-717495945fc2" 
    $RedirectUri = "urn:ietf:wg:oauth:2.0:oob"
    elseIf ([string]::IsNullOrEmpty($RedirectUri) -eq $true)
      throw "The RedirectUri not provided"
    $resourceURI = ""
    $authority = ""
    $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
    #Acquire token without user interaction
    if (([string]::IsNullOrEmpty($Office365Username) -eq $false) -and ([string]::IsNullOrEmpty($Office365Password) -eq $false))
    $SecurePassword = ConvertTo-SecureString -AsPlainText $Office365Password -Force
    #Build Azure AD credentials object
    $AADCredential = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserPasswordCredential" -ArgumentList $Office365Username,$SecurePassword
    # Get token without login prompts.
    $authResult = [Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContextIntegratedAuthExtensions]::AcquireTokenAsync($authContext, $resourceURI,$ClientId, $AADCredential)
    $accessToken = $authResult.Result.AccessToken
    # Get token by prompting login window.
    $platformParameters = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.PlatformParameters" -ArgumentList "Always"
    $authResult = $authContext.AcquireTokenAsync($resourceURI, $ClientID, $RedirectUri, $platformParameters)
    $accessToken = $authResult.Result.AccessToken

    return $accessToken

Get Access Token :

The below command gets required access token with login prompts.
$accessToken = GetAccessToken
Get token by passing the parameters ClientId and RedirectUri: Here we have used the id of Azure Active Directory PowerShell app which is used in Azure AD powershell module.
$accessToken = GetAccessToken -ClientId '1b730954-1685-4b74-9bfd-dac224a7b894' -RedirectUri 'urn:ietf:wg:oauth:2.0:oob'
Get access token by passing credentials without login prompts:
$accessToken = GetAccessToken -Office365Username "" -Office365Password "admin_pwd"

Connect and Fetch data from Azure AD using Rest API :

Once you get the required access token you can easily query graph api using Invoke-RestMethod cmdlet by passing access token.
Example 1: The below command gets the current user profile details.

$apiUrl = ""
$myPrfoile = Invoke-RestMethod -Headers @{Authorization = "Bearer $accessToken"} -Uri $apiUrl -Method Get
Example 2: The below command gets all the Azure AD user details.
$apiUrl = ""
$users = Invoke-RestMethod -Headers @{Authorization = "Bearer $accessToken"} -Uri $apiUrl -Method Get

Thursday, 4 January 2018

Convert Office 365 Group as Public or Private

When you create an Office 365 group, you can choose the group type as public or private. Previously in Office 365, you can't change the privacy setting once you created the group. Now, you can change the privacy settings using PowerShell or OWA.

Method 1: Convert Office 365 Groups privacy setting using PowerShell

We can use the Exchange Online powershell cmdlet Set-UnifiedGroup to modify an Office 365 Group. The below example changes the Office 365 Group named "Sales Department" from a public group to a private group.
Set-UnifiedGroup -Identity "Sales Department" -AccessType Private
The below example converts a private group to public group.
Set-UnifiedGroup -Identity "Sales Department" -AccessType Public

Method 2: Change an Office 365 Group's privacy type from OWA

- Open Outlook on the web (OWA).
- Navigate to the Office 365 group that you want to change the privacy setting.
- From the group page, click Edit group option as shown in below image.

Convert Office 365 Group as Public or Private Outlook on the web

- Under Privacy, select Public or Private as per your need and click Save to convert the group.

Convert Office 365 Group as Public or Private Outlook on the web