Solved

Remove a domain user from local Administrators group

Posted on 2016-07-20
7
34 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
  • 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
Enterprise Mobility and BYOD For Dummies

Like “For Dummies” books, you can read this in whatever order you choose and learn about mobility and BYOD; and how to put a competitive mobile infrastructure in place. Developed for SMBs and large enterprises alike, you will find helpful use cases, planning, and implementation.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

OfficeMate Freezes on login or does not load after login credentials are input.
Possible fixes for Windows 7 and Windows Server 2008 updating problem. Solutions mentioned are from Microsoft themselves. I started a case with them from our Microsoft Silver Partner option to open a case and get direct support from Microsoft. If s…
This tutorial will give a an overview on how to deploy remote agents in Backup Exec 2012 to new servers. Click on the Backup Exec button in the upper left corner. From here, are global settings for the application such as connecting to a remote Back…
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…

911 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now