Link to home
Start Free TrialLog in
Avatar of MilesLogan
MilesLoganFlag for United States of America

asked on

Add To groups script with Powershell

Hi ALL

I am using the script below with a scheduled task for an application team to add users to their AD group.
What can I add to the script so if the Users.txt file is blank it outputs " No Users requested to be added" to
the AddedToGroup.csv file ?

$(Foreach ($User in GC C:\Powershell\Users.txt){
GC C:\Powershell\Groups.txt | % {
   $Group = $_
   #using try catch to capture the errors
   Try{
        Add-ADGroupmember -identity $Group -member $User -ea stop
	#create custom PS object to output the command status..
        New-Object PSObject -Property @{
	GroupName = $Group
	User = $User
	Status = "Added To Group"
	}
    }Catch{
	New-Object PSObject -Property @{
	GroupName = $Group
	User = $User
	Status = "Account already in the Group or not a valid ID"
	}	
     }
   }
}) | export-csv "C:\Powershell\AddedToGroup_$((Get-Date -Format MM-dd-yyyy-hhmmss)).csv" -NoTypeInformation

Open in new window

Avatar of becraig
becraig
Flag of United States of America image

if ( (get-childitem C C:\Powershell\Users.txt).length -eq 0 )
  {write-host 'No Users requested to be added'
    exit;
  }

$(Foreach ($User in GC C:\Powershell\Users.txt){
GC C:\Powershell\Groups.txt | % {
   $Group = $_
   #using try catch to capture the errors
   Try{
        Add-ADGroupmember -identity $Group -member $User -ea stop
	#create custom PS object to output the command status..
        New-Object PSObject -Property @{
	GroupName = $Group
	User = $User
	Status = "Added To Group"
	}
    }Catch{
	New-Object PSObject -Property @{
	GroupName = $Group
	User = $User
	Status = "Account already in the Group or not a valid ID"
	}	
     }
   }
}) | export-csv "C:\Powershell\AddedToGroup_$((Get-Date -Format MM-dd-yyyy-hhmmss)).csv" -NoTypeInformation
                                  

Open in new window

Avatar of MilesLogan

ASKER

Hi becraig

Instead of the message 'No Users requested to be added' .. how can I output it to the export-csv "C:\Powershell\AddedToGroup.csv file ?
ASKER CERTIFIED SOLUTION
Avatar of becraig
becraig
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you !! that was exactly what I needed ..