Archive

Archive for the ‘Active Directory’ Category

Using PowerShell to get/start VM´s from Hyper-V servers in Active Directory

August 24th, 2012 No comments

Of course I would rather have all my hosts in my System Center VMM 2012 SP1 but if I do not, or I just as an ITPro admin want to check if there are some new Hyper-V servers out there in my Active Directory and if they have VM´s on them I can use PowerShell.

I have looked at Ravikanth´s blog and done some modifications, also I am using the Win2012 and Powershell v3.

I can with the following powershell cmd get all hyper-v virtual machines in my Active Directory (of some reason the VMware machines do not get registered in the AD as virtual machines). With powershell version 3 it autoloads the Active Directory Module, this requires though that I have the feature RSAT-AD-PowerShell installed, easily done with Get-WindowsFeature RSAT-AD-PowerShell | Add-WindowsFeature.

Get-ADObject -Filter 'Name -like "*Virtual*"' | %{$_.DistinguishedName.Split(",")[1].replace("CN=","") }

I cannot do so much more with this information, what I want is to check a list of Hyper-V servers and also try to get the VM´s on them, sadly only win2012 servers can interact with the hyper-v powershell module and give that info, but hey whom has win 2008 r2 hyper-v servers ;-)

This first query gives me all Hyper-V servers in the domain, 2008->2012

Get-ADObject -Filter 'Name -like "*Hyper-V"' | %{$_.DistinguishedName.Split(",")[1].replace("CN=","") }

This next query uses that info and asks the Hyper-V servers for their VM´s

Get-ADObject -Filter 'Name -like "*Hyper-V"' | %{$_.DistinguishedName.Split(",")[1].replace("CN=","") } | %{get-vm -ComputerName $_ -ErrorAction SilentlyContinue} | ft ComputerName,Name,State,Uptime -AutoSize

I can also use this to do things with the VM´s, like starting or stopping, observe that i just want to start the VM´s that start with the name test*.

Get-ADObject -Filter 'Name -like "*Hyper-V"' | %{$_.DistinguishedName.Split(",")[1].replace("CN=","") } | %{get-vm test* -ComputerName $_ -ErrorAction SilentlyContinue} | Start-VM

Populate and administer Active directory users with Powershell

January 4th, 2012 No comments

Some days ago I have been working on some powershell scripts for a lab environment and now i have edited the handlescript to work better and with more functionality.

First i created a small script for populating some OU with student accounts.

# Script: Createusers.ps1
# Create users in AD
# Version: 0.1
# Niklas Akerlund /RTS

Import-Module Activedirectory

$OUs =  "OU1","OU2","OU3","OU4","OU5","OU6"

foreach ($OU in $OUs){
	$path = "OU=" + $OU + ",OU=lab,OU=Users,DC=demo,DC=local"
	for ($i=1;$i -le 10;$i++){
    	$SAMid = $OU + "Student0" + $i 
    	$Name = $OU + "Student0" + $i 
    	New-ADUser -SamAccountName $SAMid -Name $Name -AccountPassword (ConvertTo-SecureString -AsPlainText "S0meP@ssw0rd" -Force) -Enabled $true -Path $path
   
	}
}

 

Then i created with help from Jeffery Hicks post a script with a menu to enable or disable accounts in the different OU´s. As i described in a earlier post it is quite powerful to use Active Directory cmdlets and i have tried to take care of that by checking that when i enable/disable accounts i check that i really have something in my searchbase. Below are two screenshots of the script running. Update I have now updated the script with a check for the searchbase that actually works and also an extra menu option with the ability to set password on the accounts i enable!

 

Here is the script that creates this, i have not yet come up with a better and more dynamic way to create the switch, maybe someone can give me some help there..

# Script: handleusers.ps1
# Version: 0.1
# Disable or enable lab account users
# 
# Niklas Akerlund / RTS
# Menu code from Jeffery Hicks 

Import-Module ActiveDirectory
 
Function Show-Menu {

	Param(
		[Parameter(Position=0,Mandatory=$True,HelpMessage="Enter your menu text")]
		[ValidateNotNullOrEmpty()]
		[string]$Menu,
		[Parameter(Position=1)]
		[ValidateNotNullOrEmpty()]
		[string]$Title="Menu",
		[switch]$ClearScreen
	)

	if ($ClearScreen) {Clear-Host}

	#build the menu prompt
	$menuPrompt=$title
	#add a return
	$menuprompt+="<code>n"
	#add an underline
	$menuprompt+="-"*$title.Length
	$menuprompt+="</code>n"
	#add the menu
	$menuPrompt+=$menu

	Read-Host -Prompt $menuprompt

} #end function

$menu="<code>n"
$ListOU = Get-ADOrganizationalUnit -filter * -Searchbase "OU=lab,OU=Users,DC=demo,DC=local" | where {$_.Name -ne "lab"} | Sort-Object $_.Name

