Hello,
I’ve been going through multiple OUs in AD, exporting the users to CSV, then I’ve been placing those users in a security group in AD. Here is what I’m currently using to export:
Get-ADUser -Filter * -SearchBase "OU=Test,OU=All_Users,DC=Test,DC=com" | Select-Object SamAccountName | Export-Csv 'C:\PS_Scripts\TestUsers.csv'
Then, once I combine all the CSV files so they contain multiple users from multiple OUs I run this script (Thanks to Matt McNabb):
Import-Module ActiveDirectory
$ADGroup = "SCCM_AppCat_HR"
$Members = Get-ADGroupMember -Identity $ADGroup
$Users = Import-Csv "C:\PS_Scripts\TestUsers.csv"
$Failures = @()
$Added = @()
$Existing = @()
Foreach ($User in $Users)
{
if ($User.SAMAccountName -in $Members.SAMAccountName)
{
$Existing += $User
}
else
{
try {
Add-ADGroupMember -Identity $ADGroup -Members $User.SAMAccountName
$Added += $User
}
catch { $Failures += $User }
}
}
$FailLog = 'C:\PS_Scripts\FailLog.csv'
$AddedLog = 'C:\PS_Scripts\AddedLog.csv'
$ExistingLog = 'C:\PS_Scripts\ExistingLog.csv'
$ErrorLog = 'C:\PS_Scripts\ErrorLog.csv'
if ($Failures)
{
$Failures | Export-Csv $FailLog -NoTypeInformation
$Error | Export-Csv $ErrorLog -NoTypeInformation
}
if ($Added)
{
$Added | Export-Csv $AddedLog -NoTypeInformation
}
if ($Existing)
{
$Existing | Export-Csv $ExistingLog -NoTypeInformation
}
I’m fairly new to PowerShell and although this has helped me tremendously, I thought I would try to improve upon this by searching multiple OUs and attempting to export all users from multiple OUs at the same time and pipe to 1 CSV file.
So, I tried this:
Get-ADOrganizationalUnit -Filter 'Name -like "*ACD*"' | Format-List -Property Name, DistinguishedName
This gives me a list of 20 different OUs and their ‘path’ if that is the correct term.
Then I tried this:
$OU = Get-ADOrganizationalUnit -Filter 'Name -like "*ACD*"' Get-ADUser -Filter * -SearchBase "$OU" | Select-Object SamAccountName | Export-csv 'C:\PS_Scripts\TestCSR.csv'
Of course, this kicks back an error At line: 2 Char: 1
Get-ADUser : The object name has bad syntax
At line:2 char:1
+ Get-ADUser -Filter * -SearchBase "$OU" | Select-Object SamAccountName | Export-c ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-ADUser], ADException
+ FullyQualifiedErrorId : The object name has bad syntax,Microsoft.ActiveDirectory.Management.Commands.GetADUser
Any help that can be given is much appreciated! Thank you!