Thursday, 30 July 2015

How to get Remote Desktop Sessions (RDP) using Powershell

In Powershell, we can get a list of remote desktop sessions (rdp) using the commands QWinsta and Query.

List Remote Desktop Sessions using QWinsta:

QWinsta /server:[Server name or IP]
Replace the parameter [Server name or IP] with the name or IP address of the remote machine.
QWinsta /server:210.168.1.54

Get Remote Desktop Sessions using Query:

Query user /server:[Server name or IP]
Replace the parameter [Server name or IP] with the name or IP address of the remote computer.
Query user /server:210.168.1.54
You can use the below powershell command to get clear output.
(Query user /server:210.168.1.54) -replace '\s{2,}', ',' | ConvertFrom-Csv
The following command exports the output to CSV file.
(Query user /server:210.168.1.54) -replace '\s{2,}', ',' | ConvertFrom-Csv |
Export-CSV "C:\\RDPSessions.csv" -NoTypeInformation -Encoding UTF8 
Read More...

Tuesday, 28 July 2015

Create AD User and Mailbox using Powershell

Creating new mailbox user is one of the important task for every Administrator either for actual new employee or for internal testing. You can use Exchange Management console to create new mailbox user, but it is a time consuming job if you want to create multiple AD users (bulk mailbox users). To overcome this, we can use Powershell Script to Create new AD User with mailbox.

Before proceed, run the following command to enable Exchange cmdlets if you are working with Powershell console instead of Exchange Management Shell.
Add-PSSnapin *Exchange*

Summary:

Create New Mailbox User

We can use the Exchange Management Powershell cmdlet New-Mailbox to create new mailbox AD user. The following command creates the Active Directory user "Will Smith" in the TestOU, with a mailbox on the TestDBStore database.
New-Mailbox -UserPrincipalName willsmith@testdomain.com -Alias 'WillSmith' -Database 'TestDBStore' -Name WillSmith –OrganizationalUnit TestOU -Password (ConvertTo-SecureString 'MyPassword123' -AsPlainText -Force) -FirstName Will -LastName Smith -DisplayName 'Will Smith' -ResetPasswordOnNextLogon $True

Enable Mailbox for existing AD User

We can create a mailbox for an existing Active Directory user using exchange powershell cmdlet Enable-Mailbox. The following powershell command creates mailbox for the existing AD user "Chris Jordan".
Enable-Mailbox -Identity:'ChrisJordan' -Alias:'ChrisJordan' -Database: 'TestDBStore'

Create Bulk Mailbox AD Users from CSV file using Powershell

1. Consider the CSV file MailboxUsers.csv which contains set of new mailbox ad users to create with the attributes name, alias, userPrincipalName, database, firstName, lastName, displayName and ParentOU.
Create Bulk Mailbox AD Users from CSV file using Powershell
2. Copy the below Powershell script and paste in Notepad file.
3. Change the MailboxUsers.csv file path with your own csv file path.
4. SaveAs the Notepad file with the extension .ps1 like Create-Bulk-Mailbox-AD-Users.ps1
Import-Csv "C:\Scripts\MailboxUsers.csv" | ForEach-Object {
New-Mailbox -UserPrincipalName $_.'userPrincipalName' -Alias $_.'alias' -Database $_.'database' -Name $_.'name' –OrganizationalUnit $_.'ParentOU' -Password (ConvertTo-SecureString 'MyPassword123' -AsPlainText -Force) -FirstName $_.'firstName' -LastName $_.'lastName' -DisplayName $_.'displayName' -ResetPasswordOnNextLogon $True }
5. Now run the file Create-Bulk-Mailbox-AD-Users.ps1 in Powershell to create Bulk Active Directory users and Mailboxes from CSV file.

Enable Mailbox for Bulk AD Users from CSV using Powershell