$i = 1
foreach ($OU in $ListOU){
	   $menu+= [string]$i + " " + $OU.Name + "</code>n"
      # write-host $menu
       $i = $i+1
     
}
$menu+= "Q Quit"
$menu+= "<code>n"

# Menu 2 
$menu2=@"
1 Disable accounts
2 Enable accounts
3 Set password and enable accounts
B Back to menu
"@
$menu2+= "</code>n"

#Keep looping and running the menu until the user selects Q (or q).
Do {
    #use a Switch construct to take action depending on what menu choice
    #is selected.
    Switch (Show-Menu $menu "Get OU to handle" -clear ) {
     "1" {
	 		if ($ListOU[0].DistinguishedName -ne $null){
		 		$menutext = "Handle " + $ListOU[0].Name + " users to disable/enable "
				$Users = Get-ADUser -filter * -searchbase $ListOU[0].DistinguishedName
		 		Switch (Show-Menu $menu2 $menutext -clear ) {
	     		"1" {
		 					$Users |  Set-ADUser -Enabled $false	
	         		} 
	     		"2" {
		 					$Users |  Set-ADUser -Enabled $true	
	          		}
	     		"3" {
							$newPassword = (Read-Host -Prompt "Provide New Password" -AsSecureString)
		 					$Users | Set-ADUser -Enabled $true	
							$Users | Set-ADAccountPassword -NewPassword $newPassword -Reset
	          		}
				"B" {
						Write-Host "Back to menu" -ForegroundColor Cyan
	        		}
				Default {Write-Warning "Invalid Choice. Try again."
	              sleep -milliseconds 750}
	         	}
			}
		 }
     "2"  {
	 		if ($ListOU[1].DistinguishedName -ne $null){
		 		$menutext = "Handle " + $ListOU[1].Name + " users to disable/enable " 
				$Users = Get-ADUser -filter * -searchbase $ListOU[1].DistinguishedName
		 		Switch (Show-Menu $menu2 $menutext -clear ) {
	     		"1" {
		 				
		 					$Users |  Set-ADUser -Enabled $false	
						
	         		} 
	     		"2" {
		 					$Users |  Set-ADUser -Enabled $true	
	          		}
				"3" {
							$newPassword = (Read-Host -Prompt "Provide New Password" -AsSecureString)
		 					$Users | Set-ADUser -Enabled $true	
							$Users | Set-ADAccountPassword -NewPassword $newPassword -Reset
	          		}
				"B" {
						Write-Host "Back to menu" -ForegroundColor Cyan
	        		}
				Default {Write-Warning "Invalid Choice. Try again."
	              sleep -milliseconds 750}
	         	} 
			}
		 }
     "3" {
	 		if ($ListOU[2].DistinguishedName -ne $null){
		 		$menutext = "Handle " + $ListOU[2].Name + " users to disable/enable " 
				$Users = Get-ADUser -filter * -searchbase $ListOU[2].DistinguishedName
		 		Switch (Show-Menu $menu2 $menutext -clear ) {
	     		"1" {
		 					$Users |  Set-ADUser -Enabled $false		
	         		} 
	     		"2" {
		 					$Users |  Set-ADUser -Enabled $true	
	          		}
				"3" {
							$newPassword = (Read-Host -Prompt "Provide New Password" -AsSecureString)
		 					$Users | Set-ADUser -Enabled $true	
							$Users | Set-ADAccountPassword -NewPassword $newPassword -Reset
	          		}
				"B" {
						Write-Host "Back to menu" -ForegroundColor Cyan
	        		}
				Default {Write-Warning "Invalid Choice. Try again."
	              sleep -milliseconds 750}
	         	} 
			}
		 }
	 "4" {
	 		if ($ListOU[3].DistinguishedName -ne $null){
		 		$menutext = "Handle " + $ListOU[3].Name + " users to disable/enable " 
				$Users = Get-ADUser -filter * -searchbase $ListOU[3].DistinguishedName
		 		Switch (Show-Menu $menu2 $menutext -clear ) {
	     		"1" {
		 					$Users |  Set-ADUser -Enabled $false		
	         		} 
	     		"2" {
		 					$Users |  Set-ADUser -Enabled $true	
	          		}
				"3" {
							$newPassword = (Read-Host -Prompt "Provide New Password" -AsSecureString)
		 					$Users | Set-ADUser -Enabled $true	
							$Users | Set-ADAccountPassword -NewPassword $newPassword -Reset
	          		}
				"B" {
						Write-Host "Back to menu" -ForegroundColor Cyan
	        		}
				Default {Write-Warning "Invalid Choice. Try again."
	              sleep -milliseconds 750}
	         	} 
			}
		 }
	 "5" {
	 		if ($ListOU[4].DistinguishedName -ne $null){
		 		$menutext = "Handle " + $ListOU[4].Name + " users to disable/enable " 
				$Users = Get-ADUser -filter * -searchbase $ListOU[4].DistinguishedName
		 		Switch (Show-Menu $menu2 $menutext -clear ) {
	     		"1" {
		 					$Users |  Set-ADUser -Enabled $false		
	         		} 
	     		"2" {
		 					$Users |  Set-ADUser -Enabled $true	
	          		}
				"3" {
							$newPassword = (Read-Host -Prompt "Provide New Password" -AsSecureString)
		 					$Users | Set-ADUser -Enabled $true	
							$Users | Set-ADAccountPassword -NewPassword $newPassword -Reset
	          		}
				"B" {
						Write-Host "Back to menu" -ForegroundColor Cyan
	        		}
				Default {Write-Warning "Invalid Choice. Try again."
	              sleep -milliseconds 750}
	         	} 
			}
		 }
	 "6" {
	 		if ($ListOU[5].DistinguishedName -ne $null){
		 		$menutext = "Handle " + $ListOU[5].Name + " users to disable/enable " 
				$Users = Get-ADUser -filter * -searchbase $ListOU[5].DistinguishedNam
		 		Switch (Show-Menu $menu2 $menutext -clear ) {
	     		"1" {
		 					$Users |  Set-ADUser -Enabled $false	
						
	         		} 
	     		"2" {
		 					$Users |  Set-ADUser -Enabled $true	
	          		}
				"3" {
							$newPassword = (Read-Host -Prompt "Provide New Password" -AsSecureString)
		 					$Users | Set-ADUser -Enabled $true	
							$Users | Set-ADAccountPassword -NewPassword $newPassword -Reset
					}          	
				"B" {
						Write-Host "Back to menu" -ForegroundColor Cyan
	        		}
				Default {Write-Warning "Invalid Choice. Try again."
	              sleep -milliseconds 750}
	         	} 
			}
		 }
     "Q" {Write-Host "Goodbye" -ForegroundColor Cyan
         Return
         }
     Default {Write-Warning "Invalid Choice. Try again."
              sleep -milliseconds 750}
    } #switch
} While ($True)


 

