Solved

Remove a domain user from local Administrators group

Posted on 2016-07-20
7
41 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
Transaction Monitoring Vs. Real User Monitoring

Synthetic Transaction Monitoring Vs. Real User Monitoring: When To Use Each Approach? In this article, we will discuss two major monitoring approaches: Synthetic Transaction and Real User Monitoring.

 
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

PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

Question has a verified solution.

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

Auditing domain password hashes is a commonly overlooked but critical requirement to ensuring secure passwords practices are followed. Methods exist to extract hashes directly for a live domain however this article describes a process to extract u…
I was prompted to write this article after the recent World-Wide Ransomware outbreak. For years now, System Administrators around the world have used the excuse of "Waiting a Bit" before applying Security Patch Updates. This type of reasoning to me …
This tutorial will walk an individual through configuring a drive on a Windows Server 2008 to perform shadow copies in order to quickly recover deleted files and folders. Click on Start and then select Computer to view the available drives on the se…
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …

688 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