PowerShell Script to create new AD user account using existing user ID

Amit Hanamannavar 1 Reputation point

Script to create new AD user account using existing user ID

import-module activedirectory

$User = Get-AdUser -Identity (Read-Host "Copy From Username")
$DN = $User.distinguishedName
$OldUser = [ADSI]"LDAP://$DN"
$Parent = $OldUser.Parent
$OU = [ADSI]$Parent
$OUDN = $OU.distinguishedName
$source = $User.SamAccountName

$NewUser = Read-Host "New Username"
$firstname = Read-Host "First Name"
$Lastname = Read-Host "Last Name"
$NewName = "$firstname $lastname"
$EmailID = Read-Host "Enter email id"
$Description = Read-Host "Enter the Description"

New-ADUser -SamAccountName $NewUser -DisplayName $NewName -UserPrincipalName $newUser -GivenName $firstname -Surname $lastname -Instance $DN -Path "$OUDN" -AccountPassword (Read-Host "New Password" -AsSecureString) -Enabled $true -EmailAddress $EmailID -Description $Description
get-adprincipalgroupmembership $source | add-adgroupmember -members $newuser -ErrorAction silentlycontinue

Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
20,608 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Shashi Shailaj 7,581 Reputation points Microsoft Employee

    @Amit Hanamannavar ,

    Thank you for sharing your knowledge. This script looks good. It does not seem that you have any query around this. I would suggest you to contribute directly using nuget API to the powershellgallery.com so that its accessible from any machine for anyone who points to PSGallery repository on their windows machine.

    Please logon to the https://www.powershellgallery.com/ and signin/register if you do not have an account . you can use your Microsoft account to signin (similar as the one you use this QnA forum.) You can then go to the Apikeys section on your profile https://www.powershellgallery.com/account/apikeys to create an APi key as per your need to publish the package.


    After this you can publish the same to the Powershell Gallery using the Publish-module/Publish-Script cmdlet as per the module/script you would like to publish. using NugetAPIkey you had obtained in the last step

    Publish-Script -Path <scriptPath> -NuGetApiKey <apiKey>  


    Please check more in the documentation on how to create and publish an item along with the best practices about publishing to powershell gallery. Hope this is useful for future scripts. you will also be able to access them on any machine with powershell connected to the web. In case this information helps , please do accept this as answer . If I have misunderstood your query , please do let us know about the question you have around the script and we will be happy to assist you or point to the right resources.

    Thank you.

    0 comments No comments