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...
Related
got a powershell script that has to use First and Last Name from CSV to do some password settings.
Import-Module ActiveDirectory
$Users = Import-Csv -Path "C:\users-to-reset.csv"
ForEach ($User in $Users) {
$LastName = $User.LastName
$FirstName = $User.FirstName
$User = Get-ADUser -Filter 'surname -eq $LastName -and givenName -eq $FirstName'
Set-ADUser -Identity $User -PasswordNeverExpires:$false
Set-ADUser -Identity $User -CannotChangePassword:$false
}
What am I doing wrong?
In the past, I have just used Set-ADAccountPassword and Set-ADUser to do this.
Set-ADAccountPassword -Identity $user -Reset -NewPassword $pw
I just used the -ChangePasswordAtLogon and -PasswordNeverExpires flags like this:
Set-ADUser -ChangePasswordAtLogon $true -Identity $($user.samAccountname) -Confirm:$false
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:
"/ \ [ ] : ; | = , + * ? < >
OK guys, i've edited my script for user creation and now it's almost perfect except one thing that i cant figure out
how to make the hash table read the Variable for the "$GivenName $Surname"
and make the Name of the user, because now it's creating users without the Name parameter
or I need to creat a header for $GivenName and $surname in the csv file
cls
#get the csv file
$filepath = import-csv "C:\users.csv"
#set the variable for the uers
$newusers = $filepath
#set Passwords for new users
$securepassword = ConvertTo-SecureString "BlahBlah" -AsPlainText -Force
foreach ($user in $newusers) {
#get user information
$User_Creation_Settings = #{
Name = "$GivenName $Surnam"
GivenName = $user.GivenName
Surname = $user.Surnam
UserPrincipalName = $user.UserPrincipalName
SamAccountName = $user.SamAccountName
Path = $user.Path
ScriptPath = $user.ScriptPath
ChangePasswordAtLogon = $false
Department = $user.Department
DisplayName = $user.DisplayName
Description = $user.Description
Title = $user.'Job Title'
AccountPassword = $securepassword
Enabled = $true
}
New-ADUser #User_Creation_Settings
#Get Groups information
$group1 = $user.Group1
$group2 = $user.Group2
$group3 = $user.Group3
$group4 = $user.Group4
#Add the users in to Groups
Add-ADPrincipalGroupMembership -Identity $user.SamAccountName -MemberOf $user.group1
Add-ADPrincipalGroupMembership -Identity $user.SamAccountName -MemberOf $user.group2
Add-ADPrincipalGroupMembership -Identity $user.SamAccountName -MemberOf $user.group3
Add-ADPrincipalGroupMembership -Identity $user.SamAccountName -MemberOf $user.group4
Write-Host "`n"
Write-Host "The account for $GivenName $Surnam created in $OuPath successfully "
}
pause
so i've figured it out and i'm posting the solution
for the solution of the issue that i've described, i had to make Powershell think that "First name" and "Last Name" are one whole variable which is split in the middle, that's why i've used the parentheses with a "$" sign before them, Power Shell will think that you are using the $user from the loop, and will "Popup" the headers from the CSV file.
here is the whole script
cls
#get the csv file
$filepath = import-csv "C:\users.csv"
#set the variable for the uers
$newusers = $filepath
#set Passwords for new users
$securepassword = "BlahBlah"
foreach ($user in $newusers) {
#get user information
$User_Creation_Settings = #{
Name = "$($user.'First Name') $($user.Lastname)"
GivenName = $user.'First Name'
Surname = $user.Lastname
UserPrincipalName = $user.UserPrincipalName
SamAccountName = $user.SamAccountName
Path = $user.Path
ScriptPath = $user.ScriptPath
ChangePasswordAtLogon = $false
Department = $user.Department
DisplayName = $user.DisplayName
Description = $user.Description
Title = $user.'Job Title'
AccountPassword = ConvertTo-SecureString $securepassword -AsPlainText -Force
Enabled = $true
}
New-ADUser #User_Creation_Settings
#Get Groups information
$group1 = $user.Group1
$group2 = $user.Group2
$group3 = $user.Group3
$group4 = $user.Group4
#Add the users in to Groups
Add-ADPrincipalGroupMembership -Identity $user.SamAccountName -MemberOf $user.group1
Add-ADPrincipalGroupMembership -Identity $user.SamAccountName -MemberOf $user.group2
add-ADPrincipalGroupMembership -Identity $user.SamAccountName -MemberOf $user.group3
Add-ADPrincipalGroupMembership -Identity $user.SamAccountName -MemberOf $user.group4
Write-Host "`n"
Write-Host "The account for $($user.'First Name') $($user.Lastname) created in $($user.Path) successfully "
}
pause
So in that case:"$($user.'First Name') $($user.Lastname)"
powershell will behave like you entered one whole variable.
The short answer is that both are fine, because both are valid ways of creating hashtables in PowerShell. For more information, check out about_Splatting.
Personally, I use single quotes around strings across the board and leave variables alone so that PowerShell doesn't think I'm trying to call a function. As mentioned, this is not required here and frankly can make your code look messier than it needs to be.
A few things to watch out for:
Name = $firstname $lastname # invalid because of the space
'class' = win32_logicaldisk # invalid: PowerShell will look for the function win32_logicaldisk
GivenName = '$firstname' # because single quotes are used, PowerShell will not replace the variable; GivenName will literally be $firstname
Both the above splatting are fine and the reason for the color change is in the first Hashtable "$firstname $lastname" is a string as you have mentioned it in quotes, Editor represents Strings in Brown color and variables in black color.
In the second Hashtable you used single quotes for all the Keys and values and again those are understood and represented as Strings by the editor.
No harm either way.
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 }
I have added about 1700+ users to Active Directory using a CSV file. I accidentially tried to use \n to seperate some attributes between them. But it did not escape new line. Instead typed it as is.
$Users = Import-Csv -Path "C:\UsersList.csv"
foreach ($User in $Users)
{
$Name = $User.Name
$AccountPassword = $User.AccountPassword
$City = $User.City
$Company = $User.Company
$GivenName = $User.GivenName
$SamAccountName = $User.SamAccountName
$Surname = $User.Surname
$UserPrincipalName = $User.UPN
$Displayname = $User.Name
$Description = "Desc1: " + $User.Desc1 + "\nDesc2: " + $User.Desc2 + "\nDesc3: " + $User.Desc3 + "\nDesc4: " + $User.Desc4
$Path = $User.Path
New-ADUser -Name "$Name" -DisplayName "$Displayname" -SamAccountName "$SamAccountName" -UserPrincipalName "$UserPrincipalName" -GivenName "$GivenName" -Surname "$Surname" -Description "$Description" -AccountPassword (ConvertTo-SecureString $AccountPassword -AsPlainText -Force) -Enabled $true -Path "$Path" -ChangePasswordAtLogon $true
}
Now I want to change those "\n" in Descriptions for all users.
I can get users using
Get-ADUser -Filter {description -like "\n"}
I need a command that using .Replace("\n"," - "). I do not know how to use it to reach my goal.
You could do a Foreach-Object loop to find all the Descriptions with your filter and pipe that to Set-Aduser.
$Description = "-Desc1: " + $User.Desc1 + "-Desc2: " + $User.Desc2 + "-Desc3: " + $User.Desc3 + "-Desc4: " + $User.Desc4
foreach ($User in (Get-ADUser -Filter {description -like "*\n*"}) )
{
$User.SamAccountName | Set-ADUser -Description $Description
}
To update the users from the CSV
foreach ($User in $users )
{
$User.SamAccountName | Set-ADUser -Description $user.Description
}
Use Set-ADUser:
Get-ADUser -Filter {description -like "*\n*"} -Properties Description |
ForEach-Object {
$newDescription = $_.Description.Replace('\n', ' - ')
Set-ADUser -Identity $_ -Description $newDescription
}
Note that with the -like operator you need to add wildcards before and after the \n, otherwise you'd only get users where the description consists of just \n and nothing else. You also need to tell Get-ADUser to include the property Description as it isn't among the properties returned by default.