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"
$groupObj.Remove($userObj.Path)
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"
   $groupObj.Remove($userObj.Path)
}

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"
$groupObj.Remove($userObj.Path)

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"
$groupObj.Add($userObj.Path)

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"
$groupObj.Add($userObj.Path)

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"
$groupObj.Add($userObj.Path)

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)
    dNSHostName:
    computername.domainname.com
    
    servicePrincipalName:
    HOST/computername.domainname.com
    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 https://ps.outlook.com/powershell/ -Credential $o365Cred -Authentication Basic -AllowRedirection
Import-PSSession $Session

Summary:


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

Connect to Microsoft Graph API using PowerShell

In this article I will explain how to connect to Microsoft Graph and query current user information from Azure AD. To call Microsoft Graph, we must first acquire an access token from Azure Active Directory (Azure AD), we can get access token either using registered Azure AD application or by using well known Azure AD clients (Ex: PowerShell).

Pre-requisites

We are going to get access token by using AuthenticationContext.AquireToken method from the Active Directory Authentication Library (ADAL). To use ADAL library we need to install Azure Resource Manager PowerShell. If your main OS is Windows 10, and if you have PowerShellGet installed, you can run the following command to install the Azure Resource Manager PowerShell module.
Install-Module AzureRM -SkipPublisherCheck -AllowClobber -Force

Function - GetAccessToken

Instead of creating a new Client Id and Azure AD application, here we are using a well know Client Id reserved for PowerShell: 1950a258-227b-4e31-a9cf-717495945fc2. You need to pass your tenant name (ex: domain.onmicrosoft.com) to this function and enter your user credentials to get token.
Function GetAccessToken
   {
    param (
        [Parameter(Position=0, Mandatory=$true)]
        [string] $TenantName,        
        [Parameter(Position=1, Mandatory=$false)] 
        [string] $Office365Username, 
        [Parameter(Position=2, Mandatory=$false)] 
        [string] $Office365Password
      )

    Import-Module AzureRm
    #PowerShell Client Id. This is a well known Azure AD client id of PowerShell client. You don't need to create an Azure AD app.
    $clientId = "1950a258-227b-4e31-a9cf-717495945fc2"
    $resourceAppIdURI = "https://graph.microsoft.com"
    $authority = "https://login.microsoftonline.com/$TenantName"
    $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority

    #Ask credential if not provided.
    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.UserCredential" -ArgumentList $Office365Username,$SecurePassword
    } 
    else 
    { 
    #Build credentials object  
    $Credential = Get-Credential
    $AADCredential = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential" -ArgumentList $credential.UserName,$credential.Password
    } 

    $authResult = $authContext.AcquireToken($resourceAppIdURI, $clientId,$AADCredential)
    return $authResult.AccessToken
}

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.

Get Access Token : The below command gets required access token.
$accessToken= GetAccessToken -TenantName "tenant.onmicrosoft.com"
Get Access Token by passing credentials :
$accessToken= GetAccessToken -TenantName "tenant.onmicrosoft.com" -Office365Username "admin@tenant.onmicrosoft.com" -Office365Password "admin_pwd"
Example 1: The below command gets the current user profile details.
$apiUrl = "https://graph.microsoft.com/v1.0/me"
$myPrfoile = Invoke-RestMethod -Headers @{Authorization = "Bearer $accessToken"} -Uri $apiUrl -Method Get
Example 2: The below command gets all the Azure AD user details.
$apiUrl = "https://graph.microsoft.com/v1.0/users"
$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