Petri IT Knowledgebase Forums
 

Petri.co.il forums Home Forums Start Page Forums Frequently Asked Questions FAQ Member List Members List
Go Back   Petri IT Knowledgebase Forums > Windows Scripting > Powershell
Petri.co.il is happy to award auglan the title of Most Valuable Member !!!
Register Calendar Calendar Search Petri IT Knowledgebase Forums Search Todays Posts Today's Posts Mark Forums Read

Notices

Disable or Enable user account via powershell script

Disable or Enable user account via powershell script

this thread has 8 replies and has been viewed 40192 times

Closed Thread
 
Thread Tools Search this Thread Display Modes
  #1  
Old 23rd June 2008, 16:32
XtaZee XtaZee is offline
Casual
It's not a coincidence
 
 Join Date: Jan 2005
  6 month star 12 month star
 Posts: 71
 Reputation: XtaZee is on a distinguished road (33)
Default Disable or Enable user account via powershell script

Hi,
Looking for a script that enable or disable a user account via PowerShell v1

the script should be given 2 parameters username and state (enable/disable)

so far I have a little code that will search for the user in ldap

Code:
function get-dn ($SAMName)
{
 	$root = [ADSI]''
 	$searcher = new-object     System.DirectoryServices.DirectorySearcher($root)
	$searcher.filter = "(&(objectClass=user)(sAMAccountName= $SAMName))"
	$user = $searcher.findall()

	if ($user.count -gt 1)
      {     
            $count = 0
            foreach($i in $user)
            { 
			write-host $count ": " $i.path 
                  $count = $count + 1
            }

            $selection = Read-Host "Please select item: "

return $user[$selection].path

      }
      else
      { 
	  	return $user[0].path
      }
}

$Name = $args[0]
$path = get-dn $Name
"'" + $path + "'"
your 2 cents will be mostly welcome...
  #2  
Old 23rd June 2008, 17:24
XtaZee XtaZee is offline
Casual
It's not a coincidence
 
 Join Date: Jan 2005
  6 month star 12 month star
 Posts: 71
 Reputation: XtaZee is on a distinguished road (33)
Default Re: Disable or Enable user account via powershell script

figured it out
here is the code:

Code:
 
function get-dn ($SAMName)
{
 	$root = [ADSI]''
 	$searcher = new-object     System.DirectoryServices.DirectorySearcher($root)
	$searcher.filter = "(&(objectClass=user)(sAMAccountName= $SAMName))"
	$user = $searcher.findall()

	if ($user.count -gt 1)
      {     
            $count = 0
            foreach($i in $user)
            { 
			write-host $count ": " $i.path 
                  $count = $count + 1
            }

            $selection = Read-Host "Please select item: "

return $user[$selection].path

      }
      else
      { 
	  	return $user[0].path
      }
}

$Name = $args[0]
$status = $args[1]
$path = get-dn $Name
"'" + $path + "'"  

if ($status -match "enable") 
	{
		# Enable the account
		$account=[ADSI]$path
		$account.psbase.invokeset("AccountDisabled", "False")
		$account.setinfo()
	}
else
	{
		# Disable the account
		$account=[ADSI]$path
		$account.psbase.invokeset("AccountDisabled", "True")
		$account.setinfo()
	}
  #3  
Old 23rd June 2008, 17:34
tonyyeb's Avatar
tonyyeb tonyyeb is offline
Moderator
 
 Join Date: Dec 2004
  6 month star 12 month star
 Location: Hull, UK
 Posts: 2,182
 Reputation: tonyyeb is a jewel in the roughtonyyeb is a jewel in the roughtonyyeb is a jewel in the rough (283)
Default Re: Disable or Enable user account via powershell script

Thanks for posting the corrected code.
__________________
Server 2000 MCP
Development: ASP, ASP.Net, PHP, VB, VB.Net, MySQL, MSSQL - Check out my blog http://tonyyeb.blogspot.com

** Remember to give credit where credit is due and leave reputation points To grant some reputation points to the user that helped you, just click on the little Yin-Yang icon on the right of the user's answer and follow the prompt. where appropriate **
  #4  
