Copy user template issue powershell - powershell

I want to use a user instance/user template to create my new users, so I wrote this:
$userInstance = "'" + "Get-ADUser -Filter { CN -eq " + "'" + $_.userInstance + "'" + " } -Properties *" + "'";
$path = $_.Path;
#create user
New-ADUser -SAMAccountName $_.SAMAccountName -Instance $userInstance -Name $_.name -DisplayName $_.displayName -Path "OU=$Path" -GivenName $_.givenname -Surname $_.surname -userPrincipalName $_.userprincipalname -AccountPassword (ConvertTo-SecureString -String $_.Password -AsPlainText -Force) -PassThru | Enable-ADAccount;
But it doesn't copy the member of properties, or the home folder path.
I must be overlooking something because I checked the Microsoft forms and other users seemed to be doing this same trick.
I read about the -expand param but I want to copy all of the properties so that shouldn't be what I want to use. Hence I use -Properties *.
When I searched this forum I couldn't find any answers for this exact problem. If anyone finds an answer please let me know! Maybe I didn't search using the right words :). Thanks for any replies in advance.

If i remember correctly then group memberships are not duplicated if you use the -instance parameter of New-ADUser. You will probably have to do it yourself.
Something like this should work for that:
Add-ADPrincipalGroupMembership -id "NewUserName" -MemberOf (Get-ADPrincipalGroupMembership -id "Templateuser")
Homedirectory should work though.

Related

Set-AdUser a referral was returned from the server

I'm trying to set a new company value for users from a CSV.
I read that you get the error when not setting the server in my Set-AdUser command.
At line:18 char:18
+ ... $query | Set-ADUser -Server tstdc01 -Company "New Company"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ResourceUnavailable: (CN=testUser\, H...DC=domain,DC=local:ADUser) [Set-ADUser], ADReferralException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8235,Microsoft.ActiveDirectory.Management.Commands.SetADUser
--------------------------------------------------------------------------------------------------------
Import-Module ActiveDirectory
$users = Import-Csv -Path "pathToCsv.csv" -Encoding UTF8 -Delimiter ";"
$setUsers = #()
$domain = "domain.local:3268"
foreach ($user in $users) {
$samAccountName = $user.samAccountName
$query = Get-ADUser -Filter {Samaccountname -eq $samAccountName} -Server $domain
if ($query) {
$query | Set-ADUser -server tstdc01-Company "New Company"
$setUsers += $query
}
}
As Santiago implied this looks like an issue of cross domain or forest communication. And/or you are passing a user from one domain and attempting to set it in another.
See here, and a link here
An aside, a few pointers; You don't need to filter for samAccountName when you already have the samAccountName, the query can be something like:
$setUsers =
Get-ADUser $samAccountName -Server $domain |
ForEach-Object{
Set-ADUser $_ -Server tstdc01 -Company "New Company" -PassThru
}
Also note: you should avoid += I don't know how big a job this is, but it can degrade performance as it causes the creation of a new array and a copy of the existing array. Repeated many times that can cause big performance issues. There are a number of ways to address that, but the preferred approach is to let PowerShell gather the results for you. So above assign the $setUsers variable to the output of the loop. Add -PassThru to output the object that was set.
Update:
With the point regarding += demonstrated, #SantiagoSquarzon pointed out we don't even need the loop anymore:
$setUsers =
Get-ADUser $samAccountName -Server $domain |
Set-ADUser -Server tstdc01 -Company "New Company" -PassThru

Trying to add SAM, country, language and proxyaddress from CSV

