How to show the groups that i copied?

Hi all,

I have this script

Import-Module ActiveDirectory
Add-Type -AssemblyName System.Windows.Forms

#Check Password Policy
Function Test-PasswordForDomain {
    Param (
        [Parameter(Mandatory=$true)][string]$Password,
        [Parameter(Mandatory=$false)][string]$AccountSamAccountName = "",
        [Parameter(Mandatory=$false)][string]$AccountDisplayName,
        [Microsoft.ActiveDirectory.Management.ADEntity]$PasswordPolicy = (Get-ADDefaultDomainPasswordPolicy -ErrorAction SilentlyContinue)
    )

    If ($Password.Length -lt $PasswordPolicy.MinPasswordLength) {
        return $false
    }


   if (($AccountSamAccountName) -and ($Password -match "$AccountSamAccountName")) {
        return $false
    }
   if ($AccountDisplayName) {
    $tokens = $AccountDisplayName.Split(",.-,_ #`t")
    foreach ($token in $tokens) {
        if (($token) -and ($Password -match "$token")) {
            return $false
        }
    }
}
   
   
    return $true   
   
}

function Get-RandomCharacters($length, $characters) {
    $random = 1..$length | ForEach-Object { Get-Random -Maximum $characters.length }
    $private:ofs=""
    return [String]$characters[$random]
}

function Scramble-String([string]$inputString){     
    $characterArray = $inputString.ToCharArray()   
    $scrambledStringArray = $characterArray | Get-Random -Count $characterArray.Length     
    $outputString = -join $scrambledStringArray
    return $outputString 
}


#Check if employee number is free

function Get-AvailableEmployeeNumber {
param(
    [int]$EmployeeNumber,
    [string[]]$AllNum
)

if($AllNum -contains $EmployeeNumber){
    Get-AvailableEmployeeNumber -EmployeeNumber ($EmployeeNumber + 1) -AllNum $AllNum

}
else{
    $EmployeeNumber
}

}





#User creation path
$ADPath = "OU=Users,OU=Alex,DC=alex,DC=local"

    

# Grab Variables from User
$firstname = Read-Host -Prompt "Enter First Name"