1. Consider the CSV file ADUsers.CSV which contains set of existing AD users that we want to enable mailbox with the attributes name, alias and database.
Create Mailbox for Bulk AD Users from CSV using Powershell
2. Copy the below Powershell script and paste in Notepad file.
3. Change the ADUsers.CSV file path with your own csv file path.
4. SaveAs the Notepad file with the extension .ps1 like Create-Mailbox-for-Bulk-AD-Users.ps1
Import-Csv "C:\Scripts\ADUsers.csv" | ForEach-Object {
Enable-Mailbox -Identity:$_.'name' -Alias:$_.'alias' -Database:$_.'database'
}
5. Now run the file Create-Mailbox-for-Bulk-AD-Users.ps1 in Powershell to create Bulk Active Directory users and Mailboxes from CSV file.
Read More...

GPO : Default Group Policies and Settings

By default, the group policy objects Default Domain Policy and the Default Domain Controllers Policy are created when we create a new Active Directory domain.

Default Domain Policy:

The default domain policy includes the following three security polices. You can check these policies under Computer Configuration > Policies > Windows Settings > Security Settings > Account Policies.
  • Password Policy 
  • Account Lockout Policy 
  • Kerberos Policy.
These three policies can only be set at the Domain level. If you configure these settings anywhere else -in Site or OU, they are ignored. However, setting these three policies at the OU level will have the effect if users log on locally to their PCs. Login to the domain you get the domain policy, login locally you get the OU policy.

The default domain policy also includes the following three security options. You can check these settings under Computer Configuration > Policies > Windows Settings > Security Settings > Local Policies > Security Options.
  • Automatically log off users when logon time expires 
  • Rename Adminsitrator Account - When set at the domain level, it affects the Domain Administrator account only. 
  • Rename Guest Account - When set at the domain level, it affects the Domain Guest account only.
For the above listed policies, you can use only the Default Domain Policy.

Default Domain Controllers Policy:

This policy can be found by right clicking the Domain Controllers OU. This policy affects all Domain Controllers in the domain regardless of where you placed the domain controllers. That means, you can put your domain controllers in any container (OU) in Active Directory (other than Domain Controllers OU), the outside domain controllers also process this policy and get settings from this policy.

Use the Default Domain Controllers Policy to set local policies for your domain controllers, e.g. Audit Policies, Event Log settings.
Read More...

How to Apply Group Policy at OU Level

GPOs can be configured Locally, at the Site level, the Domain level or at the Organizational Unit (OU) level. Group Policies are applied in a Specific Order, LSDO. This order means that the local GPO is processed first, and GPOs that are linked to the Organizational Unit are processed last, so the OU level GPO overwrites settings in the earlier GPOs if there are conflicts.

As OU policies are applied starting at the "root level", we can organize users and computers into different containers and apply GPO to a specific OU depends on various organization needs. We can set a Group Policy to OU by following two ways:

    - Create a new GPO and Link it to OU
    - Link an existing GPO to OU

Create a new GPO and Link it to a Organizational Unit (OU)

1. Open the Group Policy Management console by running the command gpmc.msc.

2. Expand the tree Forest >> Domains , right-click on the OU where you want to apply new policy, click Create a GPO in this domain, and Link it here...

How to Apply Group Policy at OU Level

3. Type the new policy name and click OK and you can edit GPO settings by right-click on the newly created GPO and click Edit.
Read More...

Friday, 24 July 2015

Enable ActiveSync for Exchange Users using Powershell

We can enable and disable Exchange ActiveSync feature for mailbox users using the powershell cmdlet Set-CASMailbox. This article contains Powershell scirpt to enable ActiveSync feature for a single user and set of users.

Before proceed, run the following command to enable Exchange cmdlets if you are working with Powershell console instead of Exchange Management Shell.
Add-PSSnapin *Exchange*

Enable Exchange ActiveSync for a Single User:

Run the following command to enable Exchange ActiveSync for a single user:
Set-CASMailbox -Identity "Morgan" -ActiveSyncEnabled $True
Use the below command and check the ActiveSync feature is enabled for the corresponding user which you have used in the above command.
Get-CASMailbox -ResultSize Unlimited

Enable ActiveSync Feature for a Group of Users:

