Update AD User From CSV Based on EmployeeID Attribute - powershell

I am attempting to update AD users based on their employeeID number. It is a reliable key field for our organization.
Every user in this case was created with an employeeID attribute. I am using the same csv for the initial creation (New-ADuser) of users (only setting less attributes), as I am the update (Set-ADUser) of users.
Most of this is pretty straightforward and sourced mostly from here. I successfully import my csv, and can print my variables. My resulting message indicates that when I execute my If/Else, that the "User with ID is not found, or more than one is found", both of which aren't true. I believe my issue to be in this line:
$UserID = Get-ADUser employeeID=$EmployeeId
Here is the entirety of the script. What am I doing wrong here?
# Import AD Module
Import-Module ActiveDirectory
# Import CSV into variable $userscsv
$ADUsers = Import-Csv -Path C:\Scripting\CSVs\UpdateADUsers.csv
foreach ($User in $ADUsers)
{
#Retrieve info from CSV
$Title = $User.Title
$Department = $User.department
$Office = $User.Office
$EmployeeId = $User.EmployeeId
$Manager = $User.manager
$Company = $User.Orglevel02
#get user DN
$UserDN = Get-ADUser -LDAPFilter "EmployeeId=$EmployeeId"
If ($UserDN.Count -eq 1)
{
# Use the Set-ADUser cmdlet to assign the new attribute values.
Set-ADUser -Identity $UserDN -Replace #{title=$Title;physicalDeliveryOfficeName=$Office;manager=$Manager}
}
Else {"User with ID $ID either not found, or more than one user found."}
}

$UserDN = Get-ADUser -LDAPFilter "(EmployeeId=*$EmployeeId*)"

Marks answer contains the major correction needed in your filter.
Each of your search criteria at a minimum must be in a set of parenthesis. Like in the example given on ldapexplorer.com
Equality: (attribute=abc) , e.g. (&(objectclass=user)(displayName=Foeckeler)
Your current example has bad syntax since it is missing braces but does not constitute a failure of the cmdlet, so, nothing ($null) is returned. You have a response to this in comments
I initially tried with that syntax, minus the *wildcard. Results still the same, implying User with ID 1234567 either not found, or more than one user found.
What if you hardcode an employeeID in there for testing?
Get-ADUser -LDAPFilter "(EmployeeId=12345)"
If that works then that tells me something is wrong with your source file. Leading or trailing whitespace or perhaps hidden characters? Either way look at the source to be sure and if you have to use .Trim() for testing as you might not initially see the problem.
Get-ADUser -LDAPFilter "(EmployeeId=$($EmployeeID.Trim()))"

Related

PowerShell: If statements and using blank cells in Import-CSV

I am having difficulty using an if statement with blank cells in my CSV file. I'm attempting to write an onboarding script and have it pull info from an xlsx HR fills out (IT copies needed rows into CSV that is used in script). In order to get the OU path, I use the department names. However, some users have a sub-department and others do not, these fields are left blank in the xlsx that HR sends. I have it working by inputting a N/A in those fields however if another tech doesn't know to do that in the CSV file the script will fail. So I would like to get it working with the blank fields.
This is what im trying when not using the N/A in the CSV field
foreach ($obj in $onboardcsv){
$dep = "$($obj.department)"
$sdep = "$($obj.subDepartment)"
if ($null -eq $obj.subDepartment){
$ou = Get-ADOrganizationalUnit -Filter {name -like $dep} -SearchBase "OU=User,OU=OU,DC=DOMAIN,DC=com"
}
else{
$ou = Get-ADOrganizationalUnit -Filter {name -like $sdep} -SearchBase "OU=User,OU=OU,DC=DOMAIN,DC=com"
}
Any help would be appreciated!
To rephrase your question, you just want to search where SubDepartment isn't empty?
Without modifying too much of your code, you can make use of the static method of ::IsNullOrWhiteSpace() provided in the [string] class to evaluate against the emptiness:
Using -Not reverses the result of [string]::IsNullOrWhiteSpace($obj.subDepartment).
foreach ($obj in $onboardcsv)
{
$department = if (-not [string]::IsNullOrWhiteSpace($obj.subDepartment)) {
$obj.subDepartment
}
else {
$obj.department
}
Get-ADOrganizationalUnit -Filter "Name -like '$department'" -SearchBase "OU=User,OU=OU,DC=DOMAIN,DC=com"
}
So, testing against the subDepartment first, if $obj.subDepartment is not null, assign it to $department. This will allow the use of just one variable for both properties, and no code copying necessary.
Thanks to #Santiago for a sanity check.
Something like this would work.
$ou = "searching by sub department"
$department = if (!($user.subDepartment)) {
#subdepartment is blank
#searching by department
$ou = "searching by department"
}
$ou

Powershell Script to query Active Directory

I am trying to query all users in multiple OUs of the same name. Get the SamAccountName attribute and then check for a file at a specific location with that name.
Here is what I have so far:
$ous = Get-ADOrganizationalUnit -Filter "Name -eq 'Admin-User-Accounts'"
$ous | ForEach-Object {
$AccountName = Get-ADUser -Filter * -SearchBase $_.DistinguishedName |
Select SamAccountName
Test-Path "\\domain.net\SYSVOL\domain.net\IA\$AccountName.pdf"
}
If a file is not found. I want to add the user to a group, however here is the kicker. The account has to be added to the non-compliance group for the organization that the account belongs to.
I.E an admin account found under:
OU=Admin-User-Accounts,OU=Administration,OU=ORG1,OU=ORGS,DC=domain,DC=net
would be added to the group named 'ORG1 IA - Non-Compliant Users' located under:
OU=Groups,OU=ORG1,OU=Information Assurance,OU=ORGS,DC=domain,DC=net
Well your post is a bit confusing, and no way to really validate because I have nothing setup like this.
Yet, querying for users in all OU or the enterprise is a common everyday thing.
However, an OU name, just like any other AD object name, must be unique. So, querying for the same OU name is not a thing, in a single AD forest / domain. If you meant querying every OU for the same username, then alrighty then.
By stepping thru how you are explanation for your use case, that you have laid out.
(though maybe you want to edit your post to make it's more clear, well to me anyway...)
Using pseudo code, then trying to map that out... and with no real way to determine what you mean by several things in your post/sample. So, the below is a rough first example of how I'd do approach this... again this is untested, so, I leave that homework to you.
# query all users in multiple OUs
(Get-ADOrganizationalUnit -Filter *).DistinguishedName |
ForEach{
# Collect all members of the current OU
$AccountNames = Get-ADUser -SearchBase $PSItem -Filter *
# Process each member in the current OU collection
ForEach($AccountName in $AccountNames)
{
"Processing $($AccountName.SamAccoutnName)`n"
# Initialize properties needed for processing
$UserOrg = $AccountName.DistinguishedName.split(",")[1]
$MemberCheckOU = "OU=Admin-User-Accounts,OU=Administration,OU=ORG1,OU=$UserOrg,DC=domain,DC=net"
$NonCompliantOU = "OU=Groups,OU=ORG1,OU=Information Assurance,OU=$UserOrg,DC=domain,DC=net"
# Validate user file existence for the current user
If(-Not (Test-Path -LiteralPath "\\domain.net\SYSVOL\domain.net\IA\$($AccountName.SamAccoutnName).pdf)"))
{
# if no file Process the user groupmebership modification
"Processing $($AccountName.SamAccoutnName)"
# Notify that the file was not found and processing is required
Write-Warning -Message "$($($AccountName.SamAccoutnName).pdf) not found. Process group modify actions"
# If the current user is in the MemberCheckOU, add to the NonCompliantOU
If(Get-ADPrincipalGroupMembership -Identity $($AccountName.SamAccoutnName) | Where-Object -Property DistinguishedName -Match $MemberCheckOU )
{ Add-ADGroupMember -Identity $NonCompliantOU -Members $($AccountName.SamAccoutnName) }
Else
{
# Do something else
}
}
Else
{
# Notify that the file was found and no processing required
Write-Host "$($AccountName.pdf) found. No further actions taken" -ForegroundColor Green }
}
}
It seems that one of the variables is incorrect because PowerShell is giving me the following:
Get-ADPrincipalGroupMembership : Cannot validate argument on parameter 'Identity'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command
again.
Okay, so here is what I have so far based on your post above Postanote:
# query all users in multiple OUs
(Get-ADOrganizationalUnit -Filter "Name -eq 'Admin-User-Accounts'") |
ForEach{
# Collect all members of the current OU
$AccountNames = Get-ADUser -SearchBase $PSItem -Filter *
# Process each member in the current OU collection
ForEach($AccountName in $AccountNames)
{
"Processing $($AccountName.SamAccoutnName)`n"
# Initialize properties needed for processing
$UserOrg = $AccountName.DistinguishedName.split(",")[1]
$MemberCheckOU = "OU=Admin-User-Accounts,OU=Administration,OU=$UserOrg,OU=ORGS,DC=domain,DC=net"
$NonCompliantOU = "OU=Groups,OU=$UserOrg,OU=Information Assurance,OU=ORGS,DC=domain,DC=net"
# Validate user file existence for the current user
If(-Not (Test-Path -LiteralPath "\\domain.net\SYSVOL\domain.net\IA\$($AccountName.SamAccoutnName).pdf)"))
{
# if no file Process the user groupmebership modification
"Processing $($AccountName.SamAccoutnName)"
# Notify that the file was not found and processing is required
Write-Warning -Message "$($($AccountName.SamAccoutnName).pdf) not found. Process group modify actions"
# If the current user is in the MemberCheckOU, add to the NonCompliantOU
If(Get-ADPrincipalGroupMembership -Identity $($AccountName.SamAccoutnName) | Where-Object -Property DistinguishedName -Match $MemberCheckOU )
{ Add-ADGroupMember -Identity "$UserOrg IA - Non-Compliant Users" -Members $($AccountName.SamAccoutnName) }
Else
{
# Do something else
}
}
Else
{
# Notify that the file was found and no processing required
Write-Host "$($AccountName.pdf) found. No further actions taken" -ForegroundColor Green }
}
}
Looking at the original script fragment:
$ous = Get-ADOrganizationalUnit -Filter "Name -eq 'Admin-User-Accounts'"
$ous | ForEach-Object {
$AccountName = Get-ADUser -Filter * -SearchBase $_.DistinguishedName |
Select SamAccountName # note 1
Test-Path "\\domain.net\SYSVOL\domain.net\IA\$AccountName.pdf" # note 2
}
Note 1: Your going to end up with $accountname.accountname holding your value. I think your going to want to expand this instead.
Note2: Powershell may be getting confused and thinking your looking for the variable $accountname.pdf
Instead, try this...
$ous = Get-ADOrganizationalUnit -Filter "Name -eq 'Admin-User-Accounts'"
$ous | ForEach-Object {
$AccountName = $(Get-ADUser -Filter * -SearchBase $_.DistinguishedName).SamAccountName
Test-Path "\\domain.net\SYSVOL\domain.net\IA\$($AccountName).pdf"
}
here, we save the value of just .SamAccountName for the query to the $AccountName, and by adding $($accountname) we make clear the variable we want, and that .pdf is not part of the variable name.
Now, note as well, this doesn't save the results anywhere, it will just flash them to screen.

Replace legacyExchangeDN value in ADSI via PowerShell

I'm looking to correct a small issue in AD where the field I mentioned has a space in the value.
For example:
legacyExchangeDN : /o= First Organization/ou=Exchange Administrative Group (FYDIBOHF23SPDLT)/cn=Recipients/cn=6131a3a42ca946b98cc146345cfd0c2e-Ron E
Should look like this:
legacyExchangeDN : /o=First Organization/ou=Exchange Administrative Group (FYDIBOHF23SPDLT)/cn=Recipients/cn=6131a3a42ca946b98cc146345cfd0c2e-Ron E
This is affecting multiple users and I can manually update the value in the AD Attribute Editor, but I was hoping to be able to automate this.
Here's what I have so far:
#List all users to check existing values
$ADUserList = Get-ADUser -Filter* -Properties * | fl name, EmailAddress, legacyExchangeDN
#Replace value with space with value without space
Set-ADUser reyer -Replace #{legacyExchangeDN="/o= ","/o="}
The second line produces the following error:
Set-ADUser : Multiple values were specified for an attribute that can have only one value
At line:1 char:1
+ Set-ADUser reyer -Replace #{legacyExchangeDN="/o= ","/o="}
It feels like I'm missing something easy here, but I cannot find it. I am testing this with one user. I would like to replace the value against all remaining users in one script once tested. If I could target just the users that match the criteria of having a space in the field that would surely be helpful for either storing it or piping that over.
My final result would look like:
Target users with a space(s) present in the text value of the legacyExchangeDN → /o=
Replace just the /o= with /o= while preserving the remainder of the text value → /o=First Organization/ou=Exchange Administrative Group (FYDIBOHF23SPDLT)/cn=Recipients/cn=6131a3a42ca946b98cc146345cfd0c2e-Ron E
$Users = Get-ADUser -Filter { legacyExchangeDN -like '*/o= *' } -Properties #('name','EmailAddress','legacyExchangeDN')
ForEach ($User in $Users)
{
$Replace = $User.legacyExchangeDN -replace '/o=\s','/o='
Set-ADUser -Identity $User -Replace #{ legacyExchangeDN = $Replace }
Write-Host ('Updated "{0}" ({1}) to "{2}"' -f
#($User.name,$User.EmailAddress,$Replace))
}
This will be faster as well. The mantra is: Filter Left, Format Right. Set-ADUser takes an ADUser object. -Replace takes a [HashTable] where you're assigning a new value to the named property (as it appears in LDAP).
(update: removed pipeline for foreach)
To implement logging, replace Write-Host with:
'Updated "{0}" ({1}) to "{2}"' -f #($User.name,$User.EmailAddress,$Replace) |
Out-File -FilePath "$env:UserProfile\ADChanges.txt" -Append

Powershell comparison with attributes

I'm beginner in powershell and I need your help.
I need to compare the department attribute from the AD containing some text amd replacing by another value.
But it doesn't work. Do I made a mistake below? Cheers
//Find the user and save the user in the variable
$member = get-Aduser -f {GivenName -eq 'Jack'}
//check if the Departement field match with "Dep20 "
if($member.department -eq "Dep20")
{
//Set "Dep21" in department field
$member.Department = 'Dep21';
set-AdUser -f {GivenName -eq $member.givenName} -departement $member.Department;
}
Some issues with your initial script
First
Get-AdUser won't give you the property Department by default.
You could have confirmed this by actually looking at the output of your Get-AdUser statement. You do need to add it to the list of properties explicitely.
get-Aduser -f {GivenName -eq 'Jack'} -Properties Department
Also, you did make a mistake in the Set-AdUser cmdlet. The parameter name you have written, at the time of my answer, is -departement. Instead, you need to set -department.
Finally, Get-AdUser could return multiple users (or none).
Therefore, you need to account for that by checking how many $member were returned or to do a foreach to process none (if 0) or all of them the same.
At least, that part is subjective to what you need but here would be my approach.
$member = get-Aduser -Filter 'GivenName -like "Jack*"' -Properties Department
$member | foreach {
if ($member.Department -eq 'Dep20')
{
$_.Department = 'Dep21'
set-AdUser $_ -Department $_.Department;
}
}
Edit:
I modified my answer to switch the Filter parameter from a scriptblock (as your question) for a string filter as per mklement0 comment.
Because the Filter parameter is actually a string, giving it a script block will create problems on multiple occasions and you are better restrict yourself to the string type for this parameter.
See this for a more detailed explanation on the matter.

Powershell command to update employee number from csv

I am trying to write a powershell script that will update employeeID attribute in AD for each user
The script needs to update employeeID from my CSV file
Sample CSV:
user,employeeID
user1,1234567
At least now you are trying some code which looks like it should work. Your logic is sound. Are you sure your CSV does not contain and blanks? Some simple statements could rule those out.
Import-CSV "C:\Scripts\Users.csv" | ForEach-Object {
$User = $_.UserName
$ID = $_.EmployeeID
If($user -and $ID){
Set-ADUser $User -employeeID $ID
} Else {
Write-Warning "User or employee number is null. Check source."
}
The If statement would fail if either $user or $id was null. If that is not the case and your CSV does contain data maybe you are having an encoding issue.
I think it depends on how you're finding the user in Active Directory... You could try something like this:
# import the users
$myUsers = Import-Csv csvFile.csv
# loop through each user and update their employeeID property
foreach ($user in $myUsers)
{
# the Set-ADUser cmdlet requires a type of System.Hashtable<>,
# so let's create one
$updateRecord = #{"EmployeeID"=$user.EmployeeID}
# Set the user attribute
Set-ADUser -Identity $user -Replace #updateRecord
}
This might do the trick. Did you guys modify the AD Schema? Keep in mind that "EmployeeID" is assuming you have an EmployeeID Attribute on your Active Directory users.
Please let me know if it helps!