Add a new O365 users to AD group using Powershell - powershell

I'm using a Powershell script to add new users to O365 and assign multiple licenses. However i'm now trying to also add the new user to existing groups.
Powershell
Connect-MsolService -Credential $UserCredential
Import-Csv -Path "C:\Users\Jesse\Documents\Powershell\NewAccounts.csv" | foreach {New-MsolUser -DisplayName $_.DisplayName -FirstName $_.FirstName -LastName $_.LastName -UserPrincipalName $_.UserPrincipalName -UsageLocation $_.UsageLocation -LicenseAssignment $_.AccountSkuIdEMS,$_.AccountSkuIdENTERPRISEPACK} | Export-Csv -Path "C:\Users\Jesse\Documents\Powershell\NewAccountResults.csv" -Verbose
.CSV
DisplayName,FirstName,LastName,UserPrincipalName,Usagelocation,AccountSkuIdEMS, AccountSkuIdENTERPRISEPACK
Test Jesse,Test,Jesse,test.jesse#(Tenant).nl,NL,(Tenant):EMS,(Tenant):ENTERPRISEPACK
I've found the following code, but wouldn't know how to correctly implement it into my existing code. I think i would also need to connect to a new service to use this cmdlet. is it possible to switch between connections within a single script?
Add-UnifiedGroupLinks -Identity "Azure AD Join" -LinkType Members -Links test.jesse#(tenant).nl

You could use AzureAD Module cmd Add-AzureADGroupMember to add the new user to existing groups.
Remember to install AzureAD Module by following Azure Active Directory PowerShell for Graph.
You can reuse the $Credential for AzureAD Module in Powershell. It won't require you to login again.
Here is my sample for your reference:
$Credential = Get-Credential
Connect-MsolService -Credential $Credential
Import-Csv -Path "E:\test\NewAccounts.csv" | foreach {New-MsolUser -DisplayName $_.DisplayName -FirstName $_.FirstName -LastName $_.LastName -UserPrincipalName $_.UserPrincipalName -UsageLocation $_.UsageLocation} | Export-Csv -Path "E:\test\NewAccountResults.csv"
Connect-AzureAD -Credential $Credential
$newusers = Import-Csv -Path "E:\test\NewAccounts.csv" | foreach {Get-AzureADUser -Filter "userPrincipalName eq '$($_.UserPrincipalName)'"}
foreach ($user in $newusers){
Add-AzureADGroupMember -ObjectId "{object id of the existing group}" -RefObjectId $user.ObjectId
}
BTW, you can get the object id of the existing group from Azure portal.

Related

How to create Teams with Powershell with a CSV file

I have to manually create Teams, so i thought i would be a good idea to make this proces automatic. The code keeps giving me the error "Cannot validate argument on parameter "DisplayName. The argument is Null or empty".
It is for Windows Server 2012 R2, I think it does recognize the csv file because this is the only error that i'm getting
This is my CSV file
$datacsv = import-csv C:\Users\$$$$$\Desktop\test.csv
Import-Module MicrosoftTeams
foreach ($data in $datacsv)
{
$cred = Get-Credential
Connect-MicrosoftTeams -Credential $cred
$teamname = $data.TeamsName
$owner = $data.Owners
$accestype = $data.TeamType
$member = $data.Members
$group = New-team -DisplayName $teamname -Owner $owner -AccesType $accestype
Add-TeamUser -User $member -GroupId $group.GroupId -DisplayName $teamname
Add-Teamuser -User $owner -GroupId $group.GroupId -DisplayName $owner
}
I expected that the teams would indeed create but this didnt happen.
Sorry for the bad English, my writing is pretty bad.

Active directory migration with powershell

