Menu

Virtual Geek

Tales from real IT system administrators world and non-production environment

Powershell Active Directory: Show treeview of User or Group memberof hierarchy

September 20, 2017 09:32AM

After going through many testing and successfully streamlining most of the Users and Groups member of in active directory environment using Powershell Active Directory: List complete hierarchy of upstream nested groups recursively of User. I was still facing some of the issues, Earlier script was not smart enough to detect the loop and will keep running if same group is in members and memberof, this will keep running indefinitely.

Active Directory Domain controller Microsoft Windows Powershell, User or Group Properties members  and Members of.png

Another thing was my earlier script was not showing the result correctly as expected if there are multiple groups in memerof tab in upstream groups, Although it was working fine if single group is there. Also I wanted a true tree size view of the captured data. Here I have re-written this script from scratch again. To use this script check my earlier articles how to run script.
Different ways to bypass Powershell execution policy :.ps1 cannot be loaded because running scripts is disabled
POWERSHELL: INSTALLING AND CONFIGURING ACTIVE DIRECTORY
As here I am going to use this script frequently, I have added it to Powershell profiles, each time powershell is launched this script is loaded into memory automatically, If PowerShell profile file does not exists it will be created with command if (!(Resolve-Path $PROFILE -eq SilentlyContinue)) {New-Item $PROFILE},  I have copied below script in file name Get-AdGroupTreeViewmemberOf.ps1, and coping file content using cat C:\temp\Get-AdGroupTreeViewMemberOf.ps1 | Add-Content $PROFILE. I can verify the same by opening file location C:\Users\UserName\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1.

Microsoft Powershell profiles tree view, resolvepath $profile, error action, New-Item, Add-Content

Installing, importing and using any module in powershell
After launching powershell simply run function to show tree map for group use Get-AdGroupTreeViewMemberOf -GroupName 'Domain Admins' and for user Get-ADGroupTreeViewMemberOf -UserName 'Administrator'. Results are as below, Loop is shown in Red color and it is skipped.