Old 16th October 2008, 06:44
MVP 58sniper 58sniper is offline
MVP
MVP
 
 Join Date: Sep 2008
  6 month star 12 month star
 Posts: 7
 Reputation: 58sniper has a spectacular aura about58sniper has a spectacular aura about58sniper has a spectacular aura about (200)
Default Re: Disable or Enable user account via powershell script

I played around with this a little. I added some minor error checking in case no users are found, and added automatically hiding/showing in the Exchange Global Address List. Save it as Disable-User.ps1

Code:
# http://www.petri.co.il/forums/showthread.php?p=109975 
# usage: Disable-User [accountname] [enable/disable]

function get-dn ($SAMName)    {
    $root = [ADSI]''
     $searcher = new-object System.DirectoryServices.DirectorySearcher($root)
    $searcher.filter = "(&(objectClass=user)(sAMAccountName= $SAMName))"
    $user = $searcher.findall()

    if ($user.count -gt 1)      {     
            $count = 0
                foreach($i in $user)            { 
            write-host $count ": " $i.path 
                    $count = $count + 1
                }

            $selection = Read-Host "Please select item: "
        return $user[$selection].path

          }      else      { 
          return $user[0].path
          }
}

$Name = $args[0]
$status = $args[1]
$path = get-dn $Name

if ($path -ne $null)    {

    "'" + $path + "'"  
    if ($status -match "enable")     {
        # Enable the account
        $account=[ADSI]$path
        $account.psbase.invokeset("AccountDisabled", "False")
        $account.setinfo()
        Set-Mailbox "$Name" -HiddenFromAddressListsEnabled $False
    }    else    {
        # Disable the account
        $account=[ADSI]$path
        $account.psbase.invokeset("AccountDisabled", "True")
        $account.setinfo()
        Set-Mailbox "$Name" -HiddenFromAddressListsEnabled $True
    }
}    else    {
    write-host "No user account found!" -foregroundcolor white -backgroundcolor red
}
Quote:
Originally Posted by XtaZee View Post
figured it out
here is the code:

Code:
 
function get-dn ($SAMName)
{
     $root = [ADSI]''
     $searcher = new-object     System.DirectoryServices.DirectorySearcher($root)
    $searcher.filter = "(&(objectClass=user)(sAMAccountName= $SAMName))"
    $user = $searcher.findall()

    if ($user.count -gt 1)
      {     
            $count = 0
            foreach($i in $user)
            { 
            write-host $count ": " $i.path 
                  $count = $count + 1
            }

            $selection = Read-Host "Please select item: "

return $user[$selection].path

      }
      else
      { 
          return $user[0].path
      }
}

$Name = $args[0]
$status = $args[1]
$path = get-dn $Name
"'" + $path + "'"  

if ($status -match "enable") 
    {
        # Enable the account
        $account=[ADSI]$path
        $account.psbase.invokeset("AccountDisabled", "False")
        $account.setinfo()
    }
else
    {
        # Disable the account
        $account=[ADSI]$path
        $account.psbase.invokeset("AccountDisabled", "True")
        $account.setinfo()
    }
__________________
Pat Richard
Exchange MVP
contributing author "Microsoft Exchange Server 2007: The Complete Reference"
  #5  
Old 16th October 2008, 11:36
AndyJG247's Avatar
AndyJG247 AndyJG247 is offline
Senior Member
Wrote the book
 
 Join Date: Mar 2008
  6 month star 12 month star
 Location: London
 Posts: 3,842
 Reputation: AndyJG247 is a jewel in the roughAndyJG247 is a jewel in the roughAndyJG247 is a jewel in the roughAndyJG247 is a jewel in the rough (349)
Default Re: Disable or Enable user account via powershell script

Much respect Pat
__________________
cheers
Andy

Please read this before you post:
http://support.microsoft.com/kb/555375

Quis custodiet ipsos custodes?
  #6  
Old 17th October 2008, 02:24
MVP 58sniper 58sniper is offline
MVP
MVP
 
 Join Date: Sep 2008
  6 month star 12 month star
 Posts: 7
 Reputation: 58sniper has a spectacular aura about58sniper has a spectacular aura about58sniper has a spectacular aura about (200)
Default Re: Disable or Enable user account via powershell script