# Stop by empty first name
while (!($firstname -eq "")){

# Grab Variables from User
$lastname = Read-Host  -Prompt  "Enter Last Name"
 
do {                                                            
    try {

        $newNum = $false
        While (-not $newNum) {
            $EmployeeNumber = [int](Read-Host "Enter Employee Number")
            If ( $EmployeeNumber.ToString().Length -le 3) {
                $newNum = $true
            }
   
            Else {
   
                [void][System.Windows.Forms.MessageBox]::Show("Length of $($EmployeeNumber.ToString().Length) digits is invalid for employee number, please use up to 3 digits.")

            }
        # Write-Host -ForegroundColor Yellow "Length of $($EmployeeNumber.length) digits is invalid for employee number, please use up to 3 digits."
 
        }


       
    }
    catch [System.Management.Automation.RuntimeException] {
      [void][System.Windows.Forms.MessageBox]::Show("You can only use numbers!")
        #write-host -ForegroundColor Cyan "You can only use numbers!"
       $EmployeeNumber = ""
    }
}
until (($EmployeeNumber -or $EmployeeNumber -eq 0) -and ($EmployeeNumber -match "^[0-9]*$" -and  $EmployeeNumber.ToString().Length -le 3))



    $allNum = 
    [Int32[]]($((Get-ADUser -Filter * -Properties EmployeeNumber).EmployeeNumber)) |
    Sort-Object -Descending 

    $newNum = Get-AvailableEmployeeNumber -EmployeeNumber $EmployeeNumber -AllNum $allNum
    if($newNum -ne $EmployeeNumber){
    
        #write-host -ForegroundColor Green "EmployeeNumber '$EmployeeNumber' is already in use by $((Get-ADUser -Filter {EmployeeNumber -eq $EmployeeNumber}).SamAccountName)"
        [void][System.Windows.Forms.MessageBox]::Show("EmployeeNumber '$EmployeeNumber' is already in use by $((Get-ADUser -Filter {EmployeeNumber -eq $EmployeeNumber}).SamAccountName)")
    }
     [void][System.Windows.Forms.MessageBox]::Show("Employee number'$newNum' is Available")
    #Write-Output "Employee number'$newNum' is Available"
    


$password = Get-RandomCharacters  -length 2 -characters 'abcdefghiklmnoprstuvwxyz'
$password += Get-RandomCharacters -length 1 -characters 'ABCDEFGHKLMNOPRSTUVWXYZ'
$password += Get-RandomCharacters -length 1 -characters '1234567890'
$password += Get-RandomCharacters -length 1 -characters '!"$%&/()=?}][{@#*+'   
      
$copyfrom = Read-Host -Prompt "Copy Groups From"


# Set username
$i = 1
$basename = $firstname
$username = $basename + $lastName.Substring(0,$i)
$username = $username.ToLower()
   
while ((Get-ADUser -filter {SamAccountName -eq $username}).SamAccountName -eq $username)
{

  if($i -gt $lastName.Length){
        # update the basename and reset $i
        $basename = $username
        $i=1
    }

   
        $username = $baseName + $lastName.Substring(0,$i++)
        $username = $username.ToLower()
       
}

$email = $username + "@alex.com" 
$SFB = $username + "@alex.local" 


if (Get-ADUser -Filter "surname -eq '$lastname' -and givenname -eq '$firstname'")

{
  
# Create the AD User
New-ADUser `
-Name "$firstname $lastname ($newNum)" `
-GivenName $firstname `
-Surname $lastname `
-EmployeeNumber $newNum `
-Displayname "$FirstName $lastname" `
-UserPrincipalName $email `
-SamAccountName $username  `
-AccountPassword (ConvertTo-SecureString $password -AsPlainText -Force) `
-Path $ADPath `
-Enabled 1   
}
else
{
   # Create the AD User
New-ADUser `
-Name "$firstname $lastname" `
-GivenName $firstname `
-Surname $lastname `
-EmployeeNumber $newNum `
-Displayname "$FirstName $lastname" `
-UserPrincipalName $email `
-SamAccountName $username  `
-AccountPassword (ConvertTo-SecureString $password -AsPlainText -Force) `
-Path $ADPath `
-Enabled 1   
}

#Copy Groups

$ReferanceUser = Get-ADUser -Identity $copyfrom -Properties memberof

$selectedGroups = $ReferanceUser.memberof

$selectedGroups | Add-ADGroupMember -Members $User

 [void][System.Windows.Forms.MessageBox]::Show("The password for $username is: $password")
#Write-Host -ForegroundColor Blue "The password for $username is: $password"




#Message Popup

   $subject = "New Users Created"
    $Message =
    "User Created: 
    First Name: $firstname 
    Last Name: $lastname 
    Employess number: $newNum 
    Username: $username 
    E-mail: $email 
    Sip: $SFB
    Initial Password: $password

    Make sure to save the initial password in a safe location!
    "

   
    

   
 
#Send Email
 
    $server = "EX2019.alex.local"
    $to = "vinokura@alex.com"
    $from = "ITRobot@alex.com"
    $subject = "New Users Created"

    $Body="

    <img src='\\dc1\Applications\alex.jpg' width='343' height='66'></img>

<br>
    <p><b><h1><font color='blue'>New User Created:</b></p></h1></font> 
    <p><b><font color='black'><h4>First Name: $firstname </b></p></font></h4></b>
    <p><b><font color='black'><h4>Last Name: $lastname </b></p></font></h4></b>
    <p><b><font color='black'><h4>Employess number: $newNum </b></p></font></h4></b>
    <p><b><font color='black'><h4>Username: $username </b></p></font></h4></b>
    <p><b><font color='black'><h4>E-mail: $email </b></p></font></h4></b>
    <p><b><font color='black'><h4>Sip: $SFB</b></p></font></h4></b>
    <p><b><font color='black'><h4>Initial Password: $password</b></p></font></h4></b>

    <p><b><font color='red'><h2>Make sure to save the initial password in a safe location!</b></p></font></h2></b>

    <p><b><font color='green'><h1>Alex IT</b></p></font></h1></b>

    "

    forEach ($useraname in $username){
        $message += "$($username.SamAccountName)     $($username.DisplayName)     $($username.emailaddress)
		"
    

    Send-MailMessage -To $to -From $from -Subject $subject -Body $Body -BodyAsHtml -SmtpServer $server
             
               

#Check if user is creted successfully or not Pop-Up                
            
$username = $username
$User = Get-ADUser -LDAPFilter "(sAMAccountName=$username)"
If ($User -eq $Null) {[void] [System.Windows.Forms.MessageBox]::Show("The user $username not created", "Information") }
Else { [void][System.Windows.Forms.MessageBox]::Show("The user $username created successfully!", "Information")}
            
           
        }


#Check if user is creted successfully or not

#$username = $username
#$User = Get-ADUser -LDAPFilter "(sAMAccountName=$username)"
#If ($User -eq $Null) {Write-Host  -ForegroundColor DarkRed "The user"$username" not created."}
#Else {Write-Host  -ForegroundColor Green "The user"$username" created successfully."}




$firstname = Read-Host -Prompt "Enter First Name"
}
 [void][System.Windows.Forms.MessageBox]::Show(" Done, Thank You")
