Powershell create new user copy group membership - powershell

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
}

Related

Add a new O365 users to AD group using 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.

office 365 bulk add shared mailbox members via powershell

I have already created the shared mailbox in o365.
Now I need to bulk import members to these shared mailboxes.
How to do it in powershell ?
I want to do something like this
$users = import-csv -Path "C:\path\members.csv" -Delimiter ";"
Foreach ($user in $users){
Add-mailboxpermission -identity "name of the shared mail box" -user $user -accessrights FullAccess
}
any thoughts ?
Connecting to Office365 would be a good first step:
$AdminUsername = "admin#your-domain.onmicrosoft.com"
$AdminPassword = "YourPassword"
$AdminSecurePassword = ConvertTo-SecureString -String "$AdminPassword" -AsPlainText -Force
$AdminCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $AdminUsername,$AdminSecurePassword
$ExchangeSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://outlook.office365.com/powershell-liveid/" -Credential $Admincredential -Authentication "Basic" -AllowRedirection
Import-PSSession $ExchangeSession
After you have a session you can play with the functions and add some logic:
$access = "FullAccess"
$mailbox = Get-Mailbox -Identity YourMailbox
$identity = $mailbox.UserPrincipalName
$permissions = Get-MailboxPermission -identity $identity
$users = Import-Csv -Path "C:\path\members.csv" -Delimiter ";"
foreach($user in $users){
try{
$setPermissions = Add-MailboxPermission -Identity $identity -User $user -AccessRights $access
Write-Host "Successfully added permissions for $user" -ForegroundColor Green
}catch{
Write-Host "Failed to add permissions for $user" -ForegroundColor Red
}
}
Remember to add users based on UserPrincipalName

Adding newly created users to pre-existing groups

This script currently creates new users after importing data from a CSV file
Import-Module ActiveDirectory
Import-Csv "C:\testcsv.csv" | ForEach-Object {
$userPrincinpal = $_."samAccountName" + "#NWTC.local"
New-ADUser -Name $_.Name `
-Path $_."ParentOU" `
-SamAccountName $_."samAccountName" `
-UserPrincipalName $userPrincinpal `
-AccountPassword (ConvertTo-SecureString "Password1" -AsPlainText -Force) `
-ChangePasswordAtLogon $false `
-Enabled $true
}
This is the csv file I am importing from:
Name,samAccountName,ParentOU,Group
Test Test1,TTest1,"OU=Business,DC=NWTC,DC=local",TestGroup
After a user is created, I want to add them to an already exisiting group. There will be different groups I want different users to be added to, but only 1 group per person.
I've been playing around with Add-AdGroupMember, but I'm not sure how to proceed. Something like this: Add-ADGroupMember -Members $_.Members. This is the first time I'm working with CSVs, so I'm in new territory
New-ADuser does not support this functionality so you will have to do that yourself after the fact. What you could do is have New-ADUser spit out the AD user object it creates and use that with Add-ADGroupMember.
$newUserProperties = #{
Name = $_.Name
Path = $_."ParentOU"
SamAccountName = $_."samAccountName"
UserPrincipalName = $_."samAccountName" + "#NWTC.local"
AccountPassword = (ConvertTo-SecureString "Password1" -AsPlainText -Force)
ChangePasswordAtLogon = $false
Enabled = $true
}
try{
$newADUser = New-ADUser #newUserProperties -PassThru
Add-ADGroupMember -Identity $_.Group -Members $newADUser.SamAccountName
} catch {
Write-Warning "Could not create $($newUserProperties.samaccountname)"
}
The error handling is crude but should exist in some form to account for failures in the source data or misconceptions of existing users. Basically just getting $newADUser and using it for Add-ADGroupMember
We use splatting of the parameters here. That way you don't have to worry about having nice formatted code by using backticks.
Add the Add-ADGroupMember in the ForEach-Object after the new user is created :
Import-Module ActiveDirectory
Import-Csv "C:\testcsv.csv" | ForEach-Object {
$userPrincinpal = $_."samAccountName" + "#NWTC.local"
New-ADUser -Name $_.Name `
-Path $_."ParentOU" `
-SamAccountName $_."samAccountName" `
-UserPrincipalName $userPrincinpal `
-AccountPassword (ConvertTo-SecureString "Password1" -AsPlainText -Force) `
-ChangePasswordAtLogon $false `
-Enabled $true
Add-ADGroupMember -Identity 'AD_GROUP_WHERE_YOU_ADD_MEMBERS' -Members $_.samAccountName
}

PowerShell Script Runs Locally, but Errors on Remote