I'd be willing to add more if anyone has requirements.
__________________
Pat Richard
Exchange MVP
contributing author "Microsoft Exchange Server 2007: The Complete Reference"
  #7  
Old 15th January 2009, 03:10
apperrault apperrault is offline
Casual
It's not a coincidence
 
 Join Date: Apr 2006
  6 month star 12 month star
 Posts: 86
 Reputation: apperrault is on a distinguished road (12)
Default Re: Disable or Enable user account via powershell script

This is exactly what i have been looking for. Is there any way to get it to read from a file? I have a list of about 40 users that i need to disable, and hide from Exchange in one fell swoop if possible. Having a script to do that would be ideal!!!

Thanks much

app
  #8  
Old 23rd June 2009, 23:39
Damianini Damianini is offline
Casual
Casual
 
 Join Date: Jun 2009
  6 month star 12 month star
 Posts: 1
 Reputation: Damianini is on a distinguished road (10)
Default Re: Disable or Enable user account via powershell script

There is an easier way to do this using quest active roles tool for active directory if your organization is a windows domain. It is a free download for your use and very powerful: http://www.quest.com/powershell/activeroles-server.aspx

This will need to be install wherever you are running your exchange tasks from. I run all this from my local system. I have powershell, quest active roles for powershell and the exchange managment console. Mostly everyone managing exchange 2007 already has 2 of these items installed.

There are two scripts below. The top one asks you the samaccountname of the user and then takes that name hides it from the address list and disables the user. The second script imports a csv file using the samaccount names of the individuals then goes through each user setting their GAL setting and disabling. Enjoy!

#Two Scripts- Contents of script between pound sign
################################################## ##############
#Single User

Add-PSSnapin Quest.ActiveRoles*
Add-PSSnapin Microsoft.Exchange*

$samaccountName = Read-Host "What is the shortname of the person you want to disable?"

Set-Mailbox $samaccountName -HiddenFromAddressListsEnabled $true
Disable-QADUser $samaccountName

################################################## ###############
#CSV file for importing.
#CSV file in the following format -Header Row !!!!!Make sure there are no empty carriage returns at the end of your csv otherwise it will throw an error
#Name
#John
#Mike
#Louie

Add-PSSnapin Quest.ActiveRoles*
Add-PSSnapin Microsoft.Exchange*

Import-Csv C:\New.txt | foreach {
Set-Mailbox $_.Name -HiddenFromAddressListsEnabled $true
Disable-QADUser $_.Name
}
################################################## ###############

If you want to make either one of these a function simply wrap in a function like this:

Function DisableUser ($samaccountname) {
Enter either script here
}

The add-pssnapin is for adding those modules to powershell. If you launch powershell by start--programs--WindowsPowershell this works. If you launch the exchange powershell managment console it will not without an error.

Viola....Enjoy!
  #9  
Old 23rd December 2009, 16:55
shiapi shiapi is offline
Casual
Casual
 
 Join Date: Dec 2009
  6 month star 12 month star
 Posts: 1
 Reputation: shiapi is on a distinguished road (10)
Default Re: Disable or Enable user account via powershell script

amn a v.new user of powershell but the bellow solution is what i have actually been looking for. pls can any one help with the finished codes using a double domain structure and multiple users in an OU. cheers

Last edited by shiapi; 23rd December 2009 at 17:09..
Closed Thread


Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Enable User in Live Communications Server Fails (Was:enable lcp user failed) h7h Windows Server 2000 / 2003 1 1st May 2007 12:07
I script was made by on of our administrator to disable any computer account noway Active Directory 3 18th July 2006 12:16
Disable Active Directory user account Lucide General Scripting 2 17th November 2005 16:30
Problems w/ unlock user account script in Active Directory Shane General Scripting 1 25th July 2005 23:29
Disable.Group.User.Account azmantek Active Directory 3 28th October 2004 19:52


All times are GMT +3. The time now is 12:42.

Steel Blue 3.5.4 vBulletin Style ©2006 vBEnhanced
Powered by vBulletin® Version 3.8.4
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
 

Valid XHTML 1.0!   Valid CSS!

Copyright 2005 Daniel Petri