#Write-Host -ForegroundColor Red "Done, Thank You"


I need help with group topic.

I’m trying to copy groups from user to another user…
and i want to send email with copied gorups.

didn’t find a way

anyone can help please?

That’s a lot of code with a lot of bad coding habits in it. I won’t digg into that. :smirk: Next time shorten the code you’re sharing to the relevant part, please.

What do you mean with “I’m trying …”? If it does not work as expected you should explain what exactly is not working as expected. If you get error messages you should post these error messages along with the relevant code - both formatted as code please.

Copying group memberships is actually 2 lines of code:

$SourceUser = Get-ADUser -Identity 'SourceUser' -Properties MemberOf
Add-ADPrincipalGroupMembership -Identity 'TargetUser' -MemberOf $SourceUser.MemberOf

Instead of creating the email body manually with HTML code, you could use the PowerShell cmdlet ConvertTo-HTML and let PowerShell do the hard work. :wink:

1 Like

thank you and sorry for the long code
its works and its good for me
i used this

$SourceUser = Get-ADUser -Identity 'SourceUser' -Properties MemberOf
Add-ADPrincipalGroupMembership -Identity 'TargetUser' -MemberOf $SourceUser.MemberOf

but i want input of all groups that the user was added to them and i dont know how to get it after the user created and group copied

can you help please great Olaf?

I don’t get it. What input do you mean? The groups to copy are in the variable $SourceUser.MemberOf.

My script is creating new user with name last name employee number and then its asking to copy group from what user
for example i want to copy groups from Olaf to Alex then the user-created and i want a pop what groups move from Olaf to Alex

im using this script to copy groups

$SourceUser = Get-ADUser -Identity $copyfrom -Properties memberof

$SelectedGroups = $SourceUser.memberof | Add-ADGroupMember -Members $username

how can i do it?

Hi sorry for the long code`
this is what I need help with

I run this code

$copyfrom = Read-Host -Prompt "Copy Groups From"


$SourceUser = Get-ADUser -Identity $copyfrom -Properties memberof
$selectedgreoupsstring = ""
$SelectedGroups = $SourceUser.memberof | Add-ADGroupMember -Members $username
foreach($g in $SelectedGroups)
{
    $selectedgreoupsstring += $g + ", "
}

#Message Popup

   $subject = "New Users Created"
    $Message =
    "User Created: 
    First Name: $firstname 
    Last Name: $lastname 
    Employess number: $newNum 
    Username: $username 
    E-mail: $email 
    Sip: $SFB
    Groups: 
    Initial Password: $password

    Make sure to save the initial password in a safe location!
    "

   $verifyDetails = [System.Windows.Forms.MessageBox]

    $Decision = $verifyDetails::Show($Message,"Verify New User Details","OK", "Information")
    

but i don’t know what to put in groups so i can see the list of groups that the new user joined to them
can you help please?

Instead of error prone free text input you should consider offering the user of this script a list of possible choices to pick from.

If you want top have the groups in a comma separated list you can join them with the -join operator:

$selectedgreoupsstring = $($SourceUser.memberof) -join ', '

I don’t get it - you have cumbersomely assembled the variable $selectedgreoupsstring containing all groups and now you’re asking what you should use? Use the variable you just created for that purpose. :thinking:

And just out of curiousity - at the end you output a message box with "Verify New User Details","OK". What happens when it’s not OK? :wink:

this is the inpute
1
after that i tried to add $selectedgreoupsstrin.name

the is no cancel button

any other idea?

If you copied that from my answer you copied my in the meantime already fixed typo. There was the g missing at the end. Sorry for that. But since $selectedgreoupsstring is a string it does not have a property .name And since the groups are stored with their distinguished names the output will probably look awful.

I urgently recommend to do a big step back and start with learning the very basics of PowerShell first. It will save you from a lot of wasted time and frustration.

One of the first things to learn should be how to debug your own code. In the simplest case it is outputting the variables to the console to see what they actually contain during the runtime of the code.

1 Like

as always you helped me thank you

what is was mising is just this
$SelectedGroups = $SourceUser.memberof | Add-ADGroupMember -Members $username -PassThru