Export/Import AD Users including manager attribute - powershell

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
}

Related

Modify Active Directory attribute with New-ADuser

My need is to feed attribute 'Ms-Ds-ConsistencyGUID' in our AD but It looks way more difficult than I expected. Here is the script I have done so far :
ipmo activedirectory
# Combo box
$collection = #()
$a = [System.Management.Automation.Host.ChoiceDescription]::new("&Oui")
$collection+=$a
$b = [System.Management.Automation.Host.ChoiceDescription]::new("&Non")
$collection+=$b
$annuler =
[System.Management.Automation.Host.ChoiceDescription]::new("&Annuler")
$collection+=$annuler
$prompt = $Host.UI.PromptForChoice("Messagerie","L'utilisateur aura-t-il
besoin d'une messagerie ?",$collection,0)
Switch ($prompt) {
0 {
# Import CSV file
$users = import-csv C:\Users\...\Desktop\test_bulk.csv -delimiter ";"
foreach ($User in $users)
{
# User's info
$Displayname = $User.Givenname + " " + $User.Surname
$Usersurname = $User.Surname
$Userfirstname = $User.Givenname
$SAM = $User.Samaccountname
$OU = $User.path
$password = $User.Password
$UPN = $SAM + "#...com"
$emailaddress = ($User.Givenname + "." + $User.Surname + "#...com").ToLower()
$description = get-aduser -Identity $User.gpuser -Properties Description | select -ExpandProperty description
$homedirectory = "\\server\$($User.Samaccountname)"
$infotab = $User.invcode
[guid]$obGUID = get-aduser $newuser -Properties objectguid | Select -ExpandProperty Objectguid
$newuser = New-ADUser -PassThru -Name $Displayname -Surname
$Usersurname -GivenName $Userfirstname -SamAccountName $SAM -Path $OU
-AccountPassword (ConvertTo-SecureString $password -AsPlainText -Force) -
Enabled $true -ChangePasswordAtLogon $false -PasswordNeverExpires $false
-UserPrincipalName $UPN -EmailAddress $emailaddress -Description
$description -ScriptPath "login.vbs" -HomeDrive "H:" -HomeDirectory
$homedirectory
-OtherAttributes #{businesscategory="Internal";
info="|MAIL_MAILBOX_O365||RU_$($infotab)|"; ms-ds-consistencyguid =
"$obguid"}
# Group membership
$gpuser = Get-ADPrincipalGroupMembership $User.gpuser | select -ExpandProperty name
$excludefromlist = #("Group1", "Group2", "Group3")
$newgrouplist = $gpuser | where {$_ -notin $excludefromlist}
# Creation of the new user
Add-ADPrincipalGroupMembership -Identity $newuser -MemberOf $newgrouplist
}
}
1 { ... }
2 { ... }
}
As you can see attribute 'ms-ds-consistencyGUID' is fed with the variable '$obguid'. But that variable extracts objectGUID out of the new user's profile which is on the way to be created. This is kinda tricky.
Do you have any idea how I can set that?
You can't set the attribute at the time of creation since the GUID is not known yet. You will have to update it after you create it.
You're already specifying the PassThru parameter, which means that the New-ADUser command will return the new user, which then means you can pass that to Set-ADUser.
$newuser = New-ADUser -PassThru ...
Set-ADUser $newuser -Replace #{"ms-ds-consistencyGUID" = $newuser.ObjectGUID}
#Gabriel, You mean I can state these two cmdlets without any issue :
Add-ADPrincipalGroupMembership -Identity $newuser -MemberOf $newgrouplist
Set-ADUser $newuser -Replace #{"ms-ds-consistencyGUID" = $newuser.ObjectGUID}
I thought it was not the right way to go but it finally works so...

Remove specific items from a list