Active Directory Powershell Get-AdGroupTreeViewmemberof username and groupname, show-treeview Groups, treesize

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#
function Get-ADGroupTreeViewMemberOf {
#requires -version 4
<#
.SYNOPSIS
    Show UpStream tree view hierarchy of memberof groups recursively of a Active Directory user and Group.
.DESCRIPTION
    The Show-ADGroupTreeViewMemberOf list all nested group list of a AD user. It requires only valid parameter AD username, 
.PARAMETER UserName
    Prompts you valid active directory User name. You can use first character as an alias, If information is not provided it provides 'Administrator' user information. 
.PARAMETER GroupName
    Prompts you valid active directory Group name. You can use first character as an alias, If information is not provided it provides 'Domain Admins' group[ information.
.INPUTS
    Microsoft.ActiveDirectory.Management.ADUser
.OUTPUTS
    Microsoft.ActiveDirectory.Management.ADGroup
.NOTES
    Version:        1.0
    Author:         Kunal Udapi
    Creation Date:  10 September 2017
    Purpose/Change: Get the exact nested group info of user
    Useful URLs: http://vcloud-lab.com
.EXAMPLE
    PS C:\>.\Get-ADGroupTreeViewMemberOf -UserName Administrator

    This list all the upstream memberof group of an user.
.EXAMPLE
    PS C:\>.\Get-ADGroupTreeViewMemberOf -GroupName DomainAdmins

    This list all the upstream memberof group of a Group.
#>

[CmdletBinding(SupportsShouldProcess=$True,
    ConfirmImpact='Medium',
    HelpURI='http://vcloud-lab.com',
    DefaultParameterSetName='User')]
Param
(
    [parameter(ParameterSetName = 'User',Position=0, ValueFromPipelineByPropertyName=$true, ValueFromPipeline=$true, HelpMessage='Type valid AD username')]
    [alias('User')]
    [String]$UserName = 'Administrator',
    [parameter(ParameterSetName = 'Group',Position=0, ValueFromPipelineByPropertyName=$true, ValueFromPipeline=$true, HelpMessage='Type valid AD Group')]
    [alias('Group')]
    [String]$GroupName = 'Domain Admins',
    [parameter(ParameterSetName = 'Group', DontShow=$True)]
    [parameter(ParameterSetName = 'User', DontShow=$True)]
    [alias('U')]
    $UpperValue = [System.Int32]::MaxValue,
    [parameter(ParameterSetName = 'Group', DontShow=$True)]
    [parameter(ParameterSetName = 'User', DontShow=$True)]
    [alias('L')]
    $LowerValue = 2
)
    begin {
        if (!(Get-Module Activedirectory)) {
            try {
                Import-Module ActiveDirectory -ErrorAction Stop 
            }
            catch {
                Write-Host -Object "ActiveDirectory Module didn't find, Please install it and try again" -BackgroundColor DarkRed
                Break
            }
        }
        switch ($PsCmdlet.ParameterSetName) {
            'Group' {
                try {
                    $Group =  Get-ADGroup $GroupName -Properties Memberof -ErrorAction Stop 
                    $MemberOf = $Group | Select-Object -ExpandProperty Memberof 
                    $rootname = $Group.Name
                }
                catch {
                    Write-Host -Object "`'$GroupName`' groupname doesn't exist in Active Directory, Please try again." -BackgroundColor DarkRed
                    $result = 'Break'
                    Break
                }
                break            
            }
            'User' {
                try {
                    $User = Get-ADUser $UserName -Properties Memberof -ErrorAction Stop
                    $MemberOf = $User | Select-Object -ExpandProperty Memberof -ErrorAction Stop
                    $rootname = $User.Name
                    
                }
                catch {
                    Write-Host -Object "`'$($User.Name)`' username doesn't exist in Active Directory, Please try again." -BackgroundColor DarkRed
                    $result = 'Break'
                    Break
                }
                Break
            }
        }
    }
    Process {
        $Minus = $LowerValue - 2
        $Spaces = " " * $Minus
        $Lines = "__"
        "{0}{1}{2}{3}" -f $Spaces, '|', $Lines, $rootname        
        $LowerValue++
        $LowerValue++
        if ($LowerValue -le $UpperValue) {
            foreach ($member in $MemberOf) {
                $UpperGroup = Get-ADGroup $member -Properties Memberof
                $LowerGroup = $UpperGroup | Get-ADGroupMember
                $LoopCheck = $UpperGroup.MemberOf | ForEach-Object {$lowerGroup.distinguishedName -contains $_}
            
                if ($LoopCheck -Contains $True) {
                    $rootname = $UpperGroup.Name
                    Write-Host "Loop found on $($UpperGroup.Name), Skipping..." -BackgroundColor DarkRed
                    Continue
                }
                #"xxx $($LowerGroup.name)"
                #$Member
                #"--- $($UpperGroup.Name) `n"
                Get-ADGroupTreeViewMemberOf -GroupName $member -LowerValue $LowerValue -UpperValue $UpperValue
            } #foreach ($member in $MemberOf) {
        }
    } #Process
}
#Get-ADGroupTreeViewMemberOf -groupname a1
#Get-ADGroupTreeViewMemberOf -UserName user2
#Get-ADGroupTreeViewMemberOf -UserName user1

 

Powershell Active Directory: List complete hierarchy of upstream nested groups recursively of User

September 15, 2017 05:27PM

Recently I had seen big mess in one of my client's Active directory environment, AD Groups where keep nested into groups and further, Due to this clients where having hard time to get either exact effective permissions of particular users, and causing users have unnecessary authorization or getting unnecessary emails due to member of upstream groups, which he should not. Just to show demo here I have a user1, it is has memberof group1, that group1 is member of group2, again group 2 is member of group3, and so on. If I want to do troubleshooting it is very hard if someone is new to the environment to co-relate group members.

Active directory domain controller Microsoft Powershell, Get-aduser, get-adGroup, username and groups, nested membership memberof

Manual searching nested group memberof is be a big task if they are further nested into multiple level. I have written this powershell script to search the complete path how those Hierarchy, below articles shows how to us and run the script.

Different ways to bypass Powershell execution policy :.ps1 cannot be loaded because running scripts is disabled
POWERSHELL: INSTALLING AND CONFIGURING ACTIVE DIRECTORY
Installing, importing and using any module in powershell

Active Directory domain Controller powershell, user group tree view hierarchy upstream list group members

Active Directory domain Controller powershell, user group tree view hierarchy upstream list groupmembers recursive

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#requires -version 4
<#
.SYNOPSIS
    List all upstream nested memberof groups recursively of a Active Directory user.
.DESCRIPTION
    The Get-ADGroupsUpStream list all nested group list of a AD user. It requires only valid parameter AD username, 
.PARAMETER UserName
    Prompts you valid active directory User name. You can use first character as an alias, If information is not provided it provides 'Administrator' user information. 'Name' can be used as an alias
.INPUTS
    Microsoft.ActiveDirectory.Management.ADUser
.OUTPUTS
    Microsoft.ActiveDirectory.Management.ADGroup
.NOTES
    Version:        1.0
    Author:         Kunal Udapi
    Creation Date:  10 September 2017
    Purpose/Change: Get the exact nested group info of user
    Useful URLs: http://vcloud-lab.com
.EXAMPLE
    PS C:\>.\Get-ADGroupsUpStream -UserName Administrator

    This list all the upstream group an user a member of.
#>
[CmdletBinding(SupportsShouldProcess=$True,
    ConfirmImpact='Medium',
    HelpURI='http://vcloud-lab.com',
    DefaultParameterSetName='Manual')]
Param
(
    [parameter(Position=0, <#Mandatory=$True,#> ValueFromPipelineByPropertyName=$true, ValueFromPipeline=$true, HelpMessage='Type valid AD username')]
    [alias('Name')]
    [Microsoft.ActiveDirectory.Management.ADUser]$UserName = 'Administrator'
)
begin {
    if (!(Get-Module Activedirectory)) {
        try {
            Import-Module ActiveDirectory -ErrorAction Stop 
        }
        catch {
            Write-Host -Object "ActiveDirectory Module didn't find, Please install it and try again" -BackgroundColor DarkRed
            Break
        }
    }
}
process {
    #$UserName = 'User1'
    try {
        $MemberInfo = Get-ADUser $UserName Properties MemberOf -ErrorAction Stop
    }
    catch {
        Write-Host -Object "`'$username`' doesn't exist in Active Directory, try again with valid user" -BackgroundColor DarkRed
        break
    }
    $MemberOf = $MemberInfo | Select-Object -ExpandProperty MemberOf 
    foreach ($Group in $MemberOf) {
        $CompleteInfo = @()
        $GroupInfo = Get-ADGroup $Group Properties MemberOf
        $CompleteInfo += $MemberInfo.Name
        $CompleteInfo += $GroupInfo.Name
        $UpperGroup = $GroupInfo | Select-Object -ExpandProperty MemberOf
        #$GroupInfo.Name #test
        do 
        {
            foreach ($x in $UpperGroup) {
                $UpperGroupInfo = Get-AdGroup $x -Properties Memberof
                $CompleteInfo += $UpperGroupInfo.Name
                $UpperGroup =  $UpperGroupInfo | Select-Object -ExpandProperty Memberof
                #$UpperGroupInfo.Name #test
                #$UpperGroup
            }
        }
        while ($UpperGroup -ne $null)
        $CompleteInfo -Join " << "
        #[array]::Reverse($CompleteInfo)
        #$CompleteInfo -join '\'
    }
}
end {}

 

Enable or disable SSH on VMWare vCenter Server Appliance (VCSA)

September 11, 2017 05:37PM

Keeping disabled SSH service in VMWare Environment is a best practices, specially on Esxi server and VCSA appliance. Use only when required to reduce any attack surface, this might be your information security who ask you to implement SSH related settings. For Esxi to change settings follow my earlier article VMWARE SECURITY BEST PRACTICES: POWERCLI ENABLE OR DISABLE ESXI SSH. When you deploy and setup VCSA for the first time you can enable SSH while setting up, Deploy install VCSA (vCenter server appliance 6.5). There may be a scenario you might keep SSH disabled while installation. and wants to enable it later for troubleshooting to gather information purpose, same is achievable in below few ways. 

First way is using VCSA management portal. Use https://vcsaIP_or_FQDN:5480 portal in the browser. Provide root username and password. In the Navigator pane on the right hand side, click Access, there is Edit button to Enable SSH login.

VMWare vcenter appliance vcsa management portal 5480 edit access settings, ssh login enabled bash shell


Next way is on vmware vsphere web client, use https://vcsa/vsphere-client to login, Expand and Click Home button. go to Home >> Administration >> System Configuration

vmware workstation vcsa, vsphere vmware vcenter server appliance vcsa vsphere-client home, administration, system configuration

Here click on the Nodes in the Navigator pane, In the right hand side click Objects tab. Under Actions button click Edit Settings, Under Access use checkbox to Enable SSH login. Modifying other SSH, Time Out settings also can be defined here.

vmware vcenter server appliance, vcsa, vsphere-client, System Configuration, Nodes and services, Objects action, edit settings, enable ssh login, access


Another way is from VCSA dcui (Direct console user interface), if you don't see screenshot like below and just see it is asking for username and password, Press Alt + F2 to change to dcui console. Next use F2 button to login as root.

vmware vcenter server appliance  with embedded platform service controller vcsa DCUI direct control user interface alt f2 enable ssh

Use keyboard to go to, Under System Customization scroll down to Troubleshooting Mode options to view various troubleshooting options like Enable BASH Shell and Enable SSH. Enable SSH here.

vmware vcenter server appliance vcsa, system customization, Troubleshooting Mode, Options enable SSH


In the next ssh into VCSA using putty or any other tool, by default it will open command shell, but you are not into the bash shell yet. By default shell is disabled, I can verify it running command shell. next check the status of shell by running shell.get, as expected it is disabled. You can enable it using shell.set --enabled true. Check the status again shell.get, as expected it is enabled. Once again run command shell. you are in.

The "pi shell" is intended for advanced troubleshooting operations and while supported in this release, is a deprecated interface, and may be removed in a future version of the product.  For alternative commands, exit the "pi shell" and run the "help" command. The "pi shell" command launches a root bash shell.  Commands within the shell are not audited, and improper use of this command can severely harm the system. Help us improve the product!  If your scenario requires "pi shell," please submit a Service Request, or post your scenario to the https://communities.vmware.com/community/vmtn/vcenter/vc forum and add "appliance" tag.

vcenter server with an embeded psc SSH logged in shell ssh enabled putty shell.set --enabled true, shell.get

In this temporary BASH shell, run this command to permanently configure the default Shell to BASH for Root chsh -s /bin/bash root, Log out from the BASH Shell. Log in again for the changes to take effect. If you would like to launch it to appliance shell once you login use command chsh -s /bin/appliancesh rootReference

Useful blogs
Deploy install VCSA (vCenter server appliance 6.5) on VMWare Workstation
VMWARE VSPHERE UPDATE MANAGER (VUM) - IMPORTING ESXI ISO AND CREATE UPGRADE BASELINE1
CREATE VIRTUAL DATACENTER AND ADD ESXI HOST ON VCENTER SERVER
ADDING AND ASSIGNING VSPHERE LICENSES IN VCENTER SERVER AND ESXI
ADDING AND CONFIGURING VMWARE VSPHERE VCENTER SSO ACTIVE DIRECTORY AS LDAP SERVER
VMWARE VSPHERE POWERCLI INSTALLATION AND CONFIGURATION STEP BY STEP
 

Deploy install VCSA (vCenter server appliance 6.5) on VMWare Workstation

September 9, 2017 04:23PM

VMware plans to deprecate vCenter Server for Windows with the next numbered release (not update release) of vSphere.  The next version of vSphere will be the terminal release for which vCenter Server for Windows will be available. For more info check on Farewell, vCenter Server for Windows. I had installed Windows vCenter Server 6.5 in my Lab previously PART 2 : VCENTER SERVER 6.0 INSTALLATION ON WINDOWS 2012 R2, and now wanted to go with VCSA 6.5, I didn't find any proper way to install it on VMware Workstation, I went through few of the steps I found online modifying VMX file and deploying it but it didn't help and work as expected. Instead I went through my own steps of Installing Esxi first, Deploy vcenter vcsa installer OVA on it, Configure vcsa, then export it in ovf format, In the last step Import it on vmware workstation, It worked perfectly for me.

I downloaded latest version of vCenter server appliance 6.5 from vmware.com site. There is a folder %cdrom%\vcsa-ui-installer\win32 on CD, Where you can locate vCenter Server appliance 6.5 installer for windows. Click Install, It will start new vCenter Server Appliance or PSC Platform Services Controller Appliance wizard.

vmware vsphere vcenter server appliance correct way to install on vmware workstation PSC platform controller appliance Installer

In the Introduction page, Installing the appliance is a two stage process. The first stage involves deploying a new appliance to the target vCenter or Esxi host. The second stage completes the setup of the deployed appliance. Click next, to proceed stage 1.  Accept EULA in End user license agreement. Next is the main configuration Select deployment type, here you decide how to design vCenter and PSC installation, whether the need be separated vcenter from PSC. Here I am selecting vCenter Server with an Embedded Platform Services Controller option, Both roles on the same server, Selecting this step is very critical, as this cannot be change later and will have adverse effects later, Selecting embedded option is best suite for my LAB environment. For more on designing part I suggest go thru these official couple of pdf, articles and Documents. Limitations of the topology I selected are it does not support Enhanced Linked Mode and Platform Service Controller replication., I am good with it right now.

vmware vsphere vcenter deploy appliance installer deployment type, Embedded Platfrom services Controller Psc and vcenter external best practices

As it require Esxi server ready first, steps to install and deploy esxi can be found on PART 1 : INSTALLING ESXI ON VMWARE WORKSTATION HOME LAB. In the select deployment type configure ESXi or vCenter target settings, type Esxi host name, username and password, Where this vCenter appliance virtual machine will be deployed. Certificate warning will be poped up, Verify SSL certificate sha1 thumbprint and click OK to proceed.

State 1 Deploy vCenter Servier with an Embedded platform services controller deployment target esxi or vcenter https username password, certificate warningState 1 Deploy vCenter Servier with an Embedded platform services controller deployment target esxi or vcenter https username password, certificate warning

Type VCSA virtual machine name and root password.

vmware vcenter appliance installation set up appliance VM name root password deployed

Here decide the VM size. As per my LAB, Tiny deployment size is perfect for me. 

Deployment Size vCPUs Memory (GB) Storage (GB) Hosts (up to) VMs (up to)
Tiny 2 10 250 10 100
Small 4 16 290 100 1000
Medium 8 24 425 400 4000
Large 16 32 640 1000 10000
X-Large 24 48 980 2000 35000

vcenter vcsa installer deployment size, storage size tyny, small, medium large, x-large, vcpus, memory gb, hosts, vms

Define and select which datastore location you want to keep vCenter VM, I have only one datastore, I selected thin mode to save some disk space. Around 3 to 5 GB of  Disk space is required.

vcenter appliance deployment installer select datastore vmfs vmware enable thin disk mode on target host

This is the end of stage one of deployment, Configure network settings, Network (Esxi Port Group), Ip address related info, After completing this step, the next screen ready to complete page will show the settings you have selected up till now, varify them, press finish to start installation.

vmware vsphere vmware deployment embedded psc, Configure network settings IP

It will start deploying VM on esxi server, it will take some time, Once this stage is completed successfully, to proceed with stage 2, click continue to start setup, In case by mistake if you exit from here you can start configuration by logging into vCenter server appliance management interface by https://vcsa:5480.

Installation stage 1 completed successfully deploy vcenter and psc, vcenter management interface port 5480

As using installer to deploy vCenter is a two way process, This first step is completed in the above screenshots, and next are second step of configuring vCenter. Press next on Introduction page, In the appliance configuration tab configure synchronize time with NTP servers (Best practice), I enabled SSH access for future use. Press next

Install stage 2 set up vcenter server appliance with an Embedded PSC NTP server configuration introduction page

On the SSO configuration page, type SSO details, Domain name, Site Name, administrator user password, On the Ready to complete page review all the information.

set up vcenter server appliance with an embedded psc SSO configuration, stage two, sso details domain, site name, username  password

Once you click finish button, warning popups that you will not be able to pause or stop the install from completing once its started. It took approx 20 -25 minutes me to complete setup successfully. after completed you can access server using https://vcsa:443/vsphere-client.

vcenter setup configuration vcsa appliance completed successfuly, 443, vsphere web client

Login in to Esxi server shut down vCenter vm, right click it, and export to start download.

vmware esxi virtual machines , shutdown vcenter right click export to ovf ova

It will start importing, download VM into ovf format, There are multiple files involved. Size is around 3-4 GB.

vcenter vm virtual machine export download file to ovf ova file.png

I have downloaded exported all the required portable files, double click vcsa65.ovf where vmware workstation is installed. Select the VM Name and folder path for Importing Virtual machine. Once Server is completely powered on, check the appliance management portal and vSphere client in browser to verify installation is successful.

VMware vCenter server appliance vcsa export ovf, Import deploy install on vmware workstation, management 5480

Useful Next Steps
VMWARE VSPHERE UPDATE MANAGER (VUM) - IMPORTING ESXI ISO AND CREATE UPGRADE BASELINE
CREATE VIRTUAL DATACENTER AND ADD ESXI HOST ON VCENTER SERVER
ADDING AND ASSIGNING VSPHERE LICENSES IN VCENTER SERVER AND ESXI
ADDING AND CONFIGURING VMWARE VSPHERE VCENTER SSO ACTIVE DIRECTORY AS LDAP SERVER
VMWARE VSPHERE POWERCLI INSTALLATION AND CONFIGURATION STEP BY STEP

SOFTERRA ADAXES - A new way to manage Active Directory

September 2, 2017 08:26PM

What is Adaxes?
Adaxes is a rescuer for any Active Directory, Exchange and Office 365 environment. It gives additional features automates repetitive everyday operations, enhances security, enforces standards and reduces the load on your IT department. Managing your IT environment with Adaxes is simpler and more efficient.

Key Features 

  1. Active Directory Management Adaxes provides enhanced AD management experience that can be integrated into any environment. It gives you powerful instruments to automate repetitive tasks, securely delegate operations, and keep your system up-to-date.
  2. Active Directory Web UI with Adaxes Web Interface everyone can have a convenient and easy-to-access way to execute all their AD-related tasks. The Web UI can be fully customized to fit the needs of any category of user — from admins to end users.
  3. Automated User Provisioning all user lifecycle tasks can be completely automated by Adaxes. No more manual account setups, user updates or off boarding procedures! Save time, money and put the human factor mistakes away from your environment.
  4. Exchange Management & Automation All user lifecycle tasks can be completely automated by Adaxes. No more manual account setups, user updates or offboarding procedures! Save time, money and put the human factor mistakes away from your environment.
  5. Role-Based Access Control Adaxes introduces an efficient role-based delegation model that makes managing and monitoring permissions in your system as well as following the least privilege principle a walk in the park.
  6. Office365 Management & Automation Adaxes fully automates the process of assigning and revoking licenses in Office 365. It doesn’t matter if a user is just arriving, getting a promotion or leaving. Adaxes will make sure that all licenses are always up-to-date.
  7. Self-Password Reset Forgotten passwords and locked accounts are most common sources of time wastage for both users and the IT staff. Adaxes allows users to deal with it themselves by answering security questions and/or using SMS codes.
  8. Approval-Based Workflow With Adaxes you can add approval steps to practically any operation in Active Directory, Exchange or Office 365. This allows you to free valuable time by delegating more tasks without losing control over their execution.

adaxes softerra Active directory mangement webui, self password reset office 365 management automation, role based control workflow

WHAT YOU GET WITH ADAXES

A more efficient environment.
Automation helps to free your IT staff from monotonous routine and let them work on improving your environment instead of just maintaining it.

Reduced Workload on IT department.
By enforcing standards and minimizing the number of possible mistakes Adaxes makes your Active Directory a much cleaner and healthier place.

Standardized environment.
With an efficient access control model, regular cleanup activities, approval steps, etc. that Adaxes brings, your AD will be much more secure and less vulnerable to malicious activities.

Increased security.
There is so much more about Adaxes that we would love to tell you about. All the information as well as a FREE 30-day trial are available at adaxes.com.


After reading these all the features and functionalities of Adaxes software I did poc in my environment and tested few features which appealed me after testing. Software can be downloaded from this link. I am installing it on Windows 2016 Server. one of the prerequisite is .net frameworks 3.5 to install it, follow my article INSTALLING .NET 3.5 FRAMEWORKS ON WINDOWS SERVER 2012 R2.  After starting installation I am selecting all the the features including Powershell. Using administrator account for services. This service account should have access 'Log on as service' in gpedit, It will be granted by software itself. 

Softerra Adaxes  SPML Web Service, Powershell module for AD, Service admin account, run log on as service right granted

Softerra Adaxes 2017 provides three web portals for managing Active Directory. Administrators, Help Desk and Self Service. It creates new service configuration, one of the example Security Roles - this are different default permissions to perform task on Active Directory. A single SPML request message can be used to simultaneously create user accounts in multiple provisioning systems. De-provisioning, such as when an employee leaves a company, is done by closing access accounts. This eliminates orphaned accounts and prevents ex-employees from gaining access to customer systems.

This installs an configuration IIS server service and Active Directory Lightweight directory services in the background. Make sure port 54782 is opened in firewall for client connection.

softerra adaxes web interface types helpdesk self-service administrators new configuration spml web services address, firewall port open

For more on installation check this link. Open Adaxes Administrative Console. In the available services click server name where adaxes is installed. Log on the account with currently logged on user.

Softerra Adaxes Service Administration console connect Domain Controller active directory management logon

When I logged in I first checked in the Logging, as it was blank for the first time, So to generate few logs I created, deleted and modified few users and group, and to my amaze it had some fantastic readable information, exactly what I was looking for. One thing I noticed, to capture all the activity information adaxes administration console must be used. If I use dsa.msc - Active directory users and computers console and make some changes they are not captured here.

adaxes Administration Console 2017 active directory logging event log activity delete, modify, create unauthorised changes


Next I tried Ad Self service portal, where users can reset their own password, First I created policy, which includes configuration like secret questions, enrollment and other information (Password can be reset through SMS or Email also). 

Adaxes Administration Console 2017 password self-service policies

Password Self-Service portal can be accessed using link - http://fqdn_IP/AdaxesSelfService/SignIn.aspx. Once logged in, it prompts for enrollment of the service. After providing selected questions answers. Log out from portal and test on login page with Forgot your password? After successfully providing answers of registered questions, according to policy defined, it shows the new random password on screen.active directory adaxes self service password reset portal

Another wow thing is self-service statistics, shows report of Enrollment, password resets and operations. Check defaulters.

Adaxes Administration console password self-Service reset portal active directory statistics enrollment


If you are PowerShell freak like me you will definitely like this part, you get Adaxes powershell cmdlets for automation. Deployment or tasks will be faster, again everything will be logged on to console. 

Adaxes Powershell module for AD active directory


I went thru and tried almost each and every features of Adaxes, I found they are all great for running perfect and error free Active Directory environment, In the last I would like to mention about A business rule is Automation workflows, qualified logic and activities of all types. Adaxes has an ability to program many stuffs with Active Directory and likewise it can connection into many additional jobs resembling Add user in the group, creating Exchange mailboxes, provisioning accounts in Office 365 and even running PowerShell scripts!, you can automate user provisioning procedures with conditions and approvals. This is the beauty of business rule and definitely useful.

vcloud-lab perefect powershell automation scripts after creating user or inetorgperson softerra adaxes administration console business rule.png

 


Verdict

Adaxes Active Directory Management proposals numerous benefits above the simple Active Directory management features originate in Windows Server, particularly in settings with several domains and/or forests.

In environments running older Domain Controllers version 2003 and 2008, the PowerShell module and the many tips and tricks offered by the Adaxes Administration Console (admc.exe) will make it easier to automate tasks.

Adaxes comes at a price. I feel the information above provides more than enough information to build the business case for Adaxes

Installing, importing and using any module in powershell

August 26, 2017 12:25PM

With PowerShell you can achieve great way to automation using additional modules. Modules are additional functionalities or extensions to Powershell. You can also treat them as client softwares, with them you can connect to particular softwares, You will see limitation if you want additional commands and modules does not exist. After installing them you can use related .net objects or adapters. Four types are Powershell modules exist Script, Binary, Manifest, Dynamic. For more detailed information read Microsoft official article

For more on using script check Different ways to bypass Powershell execution policy :.ps1 cannot be loaded because running scripts is disabled

To demonstrate I will take example of ActiveDirectory module. To install it use, Search and open Server Manager, in the Manage, click Add Roles and Features. From Select Features menu, expand Remote Server Administration Tools, Under Role Administration Tools, Select all AD DS and AD LDS tools and Install softwares. Same way you can install other modules and tools from list ie DHCP, Hyper-V and etc, these steps are for Windows 2016 server. If you need it on Windows 10, separate RSAT tools need to be downloaded and installed.server manager, remote server administration tools, RSAT, role administration tools, Active directory module for windows Powershell, AD DS tools

Once Active Directory modules for windows PowerShell installed successfully. Same can be searched in find and open it. Module is already imported on the console. To verify the list of loaded modules run command Get-Module, ActiveDirectory module is in the list. To view what commands are associated to AD use command Get-Command -Module ActiveDirectory. Again to verify everything is OK, I am running one of the AD command Get-ADUser vkunal.

Install Active Directory Module for Windows Powershell, Get-Module, Get-ADUser, Install any module

Next step is helpful when you want to run active directory command from normal PowerShell console. By default these steps are not required for newer versions of PowerShell above v4. As whenever you run related commands ie Get-AdUser, module will automatically loaded it exists on machine. But if you want to manually import it run Import-Module ActiveDirectory. It is a best practice while writing script import module first instead of depend on auto loading of module.

If you want to list of all the installed modules you can run command Get-Module -ListAvailable.

Microsoft windows powershell, Get-module -listavailable any module, Import-Module activedirectory

There might be a scenario, your required modules will not exist in RSAT tools and needs to find it online with Find-Module. This requires active internet. It will show all community and official modules in the list from online repositories. To download required module use command Install-Module ModuleName.

Microsoft Windows Powershell, Find-Module azure, Install-Module azure -force, Internet repository psgallary service management

Module files can be directly copied to modulepath, Path can be viewed using inbuilt command $env:PSModulePath -split ';'. There are 3 default paths. 
C:\Users\username\Documents\WindowsPowerShell\Modules
C:\Program Files\WindowsPowerShell\Modules
C:\Windows\system32\WindowsPowerShell\v1.0\Modules

I have copy-pasted files to first location C:\Users\username\Documents\WindowsPowerShell\Modules, If path does not exist create folders. Note my module folder name and psm1 file has same name and it should be that way to Import it. If in-case you have psm1 module in another location simply provide a file path while importing it. For this step administrator rights are not required.

Microsoft Windows Powershell, module $env PSModulePath -split, Import-Module, Get-Module, GroupMembers, Default module paths

One of the other way to extend Powershell is install 3rd party software check VMWARE VSPHERE POWERCLI INSTALLATION AND CONFIGURATION STEP BY STEP.

Useful articles
Active Directory Powershell: Create bulk users from CSV file
POWERSHELL: INSTALLING AND CONFIGURING ACTIVE DIRECTORY 

Reset forgotten ESXi root password on Domain joined Esxi using vSphere web client and Powercli

August 25, 2017 05:44PM

This article shows one of the reason why you always should follow best practices while configuring any environment. Here I will take a reference of my earlier blog . Few days back I received one personal project to work on, There was an issue, clients were wanted to perform some activity on ESXi ssh putty, but they forgot or unaware of the root password. Task was to reset the forgotten esxi root password, While troubleshooting I found Esxi servers are joined into active directory domain and were part of the vCenter. As this gives me chance to login into ESXi directly using AD user account and perform further activities without any risk of loosing anything.

ESXi 3.5, ESXi 4.x, ESXi 5.x and ESXi 6.x
Reinstalling the ESXi host is the only supported way to reset a password on ESXi. Any other method may lead to a host failure or an unsupported configuration due to the complex nature of the ESXi architecture. ESXi does not have a service console and as such traditional Linux methods of resetting a password, such as single-user mode.

POWERCLI AND VSPHERE WEB CLIENT: JOIN ESXI INTO ACTIVE DIRECTORY DOMAIN CONTROLLER

  • Use portal https://esxiip_fqdn/ui or vsphere client to login into esxi.
  • From left side menu in the Navigator pane, under Host select Manage.
  • Click Security & Users tab and select users.
  • It will list all the local users in esxi, select root from the list.
  • Click pencil icon, edit user,
  • Change password by saving it.

vmware vsphere esxi forgot root passsword change root password edit user root, security, reset password manage.png


Same task can be performed using vmware powercli, to know more on configuring powercli check VMWARE VSPHERE POWERCLI INSTALLATION AND CONFIGURATION STEP BY STEP. Login to the individual Esxi server using command Connect-VIServer Esxi001

To reset root password use Set-VMHostAccount -UserAccount root -Password P@55w0rd. Make sure while resetting password through powercli you are using complex password, Other wise it will throw below error. Same restriction is applied while logging through web client. 

Set-VMHostAccount : 8/25/2017 4:31:54 PM        Set-VMHostAccount               A general system error occurred: Weak password: not enough different characters or classes. Weak password: not enough different characters or classes.
At line:1 char:1

+ Set-VMHostAccount -UserAccount root -Password Computer@1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Set-VMHostAccount], SystemError
    + FullyQualifiedErrorId : Client20_SystemManagementServiceImpl_NewVmHostGroupAccount_ViError,VMware.VimAutomation.
   ViCore.Cmdlets.Commands.Host.SetVMHostAccount

vmware vsphere esxi powercli automation connect-viserver, set-vmhostaccount, get-vmhostaccount, -useraccount password root forgot esxi root password

Powershell Active Directory: ADGroup Managedby - Checkbox Manager can update membership list

August 23, 2017 10:40AM

I found one of the query "How to click checkbox manager can update membership list on Active directory group using powershell" on the whatsapp group Powershell scripting. There is already official MicroSoft blog written for same purpose and there are two parts to it and they are worth reading. I went through the script and found complete logic is built using .net objects, and this might puzzle non-coders if they want to automate the task and made it user friendly for them to use. To execute this script use script Different ways to bypass Powershell execution policy :.ps1 cannot be loaded because running scripts is disabled.

Active Directory Powershell Set-AdGroup Managedby Get-aduser, Manager can update membership list managed by group properties

Setting Managedby user is very easy with command Set-ADGroup GroupName -ManagedBy (Get-ADuser UserName), But if i want to set Manager can update membership list, you have to go .net way. I didnt reinvent the wheel, and using existing code from official MicroSoft blog, So it will be more useful and anyone can use, I have created csv file and kept information group Name, user Name and Domain netbios name. This way I can change multiple Groups. If any of the group or user does not exist, it will show error in red.

.\Update-AdGroupManagedbyAdUser.ps1 -Path Group.csv

Active Directory Powershell ldap Manager update membership list, ADSI adapter, .net object powershell ad acl

This code is available on github: https://github.com/kunaludapi/AD-Powershell-Manager-can-update-membership-list

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#requires -version 4
<#
.SYNOPSIS
    Adds user to manged by tab in AD Group properties and check the box Manager can update the membership list.
.DESCRIPTION
    The Update-AdGroupManagedby adds users to group. It asks for parameter as valid CSV file path (Containing Group, User and Domain details), If you want to update muliple group at once, Another option if you don't have CSV file Username, GroupName and Domain name parameter can be used separately. This cmdlet uses AD .net object to perform its task.
.PARAMETER GroupName
    Prompts you valid active directory Group name. You can use first character as an alias, This is mandetory parameter.
.PARAMETER UserName
    Prompts you valid active directory User name. You can use first character as an alias, This is mandetory parameter.
.PARAMETER Domain
    Provide domain netbios name where you User resides.
.PARAMETER CSV
    Provide valid csv file with Groupname, username and domain information.
.INPUTS
    [String]
.OUTPUTS
    Output is on console directly.
.NOTES
    Version:        1.0
    Author:         Kunal Udapi
    Creation Date:  23 August 2017
    Purpose/Change: Manager can update the membership list
    Useful URLs: http://vcloud-lab.com
.EXAMPLE
    PS C:\>Update-AdGroupManagedbyAdUser -Path C:\temp\Groups.csv

    This command update group from CSV file, CSV file contains information Groupname, UserName and Domain.
.Example
    PS C:\>Update-AdGroupManagedbyAdUser -GroupName Group1 -UserName User1 -Domain vcloud-lab
     
    Here I changing information on single Group using parameter
#>
[CmdletBinding(SupportsShouldProcess=$True,
    ConfirmImpact='Medium',
    HelpURI='http://vcloud-lab.com',
    DefaultParameterSetName='Manual')]
Param
(
    [parameter(ParameterSetName = 'Manual', Position=0, Mandatory=$True, ValueFromPipelineByPropertyName=$true)]
    [alias('U')]
    [String]$UserName,
    [Parameter(ParameterSetName='Manual', Position=1, Mandatory=$True)]
    [alias('G')]
    [String]$GroupName,
    [Parameter(ParameterSetName='Manual', Position=2, Mandatory=$True)]
    [String]$Domain,
    [parameter(ParameterSetName = 'CSV', Position=0, Mandatory=$True, ValueFromPipelineByPropertyName=$true)]
    [alias('CSV','File')]
    [String]$Path
)
begin {
    if (!(Get-Module Activedirectory)) {
        Import-Module ActiveDirectory
    }
    #$groupName = 'Group1'
    #$domain = 'vcloud-lab.com'
    #$userName = 'User1'
    switch ($PsCmdlet.ParameterSetName) {
        'Manual' {
            $Obj = New-Object psobject
            $Obj | Add-Member -Name groupName -MemberType NoteProperty -Value $GroupName
            $Obj | Add-Member -Name UserName -MemberType NoteProperty -Value $UserName
            $Obj | Add-Member -Name Domain -MemberType NoteProperty -Value $Domain
            Break
        }
        'CSV' {
            if (Test-Path -Path $Path) {
                $Obj =  Import-Csv -Path $Path
            }
            else {
                Write-Host "$path does not exist" -BackgroundColor DarkRed
            }
            break            
        }
    }
}
process {
    foreach ($O in $Obj) {
        "Working on group '{0}' adding user '{1}'" -f $O.Groupname, $O.Username
        try {
            $group = Get-ADGroup $O.groupName -ErrorAction Stop
        }
        catch {
            Write-Host "$($O.Groupname) does not exist in Active Directory" -BackgroundColor DarkRed
            Continue
        }
        try {
            $u = Get-ADUser $O.userName -ErrorAction Stop
            $UserDN = $u | Select-Object -ExpandProperty DistinguishedName
            #$UserDN
        }
        catch {
            Write-Host "$($O.UserName) does not exist in Active Directory" -BackgroundColor DarkRed
            Continue
        }
        if ($PsCmdlet.ParameterSetName -eq 'CSV') {
            $Domain = $O.Domain
        }
        $DC = ($group.DistinguishedName -split '=')[-1]
        $userAccount = "{0}\{1}" -f $O.domain.ToUpper(), $O.userName
        $rightGuid = Get-ItemProperty "AD:\CN=Self-Membership,CN=Extended-Rights,CN=Configuration,DC=$domain,DC=$DC" -Name rightsGuid | Select-Object -ExpandProperty rightsGuid
        $Guid = [GUID]$rightGuid
        $user = New-Object System.Security.Principal.NTAccount($userAccount)
        $sid = $user.translate([System.Security.Principal.SecurityIdentifier])
        #$group = Get-ADGroup $groupName
        $GroupDN = $group.DistinguishedName
        $acl = Get-Acl AD:\$GroupDN
        $ctrl =[System.Security.AccessControl.AccessControlType]::Allow
        $rights = [System.DirectoryServices.ActiveDirectoryRights]::WriteProperty -bor[System.DirectoryServices.ActiveDirectoryRights]::ExtendedRight
        $intype = [System.DirectoryServices.ActiveDirectorySecurityInheritance]::None
        #$UserDN = Get-ADUser $userName | Select-Object -ExpandProperty DistinguishedName
        $group = [adsi]"LDAP://$GroupDN"
        $group.put("ManagedBy",$UserDN)
        $group.setinfo()
        $rule = New-Object System.DirectoryServices.ActiveDirectoryAccessRule($sid,$rights,$ctrl,$guid)
        $acl.AddAccessRule($rule)
        Set-Acl -acl $acl -path AD:\$GroupDN
        $acl = Get-Acl AD:\$GroupDN
        $access = $acl.Access | Where-Object {$_.IdentityReference -eq $userAccount}
        if ($access -eq $null) {
            Write-Host "Cannot set Manager can not update membership list on Group $($O.Groupname)" -BackgroundColor DarkRed
        }
    }
}
end {}

Same command can be used for single Group by using below command.

.\Update-AdGroupManagedbyAdUser.ps1 -Groupname GroupName -UserName UserName -Domain vcloud-lab

Active directory users and comptuers powershell, Group properties managed by Name change update, manager can update membership list

Useful Blogs
POWERSHELL: INSTALLING AND CONFIGURING ACTIVE DIRECTORY
Powershell one liner: Create multiple user accounts
Different ways to bypass Powershell execution policy :.ps1 cannot be loaded because running scripts is disabled

Active Directory Powershell: Aduser A value for the attribute was not in the acceptable range of values

August 21, 2017 08:02PM

While writing and testing script Active Directory Powershell: Create bulk users from CSV file, Simulating single user creation I came across an error. This error says.

New-ADUser : A value for the attribute was not in the acceptable range of values
At line:1 char:1
+ New-ADUser -Name TestUser -PasswordNotRequired $true -path 'ou=new,dc ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (CN=TestUser,ou=new,dc=vcloud-lab,dc=com:String) [New-ADUser], ADException
    + FullyQualifiedErrorId : ActiveDirectoryServer:8322,Microsoft.ActiveDirectory.Management.Commands.NewADUser

Error is coming up due to incorrect value provided in parameter country as shown in the screenshot. If you even use Set-Aduser same error can be produced.

Active directory domain controller powershell, active directory user properties create new-aduser country a value for the attribute was not in the acceptable range of values

If you see on the Active directory users and computers, dsa.mmc console >> user properties >> Address tab  >> drop down the list of Country/region, It shows full name of the all countries, if I use them in parameter value for example India, it will throw an error. To see correct value I ran cmdlet Get-ADUser username -Properties Country and it showed me country alpha-2 code instead. 

Active Directory Powershell Get-Aduser country properties error -ADUser  A value for the attribute was not in the acceptable range of values

Below are the list of all country with their respective valid Alpha 2 codes. Parameter value need to be supplied as a below code list instead full name. 

Country Name Country code
Afghanistan AF
Åland Islands AX
Albania AL
Algeria DZ
American Samoa AS
Andorra AD
Angola AO
Anguilla AI
Antarctica AQ
Antigua and Barbuda AG
Argentina AR
Armenia AM
Aruba AW
Australia AU
Austria AT
Azerbaijan AZ
Bahamas BS
Bahrain BH
Bangladesh BD
Barbados BB
Belarus BY
Belgium BE
Belize BZ
Benin BJ
Bermuda BM
Bhutan BT
Bolivia (Plurinational State of) BO
Bonaire, Sint Eustatius and Saba BQ
Bosnia and Herzegovina BA
Botswana BW
Bouvet Island BV
Brazil BR
British Indian Ocean Territory IO
Brunei Darussalam BN
Bulgaria BG
Burkina Faso BF
Burundi BI
Cabo Verde CV
Cambodia KH
Cameroon CM
Canada CA
Cayman Islands KY
Central African Republic CF
Chad TD
Chile CL
China CN
Christmas Island CX
Cocos (Keeling) Islands CC
Colombia CO
Comoros KM
Congo CG
Congo (Democratic Republic of the) CD
Cook Islands CK
Costa Rica CR
Côte d'Ivoire CI
Croatia HR
Cuba CU
Curaçao CW
Cyprus CY
Czechia CZ
Denmark DK
Djibouti DJ
Dominica DM
Dominican Republic DO
Ecuador EC
Egypt EG
El Salvador SV
Equatorial Guinea GQ
Eritrea ER
Estonia EE
Ethiopia ET
Falkland Islands (Malvinas) FK
Faroe Islands FO
Fiji FJ
Finland FI
France FR
French Guiana GF
French Polynesia PF
French Southern Territories TF
Gabon GA
Gambia GM
Georgia GE
Germany DE
Ghana GH
Gibraltar GI
Greece GR
Greenland GL
Grenada GD
Guadeloupe GP
Guam GU
Guatemala GT
Guernsey GG
Guinea GN
Guinea-Bissau GW
Guyana GY
Haiti HT
Heard Island and McDonald Islands HM
Holy See VA
Honduras HN
Hong Kong HK
Hungary HU
Iceland IS
India IN
Indonesia ID
Iran (Islamic Republic of) IR
Iraq IQ
Ireland IE
Isle of Man IM
Israel IL
Italy IT
Jamaica JM
Japan JP
Jersey JE
Jordan JO
Kazakhstan KZ
Kenya KE
Kiribati KI
Korea (Democratic People's Republic of) KP
Korea (Republic of) KR
Kuwait KW
Kyrgyzstan KG
Lao People's Democratic Republic LA
Latvia LV
Lebanon LB
Lesotho LS
Liberia LR
Libya LY
Liechtenstein LI
Lithuania LT
Luxembourg LU
Macao MO
Macedonia (the former Yugoslav Republic of) MK
Madagascar MG
Malawi MW
Malaysia MY
Maldives MV
Mali ML
Malta MT
Marshall Islands MH
Martinique MQ
Mauritania MR
Mauritius MU
Mayotte YT
Mexico MX
Micronesia (Federated States of) FM
Moldova (Republic of) MD
Monaco MC
Mongolia MN
Montenegro ME
Montserrat MS
Morocco MA
Mozambique MZ
Myanmar MM
Namibia NA
Nauru NR
Nepal NP
Netherlands NL
New Caledonia NC
New Zealand NZ
Nicaragua NI
Niger NE
Nigeria NG
Niue NU
Norfolk Island NF
Northern Mariana Islands MP
Norway NO
Oman OM
Pakistan PK
Palau PW
Palestine, State of PS
Panama PA
Papua New Guinea PG
Paraguay PY
Peru PE
Philippines PH
Pitcairn PN
Poland PL
Portugal PT
Puerto Rico PR
Qatar QA
Réunion RE
Romania RO
Russian Federation RU
Rwanda RW
Saint Barthélemy BL
Saint Helena, Ascension and Tristan da Cunha SH
Saint Kitts and Nevis KN
Saint Lucia LC
Saint Martin (French part) MF
Saint Pierre and Miquelon PM
Saint Vincent and the Grenadines VC
Samoa WS
San Marino SM
Sao Tome and Principe ST
Saudi Arabia SA
Senegal SN
Serbia RS
Seychelles SC
Sierra Leone SL
Singapore SG
Sint Maarten (Dutch part) SX
Slovakia SK
Slovenia SI
Solomon Islands SB
Somalia SO
South Africa ZA
South Georgia and the South Sandwich Islands GS
South Sudan SS
Spain ES
Sri Lanka LK
Sudan SD
Suriname SR
Svalbard and Jan Mayen SJ
Swaziland SZ
Sweden SE
Switzerland CH
Syrian Arab Republic SY
Taiwan, Province of China[a] TW
Tajikistan TJ
Tanzania, United Republic of TZ
Thailand TH
Timor-Leste TL
Togo TG
Tokelau TK
Tonga TO
Trinidad and Tobago TT
Tunisia TN
Turkey TR
Turkmenistan TM
Turks and Caicos Islands TC
Tuvalu TV
Uganda UG
Ukraine UA
United Arab Emirates AE
United Kingdom of Great Britain and Northern Ireland GB
United States of America US
United States Minor Outlying Islands UM
Uruguay UY
Uzbekistan UZ
Vanuatu VU
Venezuela (Bolivarian Republic of) VE
Viet Nam VN
Virgin Islands (British) VG
Virgin Islands (U.S.) VI
Wallis and Futuna WF
Western Sahara EH
Yemen YE
Zambia ZM
Zimbabwe ZW

Useful articles
POWERSHELL: INSTALLING AND CONFIGURING ACTIVE DIRECTORY 
POWERSHELL ACTIVE DIRECTORY: ADD OR UPDATE (CHANGE) MANAGER NAME IN ORGANIZATION TAB OF USER
POWERSHELL ACTIVE DIRECTORY: ADD OR UPDATE PROXYADDRESSES IN USER PROPERTIES ATTRIBUTE EDITOR
Powershell one liner: Create multiple user accounts

Active Directory Powershell: Create bulk users from CSV file

August 19, 2017 11:00PM

Creating bulk multiple user accounts on Active Directory Users and Computers mmc console is very boring and tough task also it is most of the time consuming and error prone tend to be lots of mistakes. If same task is done using automation it will be interesting and happen in less time. Active directory Powershell is best way to automate the task of importing users from excel file. 

Download script and csv file sample
download new-aduseraccount fake account inventory list in excel csv

My CSV file contains below AD user properties, I tried to cover and take all properties as much as possible. If you would like to add more properties follow Microsoft official link. You will have add the same in script and header column in CSV. Below is example of one user.

Name Patrick Heninghem  active directory powershell user properties all attributes and classes filled up new-aduser 
DisplayName Patrick Heninghem
GivenName Patrick
Surname Heninghem
SamAccountName PH6558
UserPrincipalName PH6558@vcloud-lab.com
EmployeeID 6558
AccountPassword PaTo@6558
Description Employee
EmailAddress Patrick.Heninghem@vcloud-lab.com
Enabled $True
MobilePhone 184.192.5.227
Company vcloud-lab.com
Office Development Center
Department Testing
Division Software
Organization Cider
OfficePhone 339692762
StreetAddress 2392 Cameron Road
City HIGH BRIDGE
State Wisconsin
Country US
PostalCode 54846
Path ou=New,dc=vcloud-lab,dc=com
ProfilePath \\vcloud-lab.com\Profiles\%username%

To execute ps1 scripts follow this blog Different ways to bypass Powershell execution policy :.ps1 cannot be loaded because running scripts is disabled. Next I have kept my both the script in C:\temp folder location, change the location to folder using cd c:\temp command. I am running script and only providing csv file path.

.\New-AdUserAccount.ps1 -Path C:\temp\employees.csv

Active Directory Powershell  New-Aduser, domain controller new-aduseraccount, Ad user, users from csv file, enable-adaccount -identity, set-aduser, dsa.msc, ad users and computers, organization unit.

In next example if you are connecting to remote domain, I am giving explicit domain name and credential.

.\New-AdUserAccount.ps1 -Path C:\temp\employees.csv -Domain vCloud-lab.com -Credential 

Active Directory Powershell  New-Aduser, domain controller new-aduseraccount, Ad user, users from csv file, enable-adaccount -identity, set-aduser, best powershell function advanced usage teach powershell free

This code and CSV is available on Github.

#requires -version 3
<#
.SYNOPSIS
    Create new user account in Active Directory.
.DESCRIPTION
    The New-AdUserAccount cmdlet creates new user accounts on active directory domain controller from CSV file. It asks for parameter valid CSV file path, Optional Active directory domain name and Credential. This cmdlet uses
.PARAMETER Path
    Prompts you for CSV file path. There are 2 alias CSV and File, This is mandetory parameter and require valid path.
.PARAMETER Domain
    This is active directory domain name where you want to connect. 
.PARAMETER Credential
    Popups for active directory username password, supply domain admin user account for authentication.
.INPUTS
    [String]
    [Switch]
.OUTPUTS
    Output is on console directly.
.NOTES
    Version:        1.0
    Author:         Kunal Udapi
    Creation Date:  12 June 2017
    Purpose/Change: Bulk user account creation in Microsoft Active Directory domain from Excel/csv.
    Useful URLs: http://vcloud-lab.com/entries/active-directory/powershell-installing-and-configuring-active-directory-and-dns-server
.EXAMPLE
    PS C:\>New-AdUserAccount -Path C:\temp\employees.csv

    This command create bulk users account in logged in domain from CSV file, It uses default logged in Credentials.
.Example
    PS C:\>New-AdUserAccount -Path C:\temp\employees.csv -Domain vCloud-lab.com -Credential

    Here I have used all the parameters Path with user information, Domain name and Credentials.
.EXAMPLE
    PS C:\>New-AdUserAccount -Path C:\temp\employees.csv -Domain vCloud-lab.com
#>

[CmdletBinding(SupportsShouldProcess=$True,
    ConfirmImpact='Medium',
    HelpURI='http://vcloud-lab.com',
    DefaultParameterSetName='File')]
Param
(
    [parameter(ParameterSetName = 'File', Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
    [parameter(ParameterSetName = 'Credential', Position=0, Mandatory=$true)]
    [alias('CSV', 'File')]
    [ValidateScript({
        If(Test-Path $_){$true}else{throw "Invalid path given: $_"}
        })]
    [String]$Path,
    [Parameter(ParameterSetName='Credential', Position=1, Mandatory=$True)]
    [alias('ADServer', 'DomainName')]
    [String]$Domain,
    [Parameter(ParameterSetName='Credential')]
    [Switch]$Credential
)
#$Path = 'C:\temp\employees.csv'
if ($Credential.IsPresent -eq $True) {
    $Cred = Get-Credential -Message 'Type domain credentials to connect remote AD' -UserName (WhoAmI)
}
Import-Csv -Path $Path | foreach -Begin {
    try {
        Import-Module ActiveDirectory -ErrorAction Stop
    }
    catch {
        Write-host "Missing....Install ActiveDirectory Powershell feature -- RSAT (Remote Server Administration). Cannot Create Accounts" -BackgroundColor DarkRed
        Break
    }

} -Process {
    $UserProp = @{ 
            Name = $_.Name
            SamAccountName = $_.SamAccountName 
            UserPrincipalName = $_.UserPrincipalName 
            GivenName = $_.GivenName 
            DisplayName = $_.DisplayName 
            Surname = $_.Surname 
            AccountPassword = (ConvertTo-SecureString -AsPlainText $_.AccountPassword -Force) 
            Description = $_.Description
            EmployeeID = $_.EmployeeID 
            EmailAddress = $_.EmailAddress
            Path = $_.Path 
            MobilePhone = $_.MobilePhone
            Company = $_.Company
            Office = $_.Office 
            Department =  $_.Department 
            Division = $_.Division 
            Organization = $_.Organization 
            OfficePhone = $_.OfficePhone 
            StreetAddress = $_.StreetAddress
            City = $_.City
            State = $_.State
            Country = $_.Country
            PostalCode = $_.PostalCode
            ProfilePath = $_.ProfilePath
            ErrorAction = 'Stop'
    }
    try {
        $Name = $_.Name
        Write-Host "Processing account $Name" -NoNewline -BackgroundColor Gray
        switch ($PsCmdlet.ParameterSetName) {
            'Credential' {
                if ($Credential.IsPresent -eq $false) {
                    New-ADUser @UserProp -Server $Domain
                }
                else {
                    New-ADUser @UserProp -Server $Domain -Credential $Cred
                }
                Break
            }
            'File' {
                New-ADUser @UserProp; break
            }
        }
            Enable-ADAccount -Identity $_.SamAccountName -ErrorAction Stop
            Set-ADUser -Identity $_.SamAccountName -ChangePasswordAtLogon $True
            Write-Host "....Account $Name successfully created" -BackgroundColor DarkGreen
    }
    catch {
        Write-Host "....Processing $Name failed" -BackgroundColor DarkRed
    }
} -End {}

Useful articles
POWERSHELL: INSTALLING AND CONFIGURING ACTIVE DIRECTORY 
POWERSHELL ACTIVE DIRECTORY: ADD OR UPDATE (CHANGE) MANAGER NAME IN ORGANIZATION TAB OF USER
POWERSHELL ACTIVE DIRECTORY: ADD OR UPDATE PROXYADDRESSES IN USER PROPERTIES ATTRIBUTE EDITOR
Powershell one liner: Create multiple user accounts

View older posts »