We can use the Active Directory powershell cmdlet Get-ADUser to get a group of users and pass the selected users to Set-CASMailbox cmdlet to enable Exchange ActiveSync feature. We can set target OU and apply filter in Get-ADUser cmdlet to get specific set of users. Before proceed, run the following command to import Active Directory powershell cmdlets.
Import-Module ActiveDirectory
The following powershell command select and enable ActiveSync feature for all the users from the container TestOU.
$users = Get-ADUser -Filter * -SearchBase "OU=TestOU,DC=TestDomain,DC=com";
$users | ForEach-Object {
Set-CASMailbox -Identity $_.Name -ActiveSyncEnabled $True
}
You can also apply Filter to select particular set of users, the following command select and enable Exchange ActiveSync feature for all the users who are under Testing department.
$users = Get-ADUser -Filter 'Department -like "*Testing*"';
$users | ForEach-Object {
Set-CASMailbox -Identity $_.Name -ActiveSyncEnabled $True
}
Instead of SQL like fiter, you can use ldap filter by using the parameter -LDAPFilter.
$users = Get-ADUser -LDAPFilter '(Department=*Testing*)';
$users | ForEach-Object {
Set-CASMailbox -Identity $_.Name -ActiveSyncEnabled $True
}

Enable ActiveSync Feature for Multiple Users:

Use the below powershell script to enable Exchange ActiveSync connectivity for a set of mailbox users. Give the set of user names as string Array.
$users = "usr1","usr2","usr3","usr4"
Foreach($user in $users) {
Set-CASMailbox -Identity $user -ActiveSyncEnabled $True
}
Read More...

List Users with ActiveSync Disabled using Powershell

We can find and list users with ActiveSync disabled using the Powershell cmdlet Get-CASMailbox. This article contains Powershell script to get a list of ActiveSync disabled mailbox users and export user details to CSV file.

Before proceed, run the following command to enable Exchange Powershell cmdlets if you are working with normal Powershell console instead of Exchange Management Shell.
Add-PSSnapin *Exchange*

List Exchange ActiveSync Disabled Users:

The Get-CASMailbox cmdlet returns the status of mailbox features (OWA, Exchange ActiveSync, POP3, and IMAP4) for all users, we can use Where-Object and filter only users with Exchange ActiveSync disabled.
Get-CASMailbox -ResultSize Unlimited | Where-Object { $_.ActiveSyncEnabled -eq $false}
You can get users from specific container (OU) by adding the parameter OrganizationalUnit.
$OU='OU=TestOU,DC=TestDomain,DC=com'
Get-CASMailbox -OrganizationalUnit $OU -ResultSize Unlimited |
Where-Object { $_.ActiveSyncEnabled -eq $false}

Export ActiveSync Disabled Users to CSV:

The following powershell script exports Exchange ActiveSync disbaled users to CSV file.
Get-CASMailbox -ResultSize Unlimited | Where-Object { $_.ActiveSyncEnabled -eq $false} |
Select Name,ActiveSyncEnabled,OWAEnabled |
Export-CSV "C:\\ActiveSyncDisabledUsers.csv" -NoTypeInformation -Encoding UTF8
Read More...

Thursday, 23 July 2015

How to enable or disable Ping service in Windows 2008/2012 R2

Ping is used to check if a remote machine is online or offline. It is a small network packet sent to the machine. If the machine is up, an answer will be sent. This can be used to scan an IP-range for reachable hosts for potential hackers. For security reason, you might needed to disable this ping service.

Stepts to Disable Ping Service:

1. Go to Start -> Administrative Tools -> Windows Firewall with Advanced Security -> Inbound Rules -> File and Printer Sharing (Echo Request – ICMPv4-IN).
2. Right-click on the rule File and Printer Sharing (Echo Request – ICMPv4-IN) and select Enable Rule.
3. Now, right-click on the same rule and click Properties.
4. In General tab, under the section Action, select the option Block the connection and click Apply button.

How to enable or disable Ping Service in Windows 2008/2012 R2

