Solved

Remove a domain user from local Administrators group

Posted on 2016-07-20
7
32 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
Comment Utility
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
Comment Utility
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)
Comment Utility
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
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 2

Accepted Solution

by:
itnifl earned 250 total points (awarded by participants)
Comment Utility
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
Comment Utility
Thanks for the tips , will give it a try .
0
 
LVL 2

Author Comment

by:MilesLogan
Comment Utility
Thanks ..
0
 
LVL 2

Expert Comment

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

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

How to sign a powershell script so you can prevent tampering, and only allow users to run authorised Powershell scripts
In this previous article (https://oddytee.wordpress.com/2016/05/05/provision-new-office-365-user-and-mailbox-from-exchange-hybrid-via-powershell/), we made basic license assignments to users in O365. When I say basic, the method is the simplest way …
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 walk an individual through setting the global and backup job media overwrite and protection periods in Backup Exec 2012. Log onto the Backup Exec Central Administration Server. Examine the services. If all or most of them are stop…

744 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

10 Experts available now in Live!

Get 1:1 Help Now