new-aduser and import-csv not working - powershell

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.

Related

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.

Copy user template issue 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.

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
}

How to add info to the AD users with powershell from a CSV sheet

Let's say I have an CSV sheet, first line with the usernames and the second with the emailadresses.
Example:
Username Emailadress
jhornet jhornet#mail.com
How can I import this info to the AD within a safe and nice way, maybe with a check in it?
This is what I have till now (without CSV):
Import-Module activedirectory
$company = "International"
$username = Get-Content c:\users.txt
$emailadress = Get-Content c:\mail.txt
foreach($user in $username)
{
Set-ADuser -Identity $user -Company $company
}
#second
foreach($emailadress in $username)
{
Set-ADuser -Identity $user -EmailAddress $emailadress
}
Still learning a lot with powershell, some things are just hard to understand and better to see :)
Thanks in advance!
Gr,
JPA
I'm going out on a shaky limb here because I've never used the AD commands before but it should go something like this:
Import-Module activedirectory
$company = "International"
$users = Import-Csv c:\user.csv
$users # dumps users to allow visual inspection
read-host "press Enter to continue or Ctrl+C to abort"
$users | Foreach {Set-ADUser -Identity $_.username -Company $company -whatif}
$users | Foreach {Set-ADUser -Identity $_.username -EmailAddress $_.emailaddress -whatif}
Remove the -WhatIf parameter when you think the commands are going to work correctly.

Adding AD users to security group using a csv file using powershell on windows server 2008 r2

I am trying to add my users to AD groups through PowerShell AD. Here is my current code:
Import-Module ActiveDirectory #Import the active directory module
Import-CSV C:\Userlist.csv | ForEach { #Import the csv file and start the for each statement.
$groups =#{
grouparray = $_.group.split(',')
};
$user = #{ #Create the user variable and set the values within
name=$_.name #Call the name field from the csv file
givenname=$_.givenname #Callthe givenname field from the csv file.
surname=$_.surname #call the surname field from the csv file
samaccountname=$_.samaccountname #Call the samaccountname field from the csv file
department=$_.department #call the department field from the csv file.
accountpassword=(ConvertTo-SecureString "P#ssw0rd" -AsPlainText -Force) #set the password
homedirectory=$_.homedirectory #Call the homedirectory field
emailaddress=$_.emailaddress #call the email address field
mobilephone=$_.mobilephone #call the mobile phone field
Path="Ou=People,dc=G3Zone,dc=local" #Path to the OU "People"
Enabled=$True #enable the account
};##
New-ADUser #user #Create the new user with the information gathered fromthe csv.
add-ADGroupMember -Identity #groups –member $_.samaccountname
} #endforeach
This is my csv file:
name,givenname,surname,samaccountname,department,group,accountpassword,homedirectory,mobilephone,emailaddress
"Todd Fast",Todd,Fast,Tfast,President,ManagerGroup,P#ssword1,\\Group3\homedirs\Tfast,111-1111,Tfast#G3Zone.local
"Joe Doe",Joe,Doe,Jdoe,Accounting VP,"ManagerGroup,AccountingGroup",P#ssword1,\\Group3\homedirs\Jdoe,111-1112,JDoe#G3Zone.local
"Elaine Irving",Elaine,Irving,Eirving,HR VP,"ManagerGroup,HRGroup",P#ssword1,\\Group3\homedirs\Eirving,111-1113,EIrving#G3Zone.local
"Jane Malzur",Jane,Malzur,Jmalzur,Executive Assistant,"ManagerGroup, Corporate",P#ssword1,\\Group3\homedirs\Jmalzur,111-1114,JMalzur#G3Zone.local
Mike Fox,Mike,Fox,Mfox,IS VP,"ManagerGroup,ISGroup",P#ssword1,\\Group3\homedirs\Mfox,111-1115,MFox#G3Zone.local
Julie Cash,Julie,Cash,Jcash,Accounting,AccountingGroup,P#ssword1,\\Group3\homedirs\Jcash,111-1116,JCash#G3Zone.local
Manny Greene,Manny,Greene,Mgreene,Accounting,AccountingGroup,P#ssword1,\\Group3\homedirs\Mgreene,111-1117,MGreene#G3Zone.local
Russ Maine,Russ,Maine,Rmaine,HR,HRGroup,P#ssword1,\\Group3\homedirs\Rmaine,111-1118,RMaine#G3Zone.local
Paul Lam,Paul,Lam,Plam,HR,HRGroup,P#ssword1,\\Group3\homedirs\Plam,111-1119,PLam#G3Zone.local
Tom Scerbo,Tom,Scerbo,Tscerbo,HR,HRGroup,P#ssword1,\\Group3\homedirs\Tscerbo,111-1120,TScerbo#G3Zone.local
Kate McCool,Kate,McCool,KMcCool,HR,HRGroup,P#ssword1,\\Group3\homedirs\KMcCool,111-1121,KMcCool#G3Zone.local
Lech Walsh,Lech,Walsh,Lwalsh,IS,ISGroup,P#ssword1,\\Group3\homedirs\Lwalsh,111-1122,LWalsh#G3Zone.local
Bonnie Clive,Bonnie,Clive,Bclive,IS,ISGroup,P#ssword1,\\Group3\homedirs\Bclive,111-1123,BClive#G3Zone.local
Esther Male,Esther,Malo,Emalo,IS,ISGroup,P#ssword1,\\Group3\homedirs\Emalo,111-1124,EMalo#G3Zone.local
The error I get is:
Add-ADGroupMember : Missing an argument for parameter 'Identity'. Specify a par
ameter of type 'Microsoft.ActiveDirectory.Management.ADGroup' and try again.
At C:\test2.ps1:26 char:29
+ add-ADGroupMember -Identity <<<< #groups -member $_.samaccountname
+ CategoryInfo : InvalidArgument: (:) [Add-ADGroupMember], Parame
terBindingException
+ FullyQualifiedErrorId : MissingArgument,Microsoft.ActiveDirectory.Manage
ment.Commands.AddADGroupMember
Also if possible I'd like to be able to create and add them to their own home directories.
Instead of using Add-ADGroupMember, I use Add-ADPrincipalGroupMembership -Identity $instloginID -MemberOf $instGroup. It works well for me.
I'm a little confused about why you are putting the information in an array. I am not a pro; have only been running posh about 2.5 years. So my question is as much for my benefit as it is for yours. Does the array make it run faster? I plug each part of my user definition into its own variable and do it that way. The code looks a lot more straight forward and possibly easier to maintain that way.
My code to create home directories:
function Create-HomeDirs ($Synonym, $Number2Make, $studhomedir)
{
###################################################################################
# This function creates student home directories. It also assigns permissions. #
###################################################################################
for ($i=1; $i -le $Number2Make; $i++) # Create homedirs from synonym
{
$NewUser = ($Synonym + $i.ToString("00")) # Pad last two digits with zeroes so you get xxxxx01 instead of xxxxx1
$HomeDir = "$studhomedir\$NewUser"
$Principal= "domain\$NewUser"
write-host "HomeDir Being Created = $HomeDir"
New-Item ($HomeDir) –Type Directory
} #end for
#
# The piece that assigns permissions sometimes fails due to sync problems.
# This is why I put the "read-host" command in the code, to slow it down.
#
$x = (read-host "`nReady to do permisisons? Press <Enter> to continue.")
for ($i=1; $i -le $Number2Make; $i++) # Add permissions to homedirs
{
$NewUser = ($Synonym + $i.ToString("00")) # Pad last two digits with zeroes so you get xxxxx01 instead of xxxxx1
$HomeDir = "$studhomedir\$NewUser"
$Principal= "domain\$NewUser"
write-host "newuser = $newuser. Homedir = $homeDir. Principal = $principal"
write-host "HomeDir Permissions being created = $HomeDir"
$Rights = [System.Security.AccessControl.FileSystemRights]"FullControl" # This line and next 3 put security settings in variables
$InheritanceFlag = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit, ObjectInherit"
$PropagationFlag = [System.Security.AccessControl.PropagationFlags]::None
$objType =[System.Security.AccessControl.AccessControlType]::Allow
$objACE=New-Object System.Security.AccessControl.FileSystemAccessRule($Principal, $Rights, $InheritanceFlag, $PropagationFlag, $objType)
$objACL = Get-ACL $HomeDir # Get existing ACL for home directory
$objace
if ($objACe)
{
$objACL.AddAccessRule($objACE) # Add ACE to this ACL
Set-ACL $HomeDir $objACL # Put modified ACL back on home directory
}
else
{write-host "objACL appears to be empty, line 359"}
} #end for
} # end function Create-HomeDirs
Hey guys I figured it out I guess I won't fail after all :)
#Importing the Users
Import-CSV C:\Users\Administrator\Desktop\users.csv | foreach-object {New-ADUser -Name $_.Name -GivenName $_.FirstName -Surname $_.LastName -Enabled $True -PasswordNeverExpires $True -AccountPassword (ConvertTo-SecureString $_.Password -AsPlainText -Force) -ChangePasswordAtLogon $False -Department $_.Department -EmailAddress $_.Email -OfficePhone $_.Phone -Path $_.Path -SamAccountName $_.SamAccountName -Title $_.Title -UserPrincipalName $_.UPN}
#Adding the Users to the Groups
Import-CSV C:\Users\Administrator\Desktop\Powershell\usergroups.csv | ForEach-Object {
$SAM = $_.SAM
$Group = $_.Group
$Groups = $Group.split(" ")
foreach($l in $Groups){
Add-ADGroupMember -Identity $l -Member $SAM
}
}
It's looking for the group identity, which was omitted from the group array and needs to inserted as a $_. variable.