Categories: Active Directory, Automation, Powershell Tags:

Recover Administrator password after some powershell on the Active Directory

November 11th, 2011 No comments

Yes powershell can be used to administer your Active Directory, but you could do some serious damage also. I will show you one particular case where things can go very wrong and how to recover from it.

To use cmdlets for AD you simply start your powershell console and type

Import-Module ActiveDirectory

You get quite a few cmdlets to help you automate your user administration, if you write the following in your console it will list all of them.

Get-Command *-AD*

Well now to the problem, as a domain admin you do have some privileges and say that you want to disable some user accounts and you forget to add a searchbase or your filter does not do as you wish and in one line you have disabled all accounts in your domain, including admin. IF and i say IF you realize that misstake and quickly go in and enable the accounts again, you are safe, but if you log out of your session you wont be able to log in again with any account :-)

Get-ADUser -Filter * | Set-ADUser -Enabled $False

try to log in as domain administrator and you will get this, on any DC (as long as your replication is working and if it is not you have other problems, trust me)

So how do we fix this then? luckily there is a way to do this and it is quite easy. You have to find a windows iso and as in this case a Win 2008 r2, start it in repair mode and start a CMD

when the command promt is started do this (i found it in another blog from Matheu the difference here is that i use net user administrator /active:yes to enable instead of change password)

  • Go to c:\windows\system32
  • Rename Utilman.exe to Utilman.exe.bak
  • Copy cmd.exe to Utilman.exe
  • Reboot on Windows
  • Do the keyboard shortcut Windows + U when on the logon screen
  • net user administrator /active:yes
  • log on with the domain admin account
  • Reboot on the DVD to put back the original Utilman.exe

Instead of panicking and try to restore your AD you can easily as i described log in again. This is of course a big security thing to consider in a virtual environment where users that have access to the virtual infrastructure but are not domain admins can manipulate virtual Domain controllers to get access to the administrator password “net user Administrator newpasswd123″. Here is a link to all net user commands.

So if i am going to do some account disabling i would include a searchbase in my Get-ADUser to not get the Administrator locked out by mistake and actually take the right OU to modify users on.

Get-ADUser -Filter * -SearchBase "OU=Employees, DC=Test, DC=local" | Set-ADUser -Enabled $False

In my test environment i used two DC´s and both the lock and unlocking replicated quite fast. There is maybe a way with the Active Directory Domain Services Recovery without having to do a restore, i will look into that and do a follow up post if i find any easy ways!

Categories: Active Directory Tags: