The script below is what I'm attempting to use to solve three needs:
- From a csv add users by their "cn" attribute to multiple groups.
- If the user is not already in AD, create the user, using their "cn" attribute.
- The CSV headers are as follows: CommonName, cn, groups
- I can use "Get-ADUser -Filter "cn -eq 'cn'" and AD resolves to the name provided, but when I attempt to use that same command within the script, it states that it's not recognized.
- Here's the script:
# Import the Active Directory module
Import-Module ActiveDirectory
# Define the CSV file path
$csvFilePath = "C:\Path\To\CSV\File.csv"
# Read the CSV file into a variable
$csvData = Import-Csv -Path $csvFilePath
# Iterate over each row in the CSV file
foreach ($row in $csvData) {
# Get the user's CN
$cn = $row["CommonName"]
# Search for the user in Active Directory
$user = Get-ADUser -Filter "CommonName -eq '$cn'"
# If the user exists, add them to the specified groups
if ($user -ne $null) {
$groups = $row["Groups"].Split(",")
foreach ($group in $groups) {
Add-ADGroupMember -Identity $group -Members $user.SamAccountName
}
}
}
The result of my script is:
Get-ADUser : The search filter cannot be recognized
At D:\AddUser2Groups4.ps1:20 char:13
+ $user = Get-ADUser -Filter "CommonName -eq '$cn'"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-ADUser], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8254,Microsoft.ActiveDirectory.Management.Commands.GetADUser
I even changed "CommonName" to "cn" and the results are the same.