So I have CSV file with all these values firstname, lastname, SAM, email, department, OU, country, language and proxyaddress.
I can successfully create users but don't know how to add most importantly SAM and proxyaddress, but also don't know how I would add department, country and language into each users attributes, these other values are less important.
What I've tried:
Set-Mailbox -Identity $name -EmailAddresses #{add= $proxy}
Get-ADUser -Filter 'Name -like "*"' -SearchBase $ou -Properties * | % {Set-ADUser $_ -add #{proxyAddresses=$proxy}}
Add-ADGroupMember -Identity groupname
Here is the code:
Import-Module ActiveDirectory
$securedPassword = ConvertTo-SecureString "" -AsPlainText -Force
$userlist = Import-Csv "C:\users.csv"
ForEach ($row in $userlist) {
$fname = $row.'givenName'
$lname = $row.'Lastname'
$sam = $row.'SAM'
$mail = $row.'mail'
$department = $row.'Department'
$ou = $row.'OU'
$country = $row.'Country'
$lang = $row.'Preferredlanguage'
$proxy = $row.'Proxy'
$name = $fname + $lname
$proxy = $row.'Proxy' -split ';'
New-ADUser -Name "$fname $lname" -GivenName $fname -Surname $lname -UserPrincipalName "$mail" -Path $ou -AccountPassword $securedPassword -ChangePasswordAtLogon $true -EmailAddress $mail
Error when trying to include SAM into New-ADUser:
New-ADUser : The name provided is not a properly formed account name
At C:\test.ps1:28 char:5
+ New-ADUser -sAMAccountName $sam -Name "$fname $lname" -GivenName ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (CN=Fay,OU=Us...,DC=com:String) [New-ADUser], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:1315,Microsoft.ActiveDirectory.Management.Commands.NewADUser
Without seeing your CSV file I can't say for sure, but it sounds like your CSV has a value that is not valid as a sAMAccountName. There are rules for what it can be, which are listed in the documentation:
This attribute must be 20 characters or less to support earlier clients, and cannot contain any of these characters:
"/ \ [ ] : ; | = , + * ? < >

Ongoing work - Powershell Script For Creating Multiple Mailboxes From CSV - With some additional Features

I am currently working on a script that should do the following features:
Create New-mailboxes, according to CSV File, Which is currently set-up like this:
The script i am using, is as follows.
#. 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'
#Connect-ExchangeServer -auto
<#
# Bulk Mailbox creation for Exchange.
Will create Mailbox's & AD Users.
CSV / script can be expanded to create more attributes.
Steve Lindsey
11/11/2013
#>
#csv format needs to be as follows: 
#Alias,Firstname, Lastname,Name,UPN,OUpath,MBDB,password
#change the name and path of the csv file as required.
Import-Module ActiveDirectory
$users = Import-CSV C:\Users\user\Desktop\PowerShell\mailboxes2.csv
$users| foreach {
$Password = convertto-securestring $_.password -asplaintext -force
new-mailbox -name $_.name -alias $_.alias -displayname $_.Displayname -FirstName $_.Firstname -LastName $_.Lastname -userPrincipalName $_.userPrincipalName -PrimarySmtpAddress $_.PrimarySmtpAddress -Database $_.database -RetentionPolicy "b3a83dc4-e471-4d05-b357-25535aa027af" -OrganizationalUnit $_.OrganizationalUnit -Password $Password –ResetPasswordOnNextLogon:$false
}
sleep 30
foreach($user in $users){set-mailbox $user.alias -EmailAddressPolicyEnabled:$true}
sleep 30
foreach($user in $users){set-mailbox $user.alias -EmailAddressPolicyEnabled:$false}
sleep 30
foreach($user in $users){set-mailbox $user.PrimarySmtpAddress -PrimarySmtpAddress $user.PrimarySmtpAddress}
foreach($user in $users){Get-ADUser -Filter "UserPrincipalName -eq '$($user.userprincipalname)'" | Set-ADUser -PostalCode "0101010101" -POBox "000"}
In addition to what this script initialy does,
I need it to also be able to do following, after creating the mailboxes.
each of the Active Directory - USER objects , created for each mailbox should contain, ZIP \ PostalCode "01010101" -POBox "000" + Description "INC000002507906". and created under
The address tab.
https://imgur.com/NLR9HEg
For the "description" part i would look to set some additional column if possible in the imported CSV. so i can edit it, and each time the script will pick up the text from there.
I have tried the following , to achieve these, at the end of the script.
# foreach($user in $users){Set-ADUser -Filter "UserPrincipalName -eq '$($_.userprincipalname)'" -PostalCode "0101010101" -POBox "000"}
# foreach($user in $users){Get-ADUser -Filter "UserPrincipalName -eq '$($_.userprincipalname)'" | Set-ADUser -PostalCode "0101010101" -POBox "000"}
# foreach($user in $users){Get-ADUser $user.identity | Set-ADUser -PostalCode "0101010101" -POBox "000"}
# foreach($user in $users){Get-ADUser $users |Set-ADUser -PostalCode "0101010101" -POBox "000"}
# Foreach($user in $users){Set-ADUser -Identity $users -PostalCode "01010101" -POBox "000"}
Each time i tried these, i faced with a filter error:
https://imgur.com/c4BDdci
The second thing i need to do , is to force the script to go over the CSV
Again, and set the default SMTP , for each user/mailbox created, as set in
the "PrimarySmtpAddres" column.
This is due, to when the EmailAddressPolicyEnabled:$true cmdlet takes
takes place in the code, it sets the Primary Smtp back to the
organization`s default one.
I researched this a bit online and from what i could gather, this might be accomplished with something like :
Set-mailbox somealias -PrimarySmtpAddress "some.guy#contoso.com"
Combined with for each command, i believe it might work, i am m just not sure of the syntax i should use to accomplish that.
Your help is greatly appreciated
<<< UPDATE >>>
With help from AdminOFThings - most have been accomplished.
Thank you very much sir.
Now , all i have left needed , is the following:
foreach($user in $users){Get-ADUser -Filter "UserPrincipalName -eq '$($user.userprincipalname)'" | Set-ADUser -PostalCode "0101010101" -POBox "000"}
This is, the last "foreach" i have in the script.
i want also, in addition to add " -Description " to the parameters of the Set-ADuser cmdlet. in addition i would like to add, another column to the CSV file,
which will be title "Description" and for each line\mailbox created , a different description will be put in. the script will run and add the description defined on each mailbox in the file, on the description colum\line.
Please assist accomplishing that.

new-aduser and import-csv not working

I've got the following script which imports its data from a CSV file.:
import-csv CSVfilelocation.csv |
new-aduser -name $_.Name -givenname $_.Firstname -surname $_.Lastname -samaccountname $_.samAccountName -userprincipalname ($_.samaccountname+"#dc.contoso.com") -manager $_.Manager -accountpassword (convertto-securestring Password -asplaintext -force) -path "Complete OU path" -Company $_.Company -Description $_.Description -enabled $false
The CSV file only contains two rows of data, The first row containing the column headers and the next row the data.
The script does not throw an error, but it doesn't do anything either. The user is not created and the scripts outputs the >> sign like it is waiting for input.
Executionpolicy is set to unrestricted and the script is run locally from the machine.
Why is it not working?
Most likely you need an explicit foreach to call new-aduser several times.
import-csv CSVfilelocation.csv | % {
new-aduser -name $_.Name -givenname $_.Firstname -surname $_.Lastname -samaccountname $_.samAccountName -userprincipalname ($_.samaccountname+"#dc.contoso.com") -manager $_.Manager -accountpassword (convertto-securestring Password -asplaintext -force) -path "Complete OU path" -Company $_.Company -Description $_.Description -enabled $false
}
EDIT: I've missed that your Powershell waits for more input. This means you have an unclosed parentheses or string somewhere in your line, so check and fix.
Please try this:
Use PowerShell to Read a CSV file and Create Active Directory User Accounts
http://blogs.technet.com/b/heyscriptingguy/archive/2011/12/22/use-powershell-to-read-a-csv-file-and-create-active-directory-user-accounts.aspx
* I THINK THE MOST IMPORTANT PART IS THAT YOU NEED TO STEP THROUGH EACH ITEM IN THE LIST. *
“So!” Lou popped in “We have your entire file in the Windows PowerShell variable $UserList. If we wish to step through this list, we simply use the ForEach-Object cmdlet. There are two ways that we can do this. One is to pipe the information directly into ForEach-Object like this:
$USERLIST | FOREACH-OBJECT { $_ }
“This will echo each entry in the list to the screen.”
“So what is that funny Windows PowerShell variable? The one with the underscore for a name?”
“AhHa! Glad you caught that!” piped up Boo. “That’s one of the many built in automatic variables that Windows PowerShell has. It contains the current object in the pipeline. As we stepped through the information in $UserList, this holds the entire content of that line. Or we can do it this way:
FOREACH ($Person in $UserList) { $ Person }
“In the second instance (using the $Person in $UserList setup), the variable $Person replaces the automatic variable, and it gives us something far more readable. Both work equally well, but I prefer the latter for readability. So if you’d like to access each entry in the list, we reference the names of the columns in your CSV file like this:”
FOREACH ($Person in $UserList) {
$Person.FirstName
$Person.LastName
}
Hope that helps!!
Glen
Found the problem, I had one " too many in my path variable. I guess I should proofread my code better next time.

Export/Import AD Users including manager attribute

I am trying to import users from a csv file, which I exported from a different domain. Unfortunately the manager attribute gives me a hard time.
1. What I have done so far (Export):
I exported User attributes from AD1 with the domain name oldDomain.com into export.csv. In order to generate the export.csv file I useed the following command:
Get-ADUser -Filter * -Property * | Select-Object givenName,sn,name,displayName,sAMaccountName,manager | Export-Csv -Encoding "UTF8" -path \\hostex\Share\export.csv
This will result to the following file:
"givenName","sn","name","displayName","sAMaccountName","manager"
"Test","User1","Test User1","Test User1","test.user1",
"Test","User2","Test User2","Test User2","test.user2","CN=Test User1,OU=Users,DC=oldDomain,DC=com"
2. Problem with Import
Afterwards I try to import/add the users into AD2 which uses the domainname newDomain.org. My command looks like this:
Import-Csv \\hostex\Share\export.csv | ForEach { New-ADUser -AccountPassword (ConvertTo-SecureString Pass321? -AsPlainText -force) -Path "OU=Users,DC=newDomain,DC=org" -GivenName $_.givenName -Name $_.name -Surname $_.sn -DisplayName $_.displayName -SamAccountName $_.sAMAccountName -Manager $_.manager.Replace("DC=oldDomain,DC=com","DC=newDomain,DC=org") }
This leads to an ADIdentityResolutionException. Since the first line of export.csv has no value set for the manager attribute, the command tries to find the user identity "" within AD2. This is impossible to find. Therefore the user is not added to AD2.
In order to resolve this issue I would like to add some kind of If-Statement, which sets the value for the manager attribute only if the equivalent value in export.csv is not null ($_.manager -notlike $null). Any ideas how to achieve this?
You probably attempt to reference a manager account before that account is actually created. Separate account creation from assigning a manager to it. Also, empty fields read from a CSV appear as empty strings, not $null, so you need to compare to '' to filter them out.
Try this:
$users = Import-Csv '\\hostex\Share\export.csv'
$initialPassword = ConvertTo-SecureString 'Pass321?' -AsPlainText -Force
$users | % {
New-ADUser -AccountPassword $initialPassword `
-Path 'OU=Users,DC=newDomain,DC=org' `
-GivenName $_.givenName `
-Name $_.name `
-Surname $_.sn `
-DisplayName $_.displayName `
-SamAccountName $_.sAMAccountName
}
$users | ? { $_.manager -ne '' } | % {
$manager = $_.manager -replace 'DC=oldDomain,DC=com$', 'DC=newDomain,DC=org'
Set-ADUser -Identity $_.sAMAccountName -Manager $manager
}
One way to do this would be to build the complete command as a string with an additional line that adds the manager option to the end of the string if it exists in the data and then use Invoke-Expression to execute the command.
Import-Csv \\hostex\Share\export.csv | ForEach {
$NewUserCommand = "New-ADUser -AccountPassword (ConvertTo-SecureString Pass321? -AsPlainText -force) -Path 'OU=Users,DC=newDomain,DC=org' -GivenName $_.givenName -Name $_.name -Surname $_.sn -DisplayName $_.displayName -SamAccountName $_.sAMAccountName"
If ($_.manager) {$NewUserCommand += " -Manager " + $_.manager.Replace('DC=oldDomain,DC=com','DC=newDomain,DC=org')}
Invoke-Expression $NewUserCommand
}