I am creating a script that will help my colleagues to create a new AD user. This is what I have done so far:
ipmo activedirectory
$users = import-csv C:\Users\...\Desktop\test_bulk.csv -delimiter ";"
foreach ($User in $users)
{
$Displayname = $User.Givenname + " " + $User.Surname
$Usersurname = $User.Surname
$Userfirstname = $User.Givenname
$SAM = $User.Samaccountname
$OU = $User.path
$password = $User.Password
$newuser = New-ADUser -PassThru -Name $Displayname -SamAccountName $SAM -
GivenName $Userfirstname -Surname $Usersurname -AccountPassword (ConvertTo-SecureString $password -AsPlainText -Force)-Enabled $true -Path $OU -ChangePasswordAtLogon $false -PasswordNeverExpires $true -OtherAttributes #{businesscategory="Internal"}
$gpuser = Get-ADPrincipalGroupMembership $User.gpuser | select -ExpandProperty name
Add-ADPrincipalGroupMembership -Identity $newuser -MemberOf $gpuser
}
As you can see I have set a variable $gpuser so I can output a user's group membership to set all these into the new user's membership.
But there is a little hurdle... I need to remove up to three groups from the retrieved list.
I mean each time I output a user's membership I need to remove a few groups IF they are present in the list.
The thing is I don't know how to script that and where to start.
You should take a look at the Where-Object cmdlet and the -notin operator.
Basically you will do something like this:
$excludeFromThisList = #("group1", "group2")
$newGroupList = $gpuser | Where-Object { $_ -notin $excludeFromThisList }

How can I modify this powershell code in Active Directory, to be able to change attributes when emply cells from csv file?

I have a csv file with datas:
SamAccountName;MobilePhone;surname
abc;2313;abc
bca;;bca
cba;3243>cba
How can I change this code to replace the cells where no data is available. For example I can't change the bca user attributes because no mobilephone available.
Here is the code:
PS C:\Users\Administrator> Import-Csv "C:\jo.csv" -Delimiter ';' |
ForEach-Object{
Set-ADUser -Identity $_.SamAccountName -Surname $_.surname -Givenname $_.givenname -Displayname $_.displayname -Title
$_.Title -Department $_.Department -Manager $_.Manager -OfficePhone $_.HomePhone -MobilePhone $_.MobilePhone
}
You can do something called splatting in PowerShell, where you construct the parameters into an object and feed that object to the cmdlet instead of each individual parameter.
Something like this:
$params = #{Identity = $_.SamAccountName}
if (-not [string]::IsNullOrWhiteSpace($_.surname)) {
$params.Surname = $_.surname
}
if (-not [string]::IsNullOrWhiteSpace($_.givenname)) {
$params.Givenname = $_.givenname
}
#Do the same for all the other parameters
Set-ADUser #params
Because of the null values you can always use a replace command.
In your script:
$Temp = "C:\jo.csv"
(Get-Content $Temp -Raw) -replace '""','"-"' | Set-Content $Temp
#Replace the "" with "-" because the set-aduser can not complete with null values
After that you can simply run the Set-ADUser command.

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.

Office 365 license not assigned using new-msoluser

I have a Powershell (5.0) script that imports a CSV file and creates new Office 365 users. The accounts are being created correctly, however the specified license is not being applied.
My script:
Import-Csv -Path C:\Temp\tmp9DBC.csv | %{ New-MsolUser -DisplayName $_.DisplayName -UserPrincipalName $_.UserPrincipalName -City $_.City -Country $_.Country -Department $_.Department -FirstName $_.FirstName -LastName $_.LastName -ForceChangePassword:$True -UsageLocation $_.Location -Password $_.Password -PasswordNeverExpires:$True -State $_.State -Title $_.Title -LicenseAssignment $_.License}
All other properties are assigned correctly, but all of my users show isLicensed = false.
Assigning the license manually works fine, so I know that the SKU is good. Why is it not being applied?
EDIT: Sample entry from CSV file as requested:
ADULTMAN Vincent,adultmanv#domain.onmicrosoft.com,MyCity,MyCountry,Library and Information Services,Vincent,Adultman,"xxxxxxxxxxxxxx:STANDARDWOFFPACK_IW_FACULTY",Jaom3231,WA,Library Assistant
While using Import-Csv power shell command you must make sure that you are using the same column name which are mentioned in the csv file.
As your csv file contains column AccountType for licensing details, so please replace your existing powershell command with this:
Import-Csv -Path C:\Temp\tmp9DBC.csv | %{ New-MsolUser -DisplayName $_.DisplayName -UserPrincipalName $_.UserPrincipalName -City $_.City -Country $_.Country -Department $_.Department -FirstName $_.FirstName -LastName $_.LastName -ForceChangePassword:$True -UsageLocation $_.Location -Password $_.Password -PasswordNeverExpires:$True -State $_.State -Title $_.Title -LicenseAssignment $_.AccountType}
Hope this will help you.