move AD group by file - powershell

I'm new with PS and doing my first steps..
I have a file named "C:\temp\used_groups.csv".
The file has email address of AD Groups populated by Powershell script to check which distributions group are being used in 365.
Now I want to be able to move them to different OU.
the file has some AD group's email address as follow:
"RecipientAddress"
"test#test.com"
"test1#test.com"
"test2#test.com"
is it possible to move the AD group only by their email address attribute?
how can I resolve the group's sAMAccountName attribute by their email address attribute?
this is what I tried with no success:
$Groups=import-csv "C:\temp\used_groups.csv"
ForEach ($Group in $Groups){
Get-ADGroup -Filter "mail -like $Group "
# rest of script.. not done yet.
}

I would do something like this:
# put the DistinghuishedName of the destination OU here
$destinationOU = "OU=Test,DC=Fabrikam,DC=COM"
# read the CSV and grab the 'RecipientAddress' fields in an array
$emailAddresses = (Import-Csv "C:\temp\used_groups.csv").RecipientAddress
foreach ($email in $emailAddresses){
$GroupToMove = Get-ADGroup -Filter "mail -like '$email'"
if ($GroupToMove) {
# Move-ADObject takes the 'DistinghuishedName' or the 'objectGUID' as Identity parameter
# but it also works when piping the group object itself to it.
$GroupToMove | Move-ADObject -TargetPath $destinationOU
Write-Host "Moved group '$($GroupToMove.Name)'."
}
else {
Write-Warning "Could not find group with email address '$email'"
}
}

When using a CSV you have to specify the fieldname. Another problem in your script is the absence of quotes in the AD filter.
Try this:
$Groups=import-csv "C:\temp\used_groups.csv"
ForEach ($Group in $Groups){
(Get-ADGroup -Filter "mail -like '$($Group.RecipientAddress)'").samaccountname
# rest of script.. not done yet.
}
Cheers,
Gert Jan

Related

Add user to group based on their attribute department with Powershell in AD

Hello guys I would like to ask for little help
I was struggling with this for a while so Il be really glad if someone could help me with this :)
The idea is:
We have users with the filled department attribute (ex. LCZ_10960-udrzba rezie, LCZ_40900-financni utvar, etc...) and we have created security groups that look like CZ-udrzba_rezie_10960, CZ-financni_utvar_40900, etc... And that what I want from the script is to search through specific OU for users and check their department attribute and if they have forex. LCZ_10960-udrzba rezie in it then add this user to group CZ-udrzba_rezie_10960 or if another user has CZ-financni_utvar_40900 in the department then add this user the group LCZ_40900-financni utvar...
Hope I explain it good :)
I already create the script but that is only for add single group...
Get-ADUser -SearchBase "XY,DC=local" -Filter 'Department -like "LCZ_10960-udrzba rezie"' | Foreach{Add-ADGroupMember -Identity "CZ-udrzba_rezie_10960" -Members $_}
Thanks for the help guys!
In this case, I would create a lookup Hashtable linking the department names and the group names together:
# lookup hashtable:
# Keys are the Department names from the user attributes, the Values contain the Group names
$deptGroups = #{
'LCZ_10960-udrzba rezie' = 'CZ-udrzba_rezie_10960'
'LCZ_40900-financni utvar' = 'CZ-financni_utvar_40900'
# more Department-to-Group mappings go here
}
Then you can use code like this:
foreach ($dept in $deptGroups.Keys) {
$users = Get-ADUser -SearchBase "XY,DC=local" -Filter "Department -eq '$dept'" -ErrorAction SilentlyContinue
if ($users) {
# $deptGroups[$dept] has the group name from the lookup table
# you can supply an array of members with Add-ADGroupMember, so no need for a ForEach-Object loop
Add-ADGroupMember -Identity $deptGroups[$dept] -Members $users
}
else {
Write-Warning "No users found for department '$dept'.."
}
}

Pulling a specific proxyaddress from AD using powershell