I need to migrate from AD Windows2003Forest to AD 2016. I have below script to create users in bulk. My requirement is to map the same SID of older AD to new AD. For example in older AD SID='xyz' then it should be the same in newAD too as SID='xyz'
I am having all the users data along with SID in CSV format & am using below PowerShell script which is somehow not working. As of advice or suggestions.
powershell code snippent:
#Enter a path to your import CSV file
$ADUsers = Import-csv C:\scripts\newusers.csv
foreach ($User in $ADUsers)
{
$Username = $User.username
$Password = $User.password
$Firstname = $User.firstname
$Lastname = $User.lastname
$Department = $User.department
$OU = $User.ou
$sid = $User.sid
$UserPrincipalName = $User.UserPrincipalName
$DistinguishedName = $User.DistinguishedName
#Check if the user account already exists in AD
if (Get-ADUser -F {SamAccountName -eq $Username})
{
#If user does exist, output a warning message
Write-Warning "A user account $Username has already exist in Active Directory."
}
else
{
#If a user does not exist then create a new user account
#Account will be created in the OU listed in the $OU variable in the CSV file; don’t forget to change the domain name in the"-UserPrincipalName" variable
New-ADUser `
-SamAccountName $Username `
-UserPrincipalName $UserPrincipalName `
-Name "$Firstname $Lastname" `
-GivenName $Firstname `
-Surname $Lastname `
-Enabled $True `
-ChangePasswordAtLogon $True `
-DisplayName "$Lastname, $Firstname" `
-Department $Department `
-DistinguishedName $DistinguishedName `
-SID $sid `
-Path $OU `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force)
}
}
You won't be able to assign a SID as that's generated by the domain controller based on a RID. If trying to migrate to a new forest then you'll need to perform a proper AD migration. The old SIDs will be copied onto the migrated users' SID history attributes to allow permissions based on the old SID to still work.
If you simply want to upgrade to a newer version of AD then you're better off joining a newer domain controller to your existing Active Directory forest / domain. The forest functional level mush be 2003 or higher.
As a side note, I'd recommend then getting rid of the 2003 servers as soon as possible as these are no longer supported by Microsoft.

Powershell create new user copy group membership

I'm trying to successfully execute a script which has cmdlets from a win8.1 machine to a 2003 domain controller. I set up ADWS on the 2003 domain controller and can now use cmdlets on it remotely from my win8.1 machine.
What I'm trying to do with this script is to get the group membership details from a pre-existing user ($UserOne), create a new user ($UserTwo), create a foreach loop which copies the group membership details from the pre-existing ($UserOne) user to the new user ($UserTwo) that was created.
Currently the script works up until the point of creating the new user ($UserTwo), however the foreach loop afterwards doesn't seem to execute.
Would any of you know what the issue with my code is? I suspect it's how I've entered the foreach loop in directly after creating a user. I also tried creating a new session using Invoke-Command after creating the new user in order to copy the group membership, however none of my cmdlets would work in the scriptblock since the remote server is Windows 2003.
Help would be greatly appreciated, I'm still very much new to Powershell. My code is as follows:
$serv = "SERVERNAME"
$cred = "admin\admin"
$secureString = convertto-securestring "Password" -asplaintext -force
$FirstUser = "NameOne"
$SecondUser = "NameTwo"
$UserOne = Get-ADUser -Identity $FirstUser -Properties memberOf -Server $serv
New-ADUser -SAMAccountName $SecondUser -UserPrincipalName "blah#blah.com" -DisplayName $SecondUser -Enabled $true -AccountPassword $secureString -Credential $cred -Server $serv -PassThru
$UserTwo = Get-ADUser -Identity $SecondUser -Properties memberOf -Server $serv
foreach($group in $UserOne.memberof)
{
Add-ADGroupMember -Identity $group -Member $SecondUser -Server $serv
write-output $group
}
Turned out it happened to be a permissions issue, it's just that I wasn't getting any feedback via error messages!
Thanks for the posts though guys.
I see a number of issues here..
$serv = "SERVERNAME"
$cred = "admin\admin"
$secureString = convertto-securestring "Password" -asplaintext -force
$FirstUser = "NameOne"
$SecondUser = "NameTwo"
$UserOne = Get-ADUser -Identity $FirstUser -Properties memberOf -Server $serv
New-ADUser -SAMAccountName $SecondUser -UserPrincipalName "blah#blah.com"`
-DisplayName $SecondUser -Enabled $true -AccountPassword $secureString`
-Credential $cred -Server $serv -PassThru
Why add the -pasthru if your not going to use it? This will just needlessly output data to the screen (unless that is what you want).
If you assign the resulting value of the command to null, again you will get less screen junk.
Try
$null = New-ADUser -SAMAccountName $SecondUser -UserPrincipalName "blah#blah.com" -DisplayName $SecondUser -Enabled $true -AccountPassword $secureString -Credential $cred -Server $serv
and
$UserTwo = Get-ADUser -Identity $SecondUser -Properties memberOf -Server $serv
Why are you doing this? You already know the user won't be a member of any groups (except default USERS) since you just created the account. Then you never use the value $usertwo in the script.
write-host "Adding user $SecondUser to AD groups."
foreach($group in $UserOne.memberof)
{
Add-ADGroupMember -Identity $group -Member $SecondUser -Server $serv
write-output $group
}

Bulk import AD users from csv using powershell without user intervention

I'm trying to import users from a csv file using ADUser powershell cmdlet and here's the script
Import-Module ActiveDirectory
$csvcontent = Import-CSV -Path "C:\Program Files (x86)\AWS Tools\PowerShell\AWSPowerShell\import_create_ad_users_2a.csv"
foreach ($user in $csvcontent) {
$samAccountName = $user.GivenName.substring(0,1).ToLower()+$user.LastName.ToLower()
$userPrincinpal = $samAccountName+"#mmc.local"
New-ADUser
-AccountPassword (ConvertTo-SecureString -AsPlainText $user.Password -force)`
-ChangePasswordAtLogon $false`
-Company “mmc LLP.”`
-DisplayName ($user.GivenName+""+$user.Lastname)`
-userprincipalname $userPrincinpal`
-SamAccountName $samAccountName` -Name ($user.GivenName+""+$user.Lastname)`
-Path “CN=Users,DC=mmc,DC=local”`
-state $user.County`
-givenname $user.GivenName`
-surname $user.Lastname`
-description ($user.Description)`
-Enabled $true`
Add-ADGroupMember "mmc_Users" $samAccountName;
}
But when I run the command in powershell, I get a prompt as listed below and I would like to import all the users listed in the csv file without any user intervention.
cmdlet New-ADUser at command pipeline position 1
Supply values for the following parameters:
Name:
Please review the script and let me know how to fix this.
FYI - Powershell beginner
Thanks,
Karthik
Backticks are generally worth avoiding. They work by escaping the next character, which on the end of a line is the newline character so it allows the command to continue. However its too easy to end up with a space after the backtick that you can't see, which then ends up getting escaped and not the newline. That doesn't seem to be the case above, but as TessellatingHeckler pointed out you were missing one after New-ADUser.
A better solution (to keep the code from going too far horizontal) would be to use splatting like this:
Import-Module ActiveDirectory
$csvcontent = Import-CSV -Path "C:\Program Files (x86)\AWS Tools\PowerShell\AWSPowerShell\import_create_ad_users_2a.csv"
foreach ($user in $csvcontent) {
$samAccountName = $user.GivenName.substring(0,1).ToLower()+$user.LastName.ToLower()
$userPrincinpal = $samAccountName+"#mmc.local"
$NewUserParams = #{
AccountPassword = (ConvertTo-SecureString -AsPlainText $user.Password -Force)
ChangePasswordAtLogon = $false
Company = “mmc LLP.”
DisplayName = ($user.GivenName+""+$user.Lastname)
userprincipalname = $userPrincinpal
SamAccountName = $samAccountName
Name = ($user.GivenName+""+$user.Lastname)
Path = “CN=Users,DC=mmc,DC=local”
state = $user.County
givenname = $user.GivenName
surname = $user.Lastname
description = ($user.Description)
Enabled = $true
}
New-ADUser #NewUserParams
Add-ADGroupMember "mmc_Users" $samAccountName
}
This works by creating a hashtable #{ } with each of the parameters in it that you want to set and then sending that hashtable to the cmdlet with the special # character.
Few things that I think look wrong, but lets try to fix it. Changing the name is best done after the user has been created. This will limit the script from failing.
Backticks can be used for someone who is just learning how to code and it allows you to see the code in a more logical way. You could also create an array as suggested, but that can get complicated and not give correct results.
Lets break down the script below. First we call ActiveDirectory Module, then we call the CSV. That part works great.
We can test it by using the following code that was provided:
Import-Module ActiveDirectory
$csvcontent = Import-CSV -Path "C:\Program Files (x86)\AWS Tools\PowerShell\AWSPowerShell\import_create_ad_users_2a.csv"
$csvcontent | Out-GridView
This should display something with your raw data, but an example is:
GivenName | LastName | Password | Description | Country
Karthik | CSVScript | 79HKJ#p8 | UserTest | Norway
Once we can confirm that the columns are correct. We can run the script
When you use the Import-CSV it imports the columns that you defined as a pipline($_.GivenName). This allows us not to create another variable. Calling it from the Import-CSV cmdlet will only use the fields that you provide in the raw data(CSV file).
You can save the following as a PS_Script called something like NewUser_CSV.ps1
The script below will only look at what you put into the columns. If something is not correct, that means the data in the CSV is wrong. This is a basic add AD users using a CSV file with no major error handling.
We will use the Transcript cmdlet to gather a log
#RUN AS ADMIN!
Start-Transcript -Path "C:\Program Files (x86)\AWS Tools\PowerShell\AWSPowerShell\import_create_ad_users_2a.log"
Import-Module ActiveDirectory
$csvcontent = Import-CSV -Path "C:\Program Files (x86)\AWS Tools\PowerShell\AWSPowerShell\import_create_ad_users_2a.csv"
$csvcontent | ForEach-Object {
$sam = $_.GivenName.substring(0,1)+$_.Lastname
$setpass = ConvertTo-SecureString -AsPlainText $_.Password -force
Try
{
New-ADUser $samAccountName `
-Path "CN=_s,DC=mmc,DC=local" `
-GivenName $_.GivenName `
-Surname $_.LastName `
-UserPrincipalName ($samAccountName + "#mmc.local")`
-DisplayName ($_.GivenName + " " + $_.LastName) `
-Description $_.Description `
-Enabled $TRUE `
-Company "mmc LLP." `
-State $_.Country `
-AccountPassword $setpass `
-ChangePasswordAtLogon $False `
-AccountPassword $setpass
$newdn = (Get-ADUser $samAccountName).DistinguishedName
Rename-ADObject -Identity $newdn -NewName ($_.GivenName + " " + $_.LastName)
}
Catch
{
Write-Host "[ERROR]`t Oops, something went wrong: $($_.Exception.Message)`r`n"
}
}
Stop-Transcript
I really hope this helps you out and gets the task done for you. Good luck with learning PowerShell.

