Link to home
Start Free TrialLog in
Avatar of SAM2009
SAM2009Flag for Canada

asked on

PowerShell: Need to compare user and group from a list and remove user from the group

Hi,

How can I script this in PowerShell.

I have a file list mixed of AD users and groups: AD_UsersGrps.txt

My reference user= John

1- Read each content in the file list
2- If content it's a group then check if john is member of
3- If yes remove john from the AD group
ASKER CERTIFIED SOLUTION
Avatar of Mahesh
Mahesh
Flag of India 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
Avatar of SAM2009

ASKER

Hi,

Could you explain this part of code please. I don't understand what it means:

$ScriptDir = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent

Thanks
"$scriptdir" is nothing but script working directory (no matter where you save the script, but you must save it in some directory) and also I am telling script to look any input files or any output to be saved in same directory as script

$resultfile = $ScriptDir + "\Resultlogs.txt"
$txtpath = $ScriptDir + "\list.txt"
Avatar of SAM2009

ASKER

Ok I see. I was just do quick search in the web  and sometime I see this:

$ScriptDir = Split-Path $script:MyInvocation.MyCommand.Path

What this part mean?: $script:

Thanks
I have never used above variable because "Path" parameter is null in that case and I am not able to reach to script working directory (parent directory)
whereas in earlier command I am able to reach to script working directory (parent directory) because I am defining path parameter to script working directory
Please check if script works for you.
Avatar of SAM2009

ASKER

No problem I finally found that "$script:" mean variable but has script scope.

For the code I think one that is missing is to verify if user is member of the group before removing it.
By default PS script run in script scope only,

it must be "$ScriptDir = $script:MyInvocation.MyCommand.Path" so that it will run in working directory. Split-path would not required
If you mention split-path, -parent also should be there, otherwise you don't have path to split.

I thought about verifying user before removing from group, however you have only single list where I cannot pass same value with two variables (user and group in this case)
The remove-adgroupmember runs silently without any errors and whatever user (u specified), it will simply remove it if exists as member
Avatar of SAM2009

ASKER

Thanks for your help and explanation.