I have a list of users in a csv file. This list contains users whose primary SMTP address is not internal to our organization. These are mail users who are having email forwarded elsewhere.
They have a proxyaddress listed in AD that is on their AD account that points to the organization and this is what I am trying to get to. The problem is that the proxyaddresses does not put the email in the same location so I need to somehow extrapolate the email(s). that match a certain criteria.
What I would really like to get at is the first.last#example.com or first_last.example.com without the {smtp: } formatting.
I have been able to produce a list of proxyaddresses but again it is just a list.
$users = import-csv $BadEmailList | % {Get-ADUser $_.LoginID -Properties proxyaddresses}
Foreach ($u in $users) {
$proxyAddress = [ordered]#{}
$proxyAddress.add(“User”,$u.name)
For ($i = 0; $i -le $u.proxyaddresses.count; $i++)
{
$proxyAddress.add(“ProxyAddress_$i”,$u.proxyaddresses[$i])
} #end for
[pscustomobject]$proxyAddress |
Export-Csv -Path $ProxyAddressList -NoTypeInformation –Append -Force
Remove-Variable -Name proxyAddress } #end foreach
What I am trying to get is the something similar to the following:
User ProxyAddress_0
---- -----
User1 first.last#example.com
If you just want to find the specific AD user with a given proxyaddress, as the header implies, you should be able to use a LDAP filter like this:
Get-ADUser -LDAPFilter "(&(objectCategory=person)(objectClass=user)(|(proxyAddresses=*:first.last#example.com)))"

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.

powershell retrieve members of group recursively

I got a pretty big audit project that I'm hoping to automate.
I need to get every user's name, SamAccountName, Title and Department who are part of a group. Problem is, the group has groups within it and those groups have groups within them. Another problem is that about 99% of all the groups have an asterisk in it's Display Name (NOT SamAccountName).
Here is the code I currently have, it works fine until it receives a group with an asterisk in it's name.. (hence the .Replace("*","") part.... Anyone got any ideas on how to fix this?
function Get-NestedGroupMember {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$Group
)
$broke = #();
## Find all members in the group specified
$members = Get-ADGroupMember -Identity $Group
foreach ($member in $members){
## If any member in that group is another group just call this function again
if ($member.objectClass -eq 'group'){
$memberGroup = $($member.Name).Replace("*", "")
try{
Get-NestedGroupMember -Group "$($memberGroup)"
}catch{
$broke += "$($memberGroup)`n"
}
}else{
## otherwise, just output the non-group object (probably a user account)
$member.Name
}
}
Write-Host "`nThe following groups could not be found automatically.`n`n$($broke)"
}
$getGroup = Read-Host -Prompt "Group name"
Get-NestedGroupMember $getGroup
As Bill_Stewart said, you are trying to implement functionality that already exists for you. Get-ADGroupMember has a -Recursive parameter that will search all of the nested groups and get the members for you. You can then pipe the output to a select and get only the properties you care about.
AD:
TopGroup
Betty
Bob
NestedGroup1
Joe
Frank
NestedGroup2
George
Herman
Using -Recursive
Get-AdGroupMember TopGroup -Recursive | Select-Object SamAccountName
Betty
Bob
Joe
Frank
George
Herman

Powershell - Adding users to AD group from a CSV file

I know this has been done to death but im useing this as a learning experience with powershell. Could someone take a look at my code and tell me where i am going wrong? Noob code warning!
#
# Add User to an AD Group
#
#
# get arguements and quit if they dont exist
$CSV = $args[0]
$GROUP = $args[1]
if (! $CSV) {
Write-Host "Please format this command as 'AddUsersToGroup <csv file> <AD group>'"
Write-Host "CSV file must have the header 'UserName' with AD usernames following"
exit
}
# Read csv file for users and add to AD group
Import-module ActiveDirectory
Import-CSV "$CSV" | % {
# Get existing users from AD group
$ExistingGroup = "Get-ADGroupMember $GROUP | Select-Object SamAccountName"
# create new array removing existing users from the csv
$NewGroup = $ExistingGroup | where {$CSV -notcontains $_}
# add the users to the AD Group from the new array
Add-ADGroupMember -Identity $NewGroup -Member $_.UserName
exit
}
try delete double quote here:
$ExistingGroup = Get-ADGroupMember $GROUP | Select-Object SamAccountName
with quote you're assign a string value to variable not the results of your commands