How to remove user from groups that start with...

Answered How to remove user from groups that start with...

  • Wednesday, June 13, 2012 8:23 PM
     
      Has Code

    Hello,

    I have a PS script that is a work in progress, but I'm hung up on the syntax for the following:

    If a group starting with "Mydoc" is found, then remove the user from matching group.

    Any help would be much appreciated.

    Thanks!

    ---

    [IO.Directory]::SetCurrentDirectory((Convert-Path (Get-Location -PSProvider FileSystem)))
    "Current directory: " + [IO.Directory]::GetCurrentDirectory()
    
    $sourceDC="dc"
    $users = Get-Content UserSAMAcct.csv
    
    Import-module activedirectory
    
    Foreach ($user in $users){
    	$LogFile=[IO.Directory]::GetCurrentDirectory() + "\RemoveHDriveMapLog\" + $user + ".txt"
    	$ADUser = Get-ADUser -Filter 'SAMAccountName -eq $user' -server $sourceDC -properties memberof,scriptPath,homeDirectory,homeDrive
    	If($ADuser){
    	Write-Host $ADuser.name  -ForeGroundColor Cyan
    		Foreach ($Group in $ADUser.memberof){
    			If($Group.StartsWith("CN=Mydoc")){
    				$out=$User + " Found MyDoc Group"
    				Write-Host $out -ForeGroundColor DarkGray
    				If($Group -ne "Mydocsredirect_homesvr01_username"){
    				Remove-ADGroupMember -Identity $Group.StartsWith("CN=Mydoc") -Server $sourceDC
    					$out= "RemovedMyDoc," + $group
    					$out | Out-File -filepath $LogFile -append
    					Write-Host $out -ForeGroundColor DarkCyan
    				}
    			}
    			If($Group.StartsWith("CN=map_H")){
    				$out=" " + $User + " Found Map_H: Group"
    				Write-Host $out -ForeGroundColor DarkCyan
    				If($Group -ne "map_H_homesvr01_username"){
    					$out= "RemovedMapH," + $group
    					$out | Out-File -filepath $LogFile -append
    					Write-Host $out -ForeGroundColor DarkCyan
    				}
    			}
    		}
    		If($ADUser.ScriptPath -match "^map.vbs"){
    			$out="RemovedMapScript," + $ADUser.ScriptPath
    			$out | Out-File -filepath $LogFile -append
    			Write-Host $out -ForeGroundColor DarkCyan
    		}
    		If($ADUser.homeDirectory -match "^\\\\filesvr"){
    			$out="RemovedHomeDirectory," + $ADUser.homeDirectory
    			$out | Out-File -filepath $LogFile -append
    			Write-Host $out -ForeGroundColor DarkCyan
    		}elseif($ADUser.homeDirectory -ne $null){
    			$out="FoundOtherHomeDirectory," + $ADUser.homeDirectory
    			$out | Out-File -filepath $LogFile -append
    			Write-Host $out -ForeGroundColor Red
    		}
    		If($ADUser.homeDrive -eq "H:"){
    			$out="HomeDriveisH:" + $ADUser.homeDrive
    			$out | Out-File -filepath $LogFile -append
    			Write-Host $out -ForeGroundColor DarkCyan
    		}elseif($ADUser.homeDrive -ne $null){
    			$out="HomeDriveDifferentThanH," + $ADUser.homeDrive
    			$out | Out-File -filepath $LogFile -append
    			Write-Host $out -ForeGroundColor Red
    		}
    	}else{
    		$out="User not found"
    		Write-Host $out -ForegroundColor Yellow
    	}
    	$ADUser=$null
    	
    	Out-File -filepath $LogFile -append
    }


    • Edited by ian atchison Thursday, June 14, 2012 12:52 PM Adjusted Formatting
    •  

All Replies

  • Wednesday, June 13, 2012 8:47 PM
    Moderator
     
     Answered Has Code

    Your code is really hard to read without any indentation. In any case, if I understand what you are trying to do from your commented line:

    Remove-ADGroupMember -identity $Group.StartsWith "CN=Mydoc"

    You're right, that won't work. The -identity parameter needs the group's name, so just pass it the group name:

    Remove-ADGroupMember -identity $Group -members $user -whatif

    The -whatif shows what would happen if you ran the command without the -whatif parameter and is a very useful "sanity check."

    Bill

  • Thursday, June 14, 2012 12:59 PM
     
     

    Thanks Bill. I fixed the formatting, sorry about that. I must have not been paying attention. I made your suggested change and that did the trick. Thank you! Having made the change and reading through the block, I should have realized that $Group already had the value I was looking for!

    Thanks again!

    Ian

  • Thursday, June 14, 2012 2:37 PM
     
      Has Code

    This line is notgoing to work if you have a CSV.

     $LogFile=[IO.Directory]::GetCurrentDirectory() + "\RemoveHDriveMapLog\" + $user + ".txt"

     A CSV has fields. $user.name maybe?

    Here is an easier way to write it in PowerShell

    $LogFile="$pwd\RemoveHDriveMapLog\$user.txt"

    $pwd is the current directory. (pwd= Print Working Directory from Unix)

    The formatting is still not working because of mistakes in code.

    Import-module activedirectory
    function LogMsg($username,$msg){
    	Out-File $MSG -filepath $LogFile -append
    	Write-Host $msg -ForeGroundColor DarkCyan
    }
    $users = Get-Content UserSAMAcct.csv  # IS THIS REALLY A CSV?
    foreach ($user in $users){
        $username=$user.name
    	if($ADUser=Get-ADUser -LDAPFilter "(SAMAccountName=$username)" -properties memberof,scriptPath,homeDirectory,homeDrive){
            $logdile="$pwd\RemoveHDriveMapLog\$username.txt"
            LogMsg "Logfile for $username is $logfile"
    		Foreach ($Group in $ADUser.memberof){
    			If($Group.StartsWith("CN=Mydoc")){
    				LogMsg  "$username Found MyDoc Group" 
    				If($Group -ne "Mydocsredirect_homesvr01_username"){
        				Remove-ADGroupMember -Identity $Group.StartsWith("CN=Mydoc") -Server $sourceDC
    				}
    			}
    			If($Group.StartsWith("CN=map_H")){
    				LogMsg "$Username Found Map_H: Group"
    				If($Group -ne "map_H_homesvr01_username"){
    					LogMsg "RemovedMapH," + $group
    				}
    			}
    		}
    		If($ADUser.ScriptPath -match "^map.vbs"){
    			LogMsg "RemovedMapScript," + $ADUser.ScriptPath
    		}
    		If($ADUser.homeDirectory -match "^\\\\filesvr"){
    			LogMsg "RemovedHomeDirectory," + $ADUser.homeDirectory
    		}elseif($ADUser.homeDirectory -ne $null){
    			LogMsg "FoundOtherHomeDirectory," + $ADUser.homeDirectory
    		}
    		If($ADUser.homeDrive -eq "H:"){
    			LogMsg "HomeDriveisH:" + $ADUser.homeDrive
    		}elseif($ADUser.homeDrive -ne $null){
    			LogMsg "HomeDriveDifferentThanH," + $ADUser.homeDrive
    		}
    	}else{
    		write-Host "User not found" -ForegroundColor red -BackgroundColor white
    	}
    }

    Notice that when I fix the code the fromatting is colorized correctly.

    I also removed the redundant lines as it makes this easier to undersand.  By using a logging function you can control the output better.file.  You are dealing with it as if it were a text file but it has a CSV extension.  This can confuse anyone looking at your code.

    ¯\_(ツ)_/¯




  • Thursday, June 14, 2012 2:48 PM
     
     

    I tried running the script with your suggestion ($LogFile="$pwd\RemoveHDriveMapLog\$user.txt") and it completed the same function. Will this work if run as a scheduled task? The only reason I used the original syntax was because a coworker mentioned issues when using a scheduled task. Your suggestion is much friendlier. The original did work even though it was referencing SAMAccount names from a CSV file. Not sure what the relationship would be to cause it not to work. 

    I'm not sure what you are referring to regarding the formatting and mistakes in the code.


    • Edited by ian atchison Thursday, June 14, 2012 2:51 PM edit
    •  
  • Thursday, June 14, 2012 3:06 PM
     
     

    I did not debug your code so there may stil be issues.  I am just showing you how to simplify by usig standard PowerShell coding techniques.  Tose lines of code are basically a do nothing patch for superstitious reasons.

    I have seen this before and it doesn;t fic the issue.  If you are going to run under the task scheduler then it would be better to use absolute paths. 

    SSTart bys setting the logpath.

    $logpath='x:\folder\logs'

    The use this in the logging routine.

    $logfile="$logpath\$username.txt"

    That will eliminate the mistakes associated with the scheduler. Peoplke always forget that under the scheduler to currentpath is set to the Windows folder or to the home folder of the user account the script is running under.  Ty need to specuify a specfic starting folder in teh scheduler.

    Stay with PowerShell methods.  Your code will be easier to understand and easier to debug.  The write-host output will not be visble when run as a task.

    It is beter to give a worker permisisons on teh objects and let them run direct.  Uisng Task scheduler to give a manager or helpdesk person access to user management has been discussed for years.  It is never a good idea to use the task scheduler.  It is jsut as unsafe as giving out the admin account password.

    The delegation wizard was created in AD to allow a group or user to be assigned to do basic user management functions like add or remove goup members.  It is extremely granular down to the individual attribute.  AD was designed from the beginning to be used this way.  Unfortuantely only   few are actually trained and certified in AD. The othe rAdmins learn by asking other untrained admins.  The solutions are not usually very good.

    Anyway - Good Luck with your script.


    ¯\_(ツ)_/¯