search
Categories
Sponsors
VirtualMetric Hyper-V Monitoring, Hyper-V Reporting
Archive
Blogroll

Badges
MCSE
Community

Cozumpark Bilisim Portali
How to create Windows user with Powershell?
Posted in Windows Powershell, Windows Server | 4 Comments | 7,353 views | 23/06/2009 10:39

You can create Windows user from Powershell:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function create_user($username, $password)
	{
		$computer = [ADSI]"WinNT://localhost"
		foreach ($user in $computer.psbase.children)
			{
				if ($user.Name -eq $username)
					{
						Write-Host $user.Name "already exist."
						Return
					}
			}
		$user_obj = $computer.Create("user", "$username")
		$user_obj.Put("description", "$username")
		$user_obj.SetInfo()
		$user_obj.SetPassword($password)
		$user_obj.SetInfo()
		$user_obj.psbase.invokeset("AccountDisabled", "False")
		$user_obj.SetInfo()
		Write-Host "$username created."
	}
 
create_user "$username" "$password"

It checks user and if it is not exist, creates that username.


Comments (4)

Heriyanto

February 9th, 2010
08:13:12

what about to create user on remote host (server)?
i’ve tried to replace the
$computer = [ADSI]”WinNT://localhost”
to
$computer = [ADSI]”WinNT://192.168.1.10″ but i got this error :
Exception calling “SetInfo” with “0” argument(s): “Logon failure: unknown username or bad password. (Exception from HRESULT: 0x8007052E)”
At line:14 char:26
+ $user_obj.SetInfo <<<< ()
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : CatchFromBaseAdapterMethodInvokeTI

please help me!

thanks.


admin

February 13th, 2010
13:02:08

Hello Herry,

I wrote a script to create user remote host. I’ll try to post you today, it’s on office pc.

But you can try Remote Powershell for all scripts. Just google for New-PSSession and Enter-PSSession.

See you.


admin

February 15th, 2010
23:14:09

Hello Herry,

You need to have admin privileges on all remote servers. You can set same username and password on all servers or you can join them to an active directory. Using PSexec or Remote Powershell are other options.


kiran

July 26th, 2010
16:38:58

you might want to add an additional if statement at the end to actually verify if the user got created or not.

I ran this today on localhost and got an error and still got the output user created which obviously wasnt right.

function create-user($username, $password)
{

$computer = [ADSI]”WinNT://localhost”
foreach ($user in $computer.psbase.children)
{
if ($user.Name -eq $username)
{
Write-Host $user.Name “already exist.”
Return
}
}
$user_obj = $computer.Create(“user”, “$username”)
$user_obj.Put(“description”, “$username”)
$user_obj.SetInfo()
$user_obj.SetPassword($password)
$user_obj.SetInfo()
$user_obj.psbase.invokeset(“AccountDisabled”, “False”)
$user_obj.SetInfo()
if ($user.Name -eq $username)
{
Write-Host “$username created.”
Return
}
else
{
Write-host “Error Creating $username”
}
}



Leave a Reply