Thats all, you can try a ping command from other remote machine and you could see the response as "Request timed out".

Enable Ping Service:

To enable ping service, you can either disable the rule File and Printer Sharing (Echo Request – ICMPv4-IN) or select the Action Allow the connection.
Read More...

C# : Check If Machine is Online or Offline

In C#, We can test if a remote computer is online or offline using Ping service. For security reason, the Ping service may be disabled in your network, in that case, you can use WMI service to check if a remote computer is up or down.

Summary:


C# - Check If Machine is Up or Down using Ping Service

You can use the C# class Ping from System.Net.NetworkInformation namespace to find a remote machine is alive or not. This is the fastest way to check a remote machine online status compared with using WMI Service method.
// using System.Net.NetworkInformation;
private static bool IsMachineUp(string hostName)
{
    bool retVal = false;
    try
    {
        Ping pingSender = new Ping();
        PingOptions options = new PingOptions();
        // Use the default Ttl value which is 128,
        // but change the fragmentation behavior.
        options.DontFragment = true;
        // Create a buffer of 32 bytes of data to be transmitted.
        string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        byte[] buffer = Encoding.ASCII.GetBytes(data);
        int timeout = 120;

        PingReply reply = pingSender.Send(hostName, timeout, buffer, options);
        if (reply.Status == IPStatus.Success)
        {
            retVal = true;
        }
    }
    catch (Exception ex)
    {
        retVal = false;
        Console.WriteLine(ex.Message);
    }
    return retVal;
}

C# - Check If Machine is Online or Offline using WMI (without Ping Service)

You can use Ping service to get faster results, but for security reason, the Ping service may be disabled in your network, in that case, you can use WMI service in C# to find a remote host is up or down.
// using System.Management;
private static bool IsMachineOnline(string hostName)
{
    bool retVal = false;
    ManagementScope scope = new ManagementScope(string.Format(@"\\{0}\root\cimv2", hostName));
    ManagementClass os = new ManagementClass(scope, new ManagementPath("Win32_OperatingSystem"), null);
    try
    {
        ManagementObjectCollection instances = os.GetInstances();
        retVal = true;
    }
    catch (Exception ex)
    {
        retVal = false;
        Console.WriteLine(ex.Message);
    }
    return retVal;
}
Read More...

Wednesday, 22 July 2015

Powershell : Declare Array and Iterate with ForEach

In Powershell, you can iterate through list of objects (or collection of objects) using ForEach loop. You can either initialize new array variable or get collection of objects from other cmdlet and store it in an array variable and iterate the array object using foreach loop function. You can also iterate collection of objects using ForEach-Object cmdlet.

Let's declare array variable with list of string values:
$strArray = @("value1", "value2", "value3","value4")
Now, we can pass this array object to ForEach statement and get all the elements one-by-one and process it.
$strArray = @("value1", "value2", "value3","value4")
ForEach($str in $strArray) 
{
        Write-Host  "Processing the string element:" $str
}
You can also process the list of objects using ForEach-Object cmdlet.
$strArray = @("value1", "value2", "value3","value4")
$strArray | ForEach-Object {
        Write-Host  "Processing the string element:" $_
}
Although we can use both ForEach statement and ForEach-Object to return the same results, there are some differences between them regarding performance and usage. We can pass the output of ForEach-Object to next pipeline, but we can’t do this with foreach statement. The ForEach-Object cmdlet process each element as it passes through the pipeline, so it uses less memory, but foreach statement generates the entire collection before processing individual values.
Read More...

Tuesday, 21 July 2015

Disable ActiveSync for Exchange Users using Powershell

We can enable and disable Exchange ActiveSync feature for mailbox users using Set-CASMailbox cmdlet. In this article, I am going write Powershell scirpt to disable ActiveSync feature for a single user and disable ActiveSync feature for a set of users.

Before proceed, run the following command to enable Exchange cmdlets if you are working with Powershell console instead of Exchange Management Shell.
Add-PSSnapin *Exchange*

Disable Exchange ActiveSync for a Single User:

