Solved

Remove a domain user from local Administrators group

Posted on 2016-07-20
7
40 Views
Last Modified: 2016-08-22
HI EE

Does anyone have a script they can share that will remove user objects from the local Administrators group on a Windows server(s)?

Ideally I would like to enter the server names to a text file and the SamAccountnames to another text file.

$ErrorActionPreference = "Stop"
GC Servers.txt | %{
$Serv = $_
$domain="MyDomain"
$group = "GroupName"
      Try {
      ([adsi]"WinNT://$Serv/Administrators,group").Remove("WinNT://$domain/$group,group")
      "" | Select @{N="Server";e={$Serv}},@{N="Status";e={"Success"}}
      }
      Catch{
      "" | Select @{N="Server";e={$Serv}},@{N="Status";e={"Failed"}}
      }
}
0
Comment
Question by:MilesLogan
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
  • 2
7 Comments
 
LVL 16

Expert Comment

by:FOX
ID: 41721382
If there are many servers to do this on in your scenario I would set up a gpp on the local administrators removing all and adding only who you want.  The below link will point you in the right direction

ref link:  http://www.grouppolicy.biz/2010/01/how-to-use-group-policy-preferences-to-secure-local-administrator-groups/

create your gpp and apply it to the OU or OUs with your servers.
0
 
LVL 2

Author Comment

by:MilesLogan
ID: 41721461
Hi Foxluv , I cant configure a GPP on these servers why I need to remove them manually.. thanks for the tip .
0
 
LVL 16

Assisted Solution

by:FOX
FOX earned 250 total points (awarded by participants)
ID: 41721465
Fair enough, if you know the user in question just run the command on the Server
example:  net localgroup administrators John /delete

*run from an elevated command prompt*
0
Does Powershell have you tied up in knots?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

 
LVL 2

Accepted Solution

by:
itnifl earned 250 total points (awarded by participants)
ID: 41721665
You can use psexec and run the command that Foxluv showed you remotely, and run it against all server listed in a file.
Psexec is a part of pstools:
https://technet.microsoft.com/en-us/sysinternals/psexec.aspx?f=255&MSPPError=-2147217396

psexec @run_file [options] command [arguments]

psexec.exe -accepteula serverlist.txt net localgroup administrators John /delete

Open in new window


Or something similar.
See also: http://ss64.com/nt/psexec.html

Haven't done this in some time, so you may have to try this a bit to get it correctly.

You can also loop through a list of servers from a file like you are already doing and then start remote powershell sessions to them. In those you can run commands as if you were local.