Error when running powershell script to import users from csv using Import-Csv and New-QADUser into Active Directory

My script looks like this:
$Users = Import-Csv "C:\users.csv"
foreach ($User in $Users)
{
New-QADUser -Name $User.Name `
-ParentContainer $User.OU `
-FirstName $User.FirstName `
-LastName $User.LastName `
-UserPassword $User.userPassword `
-SamAccountName $User.sAMAccountName `
}
When I run it I get the following error:
DefaultNamingContext Type
-------------------- ----
DC=example,DC=domain,DC=org ActiveDirectory
The server is unwilling to process the request. (Exception from HRESULT: 0x80072035)
At :line:5 char:12
+ New-QADUser <<<< -Name $User.Name `
My CSV looks like this:
Name,FirstName,LastName,sAMAccountName,UserPassword,OU
Joe Bob,Joe,Bob,jb241277,4gh60b4,"OU=2010,OU=Sub,OU=Users,OU=MAIN,DC=example,DC=domain,DC=org"
Not sure what is going on, any help would be appreciated. This is a child domain in a forest on Win2K8 Ent.
It is possible that this action is being attempted against a Global Catalog for some reason. Your code works fine for me, but I get the error when I attempt to do it against a GC, which is expected. The connect-QADService cmdlet specifies where you want to connect. If you're setting this before your new-qaduser code, double-check to make sure that "-UseGlobalCatalog" is not in there.
As a troubleshooting step you can try to specify a specific Domain Controller to see if that changes your error.
$Users = Import-Csv "C:\users.csv"
foreach ($User in $Users)
{
New-QADUser -Name $User.Name `
-ParentContainer $User.OU `
-FirstName $User.FirstName `
-LastName $User.LastName `
-UserPassword $User.userPassword `
-SamAccountName $User.sAMAccountName `
-Service $DomainController `
}
That will tell it to perform the action against a specific domain controller and not a Global Catalog.