Run the following command to disable Exchange ActiveSync for a single user:
Set-CASMailbox -Identity "Morgan" -ActiveSyncEnabled $False
Run the below command and check the ActiveSync feature is disabled or not for the corresponding user which you have used in the above command.
Get-CASMailbox -ResultSize Unlimited

Disable ActiveSync Feature for a Group of Users:

We can use the Active Directory powershell cmdlet Get-ADUser to get a group of users and pass the selected users to Set-CASMailbox cmdlet to disable ActiveSync feature. We can set target OU and apply filter in Get-ADUser cmdlet to get specific set of users. Before proceed, run the following command to import Active Directory powershell cmdlets.
Import-Module ActiveDirectory
The following powershell command select and disable ActiveSync feature for all the users from the container TestOU.
$users = Get-ADUser -Filter * -SearchBase "OU=TestOU,DC=TestDomain,DC=com";
$users | ForEach-Object {
Set-CASMailbox -Identity $_.Name -ActiveSyncEnabled $False
}
The following command select and disable Exchange ActiveSync feature for all the users who are under Testing department.
$users = Get-ADUser -Filter 'Department -like "*Testing*"';
$users | ForEach-Object {
Set-CASMailbox -Identity $_.Name -ActiveSyncEnabled $False
}

Disable ActiveSync Feature for Multiple Users:

Use the below powershell script to disable Exchange ActiveSync connectivity for a set of mailbox users. Give the set of user names as string Array.
$users = "usr1","usr2","usr3","usr4"
Foreach($user in $users) {
Set-CASMailbox -Identity $user -ActiveSyncEnabled $False
}
Read More...

How to Logoff Remote Desktop User via Command Line

We can logoff a remote desktop user session by using the command line tool Logoff.

Logoff command syntax:

LOGOFF [sessionname | sessionid] [/SERVER:servername] [/V] [/VM]

  sessionname         The name of the session.
  sessionid           The ID of the session.
  /SERVER:servername  Specifies the Remote Desktop server containing the user session to log off.
  /V                  Displays information about the actions performed.
  /VM                 Logs off a session on server or within virtual machine.
Before proceed, we should find the ID of the session which we want to terminate, we can list all the remote desktop user sessions by using the command QWinsta.
QWinsta /server:[Server name or IP]
Replace the parameter [Server name or IP] with the name or IP address of the Remote Computer. You will get the list of remote user sessions with username and session ids in the command window.
How to Logoff Remote Desktop User via Command Line

From the above output you can easily find the session id of an user whom you want to logoff. Now, I am trying to terminate the user Administrator and its session id is 1.

Command to logoff remote user:

Logoff /SERVER:[Server name or IP] [Session ID] /V 
Example:
Logoff /SERVER:202.68.1.51 1 /V 

Command to disconnect remote user:

You can also use the following command if you want only disconnect the remote user session instead of complete logoff.
RWinsta /server:[Server name or IP] [Session ID]
Example:
RWinsta /server:202.68.1.51 1
Finally, use the command QWinsta to confirm the user is logged out/disconnected successfully.
QWinsta /server:202.68.1.51
Read More...

Monday, 20 July 2015

List and Disconnect Remote Desktop Sessions via Command Line

We can list all the Remote Desktop sessions by using the command line tool QWinsta and we can disconnect RDP Sessions using the command RWinsta.
QWinsta /server:<Server name or IP>
Replace the parameter <Server name or IP> with the name or IP address of the Remote Computer.

Example:

QWinsta /server:202.68.1.51
You will get a list of Remote Sessions with username and session ids in the command window.
List and Disconnect Remote Desktop Sessions via Command Line
From the above output you can easily find what are the RDP sessions are Active from the field STATE. In order to disconnect a user, first, we should find the session id for the corresponding user and you can the session id for the user Administrator is 1.