I have a PowerShell script I am writing to create new users in our domain, as well as email address. The script works when I run it directly on Exchange. However, if I try to do it from my local PC either with Enter-PSSession or Invoke-Command I get the error:
The term 'Get-ADUser' is not recognized as the name of a cmdlet...
Running that same command from the local machine does work. And running that command on the remote machine works, just not if I run the script remotely.
Here is my script:
$cred = Get-Credential
$first_name = Read-Host -Prompt "What is the new user's first name?"
$last_name = Read-Host -Prompt "What is the new user's last name?"
$copy_from = Read-Host -Prompt "Copy from other user (leave blank if not)?"
$password = Read-Host -Prompt "New user's password?"
$ss_password = ConvertTo-SecureString -String $password -AsPlainText -Force
$new_user_name = $last_name.Substring(0,3) + $first_name.Substring(0,2)
$new_user_name = $new_user_name.ToLower()
Write-Host "Creating user $new_user_name..." -ForegroundColor Green
if ([string]::IsNullOrEmpty($copy_from))
{
Write-Host "Setting up new user (not copying...)" -ForegroundColor Yellow
New-ADUser -Name "$first_name $last_name" -AccountPassword $ss_password -SamAccountName $new_user_name -PassThru | Enable-ADAccount
}
else
{
$copy_from_user = Get-ADUser -Identity $copy_from
Write-Host "Copying user from: " $copy_from_user.Name -ForegroundColor Yellow
$ou = $copy_from_user.DistinguishedName -replace '^cn=.+?(?<!\\),'
New-ADUser -Name "$first_name $last_name" -AccountPassword $ss_password -Path $ou -SamAccountName $new_user_name -PassThru | Enable-ADAccount
$new_user = Get-ADUser -Identity $new_user_name
#Time to copy their group memberships
Get-ADUser -Identity $copy_from -Properties memberof | Select-Object -ExpandProperty memberof | Add-ADGroupMember -Members $new_user_name
}
$pn = $new_user_name + "#INDY"
Set-ADUser -Identity $new_user_name -GivenName $first_name -Surname $last_name -UserPrincipalName $pn
#Now create email
$email_select = Read-Host -Prompt "Select email domain (1. Woodmizer; 2. Lastec; 3. Brightstone)"
if ($email_select -eq 2)
{
$domain = "#lastec.com"
}
elseif ($email_select -eq 3)
{
$domain = "#brightstoneabrasives.com"
}
else
{
$domain = "#woodmizer.com"
}
$email_address1 = $first_name.Substring(0,1) + $last_name + $domain
Write-Host "Creating mailbox $email_address1..." -ForegroundColor Green
Enable-Mailbox -Identity $new_user_name -Database "Mailbox Database 1188513962"
Start-Sleep -s 10
Get-Mailbox -Identity $new_user_name | Set-Mailbox -EmailAddresses #{add="$email_address1"} -EMailAddressPolicyEnabled $false
Get-Mailbox -Identity $new_user_name | Set-Mailbox -PrimarySmtpAddress $email_address1 -EmailAddressPolicyEnabled $false
Write-Host "Finished." -ForegroundColor Green
If you want this script to run on machines that don't have the Active Directory module, you can simply add this to the top of your script to import the cmdlets via session..
$cred = Get-Credential "DOMAIN\adminuser"
$ADsession = New-PSSession -ComputerName DOMAINCONTROLLERNAME -Credential $cred
Import-Module -PSSession $ADsession ActiveDirectory
I also notice you're trying to run Exchange cmdlets..
$exchSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "http://EXCHANGESERVER/PowerShell/" -Authentication Kerberos
Import-PSSession $exchSession
It looks like the ActiveDirectory module is not installed on that machine, you can install the MSFT RSAT tools to get it.
Try the following, It works!! {I tried after giving the Authentication type}
$pass = ConvertTo-SecureString -AsPlainText 'PASSWORD' -Force
$MySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList 'USERNAME',$pass
$s=New-PSSession SERVERNAME -Credential $MySecureCreds -Authentication Credssp
Invoke-Command -Session $s -scriptblock {
Get-CsUser User
}

Set-ADUser with PowerShell's ActiveDirectory Module: changing the user's OU

I was wondering if it was possible to change the OU (organizational unit) of a user in ActiveDirectory using PowerShell. I have a script that should update many of the fields. I am using the Set-ADUser command to update, but I can't seem to find a flag that will allow me to update the OU. Below is the the Set-ADUser command I am using currently. The variables are set earlier in the script and shouldn't be relevant to the question.
set-ADUser -identity $samName -GivenName $firstName -Surname $lastName -Department $department -Description $description -Manager $manager -AccountExpirationDate $acctExp -Organization $org
I also have a script that creates users. That script allows me to set the OU. That leads me to believe that I could change the OU after creation. Below is the command I use to create the user. Again, the variables are set earlier in the script.
New-ADUser -Name $dName -SamAccountName $sam -GivenName $firstName -Surname $lastName -Path $OU -AccountPassword $passwd -ChangePasswordAtLogon $true -Department $department -Description $description -Manager $manager -Organization $org
If there is a flag for the Set-ADUser command that would be great, otherwise, any help is appreciated. Thanks.
You can use the move-adobject:
Move-ADObject 'CN=myuser,CN=Users,DC=mydomain,DC=com' -TargetPath 'OU=mynewou,DC=mydomain,DC=com'
or
Get-ADUser $name| Move-ADObject -TargetPath 'OU=mynewou,DC=mydomain,DC=com'