NewUser file error and modificatioin

Hi,
I have been trying to run the script ‘NewUser.PS1’, then i get the following;

  1. open dialog box to open file / select file
    Q. how can this script run without prompting select file? that is I want it to silently open file without my intervention.

  2. once the file is selected, the script loads AD modules, then the error below. please help sort this out.
    error

1 Like

Hi Team, please any guide in this?

1 Like

Hey @fruitituti,

If you don’t want to use the open file dialog, then remove that code and just add the Get-Content -Path “path to your csv file…” command.

For the second issue, there is a syntax error with your new user command. Please share your full code so we can take a look.

# Import Active Directory module
Import-Module ActiveDirectory

# Open file dialog
# Load Windows Forms
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null

# Create and show open file dialog
$dialog = New-Object System.Windows.Forms.OpenFileDialog
$Dialog.InitialDirectory = $StartDir
$dialog.Filter = "CSV (*.csv)| *.csv" 
$dialog.ShowDialog() | Out-Null

# store file path in variable
$CSVFile = $dialog.FileName

# Import file into variable
# Validate file path
# If the file path is not valid, then exit the script
if ([System.IO.File]::Exists($CSVFile)) {
    Write-Host "Importing CSV..."
    $CSV = Import-Csv -LiteralPath "$CSVFile"
} else {
    Write-Host "File path specified was not valid"
    Exit
}

# Iterate over each line in the CSV file
foreach($user in $CSV) 
    {

# Password
	
    $SecurePassword = ConvertTo-SecureString "$($user.'First Name'[0])$($user.'Last Name')20!@#" -AsPlainText -Force
 
    # Format their username
    $Username = "$($user.'Initials').$($user.'Last Name')"
    $Username = $Username.Replace(" ", "")

  # Create new user
 New-AdUser -Name "$($user.'First Name') $($user.'Last Name')" `
                -GivenName $user.'First Name' `
                -Surname $user.'Last Name' `
                -UserPrincipalName $Username `
                -SamAccountName $Username `
                -EmailAddress $user.'Mail' `
                -Description $user.Description `
                -OfficePhone $user.'Phone' `
                -Path "$($user.'Organizational Unit')" `
                -ChangePasswordAtLogon $true `
                -AccountPassword $SecurePassword `
                -Enabled $([System.Convert]::ToBoolean($user.Enabled))

 # Write to host that we created a new user
    Write-Host "Created $Username / $($user.'Email Address')"
 
 # If groups is not null... then iterate over groups (if any were specified) and add user to groups
    if ($User.'Add Groups (csv)' -ne "") {
        $User.'Add Groups (csv)'.Split(",") | ForEach {
            Add-ADGroupMember -Identity $_ -Members "$($user.'First Name').$($user.'Last Name')"
            WriteHost "Added $Username to $_ group" # Log to console
        }
    }

# Write to host that we created the user
    Write-Host "Created user $Username with groups $($User.'Add Groups (csv)')"
}
 
Read-Host -Prompt "Script complete... Press enter to exit."
1 Like

Hmm that appears to be good. Are you using the same CSV? Is it possible that one of your user names is enabled? Which user is it failing on? Press F9 to add a line break at the troubled line.

@ServerAcademy

i have modified file path as below but i am getting access denied error, which part should i replace? with what? note: it is not permissions coz i am running PS elevated. if i enable dialogue it is accessible.

I also want to add extension attributes and proxy addresses, in my case i have SIP: and SMTP:

Open file dialog

#Load Windows Forms
[System.Reflection.Assembly]::LoadWithPartialName(“System.windows.forms”) | Out-Null

#Create and show open file dialog
#$dialog = New-Object System.Windows.Forms.OpenFileDialog
#$dialog.InitialDirectory = $StartDir
#$dialog.Filter = “CSV (*.csv)| *.csv”
#$dialog.ShowDialog() | Out-Null

Get file path

$CSVFile = Get-Content -Path “C:\script1\NewUsers1\NewUsers.ps1”

1 Like

If it’s an access denied error then most likely you need to run the ISE or script as Administrator. Also, why do you use the open file dialog but also specify the file path?

@ServerAcademy

Okay, access rights and filepath is sorted. thank you.
I deleted the dialogue section.

I want to add the following attributes:
I also want to add cloudextensionAttribute1 and proxy addresses, in my case i have SIP: and SMTP:

can you guide with right script to include these?

1 Like

Good call! So you can add custom attributes by adding this to your New-ADUser command:

New-ADUser [...] -OtherAttributes @{'cloudextensionAttribute1'="abc";'proxyaddresses'="xyz"}

You should also be able to splat your custom attributes like so to make it easier to read…note I haven’t tested this code though:

$customAttributes = @{
    'cloudextensionAttribute1' = "abc";
    'proxyaddresses' = "xyz"
}
New-ADUser [...] -OtherAttributes $customAttributes 

Hi I am still dealing with this cloud extension attribute, currently its not working, should i use the object name as in AD? I can see we have only used a section of the name. what would be the correct way.

1 Like

@fruitituti, I will need to see what command you tried and what error you received in order to help. I can’t really figure out what’s going on based on your message. Are you still trying to add custom attributes?

Has your AD schema been extended to support those attributes?

@ServerAcademy

  1. This is the code i am using for extension attribute
    {
    $ext = [ADSI]“LDAP://$dn”
    $ext.Put(“extensionAttribute1”, $.ExtensionAttribute1)
    Try { $ext.SetInfo() }
    Catch { Write-Host "[ERROR]`t Couldn’t set the Extension Attribute : $($
    .Exception.Message)" }
    }
    image

  2. I would like to add user to group based on an attribute for example “Department”, ie, if department = sales, the user will go to (A, B, C, and D).
    my current code; this is adding from text field(working correctly)
    if ($.‘Add Groups (csv)’ -ne “”) {
    $
    .‘Add Groups (csv)’.Split(",") | ForEach {
    Add-ADGroupMember -Identity $_ -Members “$sam”
    Write-Host “Added $sam to $_ group” # Log to console
    }
    }

I want something like this; just help with modification to work correctly, i have compiled it to reflect what i am expecting.

		if ($_.'Department' -ne "") {
			$filter = 'Department -eq "$_.Department"'
			Get-ADUser -Filter $filter | Add-ADPrincipalGroupMembership -MemberOf '$_.Department'
			}
		} 

Thank you