Use the following command to disconnect the remote session:
RWinsta /server:<Server name or IP> <Session ID>
I have used the below command to terminate the session of the Administrator:
RWinsta /server:202.68.1.51 1
Once again use the command QWinsta to confirm the user is disconnected successfully.
QWinsta /server:202.68.1.51
Now, you can see the Administrator is not listed in available RDP sessions.
C:\> QWinsta /server:202.68.1.51

 SESSIONNAME       USERNAME                 ID  STATE   TYPE        DEVICE
 services                                    0  Disc
 rdp-tcp                                 65536  Listen
Read More...

Get ActiveSync Enabled Mailbox Users using Powershell

We can get and list Exchange ActiveSync enabled users using the Powershell cmdlet Get-CASMailbox. In this article, I am going write Powershell script to get a list of ActiveSync Enabled Mailbox Users and Export ActiveSync Enabled User details to CSV file.

Before proceed, run the following command to enable Exchange Powershell cmdlets if you are working with Powershell console instead of Exchange Management Shell.
Add-PSSnapin *Exchange*

List Exchange ActiveSync Enabled Users:

The Get-CASMailbox cmdlet returns all the features for all the mailbox users, we can use Where-Object and filter only users with Exchange ActiveSync Enabled.
Get-CASMailbox -ResultSize Unlimited | Where-Object { $_.ActiveSyncEnabled -eq $true}
You can add the parameter OrganizationalUnit if you want to list users from specific container (OU).
$OU='OU=TestOU,DC=TestDomain,DC=com'
Get-CASMailbox -OrganizationalUnit $OU -ResultSize Unlimited |
Where-Object {$_.ActiveSyncEnabled -eq $true}

Export ActiveSync Enabled Users to CSV:

The following powershell script exports all the ActiveSync Enabled users to CSV file.
Get-CASMailbox -ResultSize Unlimited | Where-Object { $_.ActiveSyncEnabled -eq $true} |
Select Name,ActiveSyncEnabled,OWAEnabled |
Export-CSV "C:\\ActiveSyncEnabledUsers.csv" -NoTypeInformation -Encoding UTF8
Read More...

Thursday, 16 July 2015

C# : The server is unwilling to process the request

Problem:

I am receiving the error "The server is unwilling to process the request" when changing the AD attribute userAccountControl to enable user account in C#. I am using the below C# code to enable AD user account and reset password.
public static void EnableADUser(string username)
{
    DirectoryEntry user = new DirectoryEntry("LDAP://CN="+username+ ",OU=TestOU,DC=TestDomain,DC=com");
    int old_UAC = (int)user.Properties["userAccountControl"][0];

    // Enable User Account
    user.Properties["userAccountControl"][0] = (old_UAC & ~2);
    user.CommitChanges();

    // Reset Password
    user.Invoke("SetPassword", new object[] { "MyP@$$w0rd" });
    user.CommitChanges();
}

Cause:

The cause of the problem is, we are modifying new user attribute before Set the Password. So, we should set the password for new user before making any attribute change. I have changed my C# code to reset password first and change attribute.
public static void EnableADUser(string username)
{
    DirectoryEntry user = new DirectoryEntry("LDAP://CN="+username+ ",OU=TestOU,DC=TestDomain,DC=com");

    // Reset Password
    user.Invoke("SetPassword", new object[] { "MyP@$$w0rd" });
    user.CommitChanges();

    int old_UAC = (int)user.Properties["userAccountControl"][0];
    // Enable User Account
    user.Properties["userAccountControl"][0] = (old_UAC & ~2);
    user.CommitChanges();
}
Read More...

Powershell : List only required Parameters for a Cmdlet

We can get all the required parameters for a Powershell cmdlet using Get-Help cmdlet. The Get-Help displays the detailed description of all the available parameters if we pass the parameter -Parameter * and we can filter the results using Required property to get only required parameters for a powershell cmdlet.

The following command displays all the available parameters of the Get-Childitem cmdlet.
Get-Help Get-ChildItem -Parameter *
To view only the required parameters, we can filter the results using Where-Object with Required property.:
Get-Help Get-ChildItem -Parameter * | Where-Object {$_.Required -eq $true}
Read More...