For instance the following. It does not solve your problem, but gives you an example on how it can be done.
Function Set-RemoteDate {
 <#
    .SYNOPSIS 
		Sets date and time on a remote Windows System via a Powershell session
    .EXAMPLE
		Set-RemoteDate -Address "address" -Username "administrator" -Password "123pass" -DateString "17/11/2011 5:35:25 PM"
  #>
	param(
		[alias("Address")] [Parameter(Mandatory=$True,Position=0)] [String] $systemAddress,
		[alias("Username")] [Parameter(Mandatory=$True,Position=1)] [String] $systemUsername,
		[alias("Password")] [Parameter(Mandatory=$True,Position=2)] [String] $systemPassword,
		[alias("DateString")]
		[Parameter(Mandatory=$True,Position=3)]
		[String] $dString,
		[alias("TimeZone")]
		[Parameter(Mandatory=$False,Position=4)]
		[String] $tZone
	)
	$props = @{
		errorID = 0;
	}
		
	#If we are using an IP-Address to communicate with the host we want to registry manipulate, add the address to list of trusted hosts:
	if($systemAddress -match '\b(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}\b') {
		#Write-Host -Foregroundcolor Yellow "-Adding $systemAddress to list of trusted hosts"
		set-item wsman:\localhost\Client\TrustedHosts -value $systemAddress -Force -Confirm:$false
	}
	function Set-TimeZoneRemote { 
		param( 
			[parameter(Mandatory=$true)] 
			[string]$TimeZone 
		) 
		 
		$osVersion = (Get-Item "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").GetValue("CurrentVersion") 
		$proc = New-Object System.Diagnostics.Process 
		$proc.StartInfo.WindowStyle = "Hidden" 
	 
		if ($osVersion -ge 6.0) 
		{ 
			# OS is newer than XP 
			$proc.StartInfo.FileName = "tzutil.exe" 
			$proc.StartInfo.Arguments = "/s `"$TimeZone`"" 
		} 
		else 
		{ 
			# XP or earlier 
			$proc.StartInfo.FileName = $env:comspec 
			$proc.StartInfo.Arguments = "/c start /min control.exe TIMEDATE.CPL,,/z $TimeZone" 
		} 
		$proc.Start() | Out-Null 
	}
	try {
		Write-Host -Foregroundcolor Yellow "-Creating PowerShell remote session to $systemAddress"
		$securePassword = ConvertTo-SecureString -String $systemPassword -AsPlainText -Force
		$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $SystemUsername, $securePassword
		$session = New-PSSession -Credential $cred -ComputerName $systemAddress
	} catch {
		$props["errorID"] = 1.0;
		$props.Add("failedItem", $_.Exception.ItemName);
		$props.Add("errorMessage", @("ERROR: 1.0 Could not initiate remote PowerShell session to create scheduled task:" + $_.Exception.Message));
		return new-object PSCustomObject -property $props
	}
	function Set-RemoteDate { 
		param( 
			[parameter(Mandatory=$true)] 
			[System.DateTime]$RemoteDate 
		) 
		Set-Date -Date $RemoteDate -Confirm:$false
	}
	try {
		Write-Host -Foregroundcolor Yellow "-Creating PowerShell remote session to $systemAddress"
		$securePassword = ConvertTo-SecureString -String $systemPassword -AsPlainText -Force
		$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $SystemUsername, $securePassword
		$session = New-PSSession -Credential $cred -ComputerName $systemAddress
	} catch {
		$props["errorID"] = 1.3;
		$props.Add("failedItem", $_.Exception.ItemName);
		$props.Add("errorMessage", @("ERROR: 1.0 Could not initiate remote PowerShell session to set remote date:" + $_.Exception.Message));
		return new-object PSCustomObject -property $props
	}

	try {
		Write-Host -Foregroundcolor Yellow "-Invoking command and running Set-Date on remote session"	
		if($tZone) {
			Write-Host -Foregroundcolor Yellow "-Invoking command and running remote function Set-TimeZoneRemote on remote session with argument $tZone"
			$i = Invoke-Command $session -ScriptBlock ${function:Set-TimeZoneRemote} -ArgumentList $tZone
		}
		if($dString -ne "NA") {
			Write-Host -Foregroundcolor Yellow "-Invoking command and running remote function Set-RemoteDate on remote session with argument $dString"
			$i = Invoke-Command $session -ScriptBlock ${function:Set-RemoteDate} -ArgumentList (Get-Date $dString)
		}
		#If we are using an IP-Address to communicate with the host we want to registry manipulate, remove the address to list of trusted hosts now since we are done using it:
		if($systemAddress -match '\b(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}\b') {
			$newvalue = ((Get-ChildItem WSMan:\localhost\Client\TrustedHosts).Value).Replace($systemAddress,"")
			Set-Item WSMan:\localhost\Client\TrustedHosts $newvalue -Force -Confirm:$false
		}
		try {
			Remove-PSSession -Session $session -Confirm:$false
		} catch {
			$props["errorID"] = 1.2;
			$props.Add("failedItem", $_.Exception.ItemName);
			$props.Add("errorMessage", @("ERROR: 1.2 Could not terminate remote PowerShell session to systemAddress: " + $_.Exception.Message));
			return new-object PSCustomObject -property $props
		}		
		return $i;
	} catch {
		$props["errorID"] = 1.1;
		$props.Add("failedItem", $_.Exception.ItemName);
		$props.Add("LineNumber",  @("At line: " + $_.InvocationInfo.ScriptLineNumber));
		$props.Add("PositionMessage",  @($_.InvocationInfo.PositionMessage));
		$props.Add("errorMessage", @("ERROR: 1.1 Could not initiate remote PowerShell session to set remote date: " + $_.Exception.Message));
		return new-object PSCustomObject -property $props
	}
}

Open in new window

0
 
LVL 2

Author Comment

by:MilesLogan
ID: 41724814
Thanks for the tips , will give it a try .
0
 
LVL 2

Author Comment

by:MilesLogan
ID: 41730129
Thanks ..
0
 
LVL 2

Expert Comment

by:itnifl
ID: 41756097
The author has thanked for the participation and seems to be content with the answers given.
0

Featured Post

Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Background Information Recently I have fixed file server permission issues for one of my client. The client has 1800 users and one Windows Server 2008 R2 domain joined file server with 12 TB of data, 250+ shared folders and the folder structure i…
A safe way to clean winsxs folder from your windows server 2008 R2 editions
To efficiently enable the rotation of USB drives for backups, storage pools need to be created. This way no matter which USB drive is installed, the backups will successfully write without any administrative intervention. Multiple USB devices need t…
This tutorial will show how to configure a new Backup Exec 2012 server and move an existing database to that server with the use of the BEUtility. Install Backup Exec 2012 on the new server and apply all of the latest hotfixes and service packs. The…

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question