Created
March 26, 2014 17:08
-
-
Save ferventcoder/9788258 to your computer and use it in GitHub Desktop.
Adding a user to a group and managing Home Directory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
param ( | |
[parameter(Position=0)] | |
[alias("user")][string]$userName, | |
[alias("group")][string]$groupName=$null, | |
[alias("home")][string]$homeDirectory=$null | |
) | |
# there are some much simpler ways to do this with the Active-Directory Module | |
# like Get-ADUser, Set-ADUser, etc but it is not installed on Win2008 (non-R2) | |
# and below so we want to prefer what works natively for all Windows machines | |
if ($userName -eq $null) { return "Error: Please pass in a User Name" } | |
$groups = @() | |
$currentHomeDirectory = $null | |
$adsi = [ADSI]"WinNT://$env:COMPUTERNAME" | |
# these do not return null | |
#$adsiUser = [ADSI]("WinNT://$env:COMPUTERNAME/$userName") | |
#$adsiGroup = [ADSI]("WinNT://$env:COMPUTERNAME/$groupName") | |
$adsiUser = $adsi.Children | ?{$_.SchemaClassName -eq 'user'} | ?{$_.Name.ToString().ToLower() -eq "$userName".ToLower()} | |
if ($adsiUser -eq $null) { | |
# we are creating the user | |
$newUser = $adsi.Children.Add("$userName","user") | |
#$newUser.Invoke("Put", { "Description", "Test Group from .NET" }); | |
$newUser.CommitChanges() | |
$adsiUser = $newUser | |
} else { | |
$groups = $adsiUser.Groups() | %{$_.GetType().InvokeMember("Name", "GetProperty", $null, $_, $null)} | |
$currentHomeDirectory = $adsiUser.HomeDirectory.Value | |
} | |
if ($groupName -ne $null) { | |
# does the group exist? | |
$adsiGroup = $adsi.Children | ?{$_.SchemaClassName -eq 'group'} | ?{$_.Name.ToString().ToLower() -eq "$groupName".ToLower()} | |
if ($adsiGroup -eq $null) { | |
# create the group | |
$newGroup = $adsi.Children.Add("$groupName","group") | |
$newGroup.CommitChanges() | |
$adsiGroup = $newGroup | |
} | |
# is the user in the group? | |
if (! ($groups -contains "$groupName")) { | |
#put the user in the group | |
$adsiGroup.PSBase.Invoke("Add",$adsiUser.PSBase.Path) | |
} | |
} | |
# this may or may not be the correct thing to do because of HOMEDRIVE | |
if ($homeDirectory -ne $null) { | |
# does the user have the home directory set properly? | |
if ($currentHomeDirectory -ne $homeDirectory) { | |
$adsiUser.HomeDirectory = "$homeDirectory" | |
$adsiUser.CommitChanges() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
And hmmm, homedrive may or may not come into play here. I'm thinking about it way too much I know.