Tuesday, August 10, 2010

powershell - add user

In addition to the previous example it would be nice to create users from the .csv files.

You’ll need the Windows 2008 r2 ActiveDirectory module for this to work:

import-module ActiveDirectory

Also i have a couple of static variables:

$default_users_ou="OU=myusers,"
$ad_domain="my.domain.local"
$share_profiles="\\fileserver01\profiles"
$share_users="\\fileserver01\users"
$homeshare_drive="Z:"

And here we go:

function add_user([string]$username, [string]$plaintextpassword, [string]$group, [string]$givenname, [string]$surname, [string]$displayname, [bool]$enabled)
{
  # syntax: add_user f.deboer mypass$78 teacher "Boer, De" "Frank" "Boer, De, Frank" $true

  $check = get-aduser -Filter { samAccountName -eq $username }
  if($check -eq $null)
  {
    $user_password=ConvertTo-SecureString -string $plaintextpassword -asPlainText -Force
    $ad_user_path=$default_users_ou + (get-addomain).distinguishedname
    $loginscript=$group + ".bat"
    New-ADUser -Name $displayname -SamAccountName $username -UserPrincipal "$username@$ad_domain" -AccountPassword $user_password -CannotChangePassword $true -PasswordNeverExpires $true -Enabled $enabled -ProfilePath "$share_profiles\$username" -HomeDirectory $share_users\$username -HomeDrive $homeshare_drive -ScriptPath $loginscript -GivenName $givenname -Surname $surname -DisplayName $displayname -Path $ad_user_path
    write-host "- User Created - OK" -ForeGroundColor Green
  }
  else
  {
    write-host "- User allready exists" -ForeGroundColor Yellow    
  }
}