Managing Local Accounts through PowerShell

When managing Local Accounts through PowerShell, it’s possible to use the [ADSI] type adapter.
Starting off, let’s look at how to connect to the Local Computer.


PS > $ComputerName = $env:COMPUTERNAME
PS > $Computer = [adsi]"WinNT://$ComputerName"
PS > $Computer


distinguishedName :
Path              : WinNT://Computer01

Now that we have a variable holding the reference to our local computer, we can go ahead and add a Local User Account. This is done through the Create Method on the object. we’ll also add a Password for our User.


PS > $UserName = "NewUser"
PS > $Password = "Password1"
PS > $User = $Computer.Create("user",$UserName)
PS > $User.SetPassword($Password)
PS > $User.SetInfo()

And it’s as simple as that. If you’r running Windows 7 you have to start PowerShell with elevated rights in order to get it to work.

Removing the User is done by using the Delete() method.


PS > $Computer.Delete("user",$UserName)

Here’s a script i wrote that adds, removes or resets the password of a local User Account.

Click here to download the script

Examples on running the Script:


PS > Set-LocalAccount.ps1 -UserName NewUser -Password Password1 -Add
PS > Set-LocalAccount.ps1 -UserName NewUser -Password Password2 -ResetPassword
PS > Set-LocalAccount.ps1 -UserName NewUser -Remove

Rating 3.00 out of 5
[?]
  1. Fortunate
    October 31st, 2011 at 11:09 | #1

    Hi please assist me with below error:You cannot call a method on a null-value expression.
    At C:\scripts\CreateUser.ps1:93 char:90
    +< < .Create >.SetPassword >.SetInfo <<<<
    + CategoryInfo :InvalidOperation: [],RuntimeExpression
    + FullyQaulifiedErrorId :InvokeMethodOnNull

    I an trying to create a user
    ( ( ([adsi] “WinNT://$computer”).Create(“User”, $user) ).SetPassword($password) ).SetInfo()

  2. Fortunate
    October 31st, 2011 at 11:09 | #2

    $objOu = [ADSI]“WinNT://$computer”

    $objUser = $objOU.Create(“User”, $user)

    $objUser.setpassword($password)

    $objUser.SetInfo()

    $objUser.description = “Test user”

    $objUser.SetInfo()

  1. No trackbacks yet.

Comment Spam Protection by WP-SpamFree