Modificar la información del usuario

Nos provee de una interfaz grafica que nos permite modificar la información del usuario.

<head>
<title>Staff details editor</title>
<HTA:APPLICATION
     APPLICATIONNAME="Staff details editor"
     SCROLL="YES"
     SINGLEINSTANCE="YES"
>
</head>

<script language="VBScript">
Const strDomainPath = "ou=Staff,dc=Contoso,dc=com"

Sub StaffSelected
  strStaffLDAP = StaffDropDown.Value
  Set objUser = GetObject(strStaffLDAP)

  ' If the employee has a manager defined, prefix the string with "LDAP://" to make it easier to compare against ADsPath strings
  If objUser.Manager<>"" Then
    strManagerLDAP = "LDAP://" & objUser.Manager
  End If

  ' Build the form HTML
  strSpanHTML = "<p>Job title: <input type=" & Chr(34) & "text" & Chr(34) & " name=" & Chr(34) & "JobTitle" & Chr(34) & " size=50><br>"
  strSpanHTML = strSpanHTML & "Manager: <select name=" & Chr(34) & "ManagerDropDown" & Chr(34) & "></select><br>"
  strSpanHTML = strSpanHTML & "Department: <input type=" & Chr(34) & "text" & Chr(34) & " name=" & Chr(34) & "Department" & Chr(34) & "></p>"
  strSpanHTML = strSpanHTML & "<p><input class=" & Chr(34) & "button" & Chr(34) & " type=" & Chr(34) & "button" & Chr(34) & " value=" & Chr(34) & "Save changes" & Chr(34) & " onClick=" & Chr(34) & "SaveButton" & Chr(34) & ">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  strSpanHTML = strSpanHTML & "<input class=" & Chr(34) & "button" & Chr(34) & " type=" & Chr(34) & "button" & Chr(34) & " value=" & Chr(34) & "Cancel" & Chr(34) & " onClick=" & Chr(34) & "CancelButton" & Chr(34) & "></p>"

  ' Plonk it onto the page
  Output.InnerHTML = strSpanHTML

  ' Build the Manager drop-down list
  ' We can do this by copying the staff list, since it is going to be the same list of names
  For Each objOption in StaffDropDown.Options
    Set objManager = Document.CreateElement("OPTION")
    objManager.Text = objOption.Text
    objManager.Value = objOption.Value
    ManagerDropDown.Add(objManager)
    If objManager.Value = strManagerLDAP Then
      objManager.Selected = True
    End If
  Next

  ' Fill in the other missing details
  JobTitle.Value = objUser.title
  Department.Value = objUser.department
End Sub

Sub SaveButton
  ' Just write all three values out
  strStaffLDAP = StaffDropDown.Value
  Set objUser = GetObject(strStaffLDAP)

  If JobTitle.value <> "" Then
    objUser.Put "title", JobTitle.Value
  End If
  If Department.value <> "" Then
    objUser.Put "department", Department.Value
  End If

  ' Manager is slightly more tricky as we have to strip the LDAP:// bit off the ADsPath
  strManager = ManagerDropDown.Value
  If strManager <> "" Then
    strManager = Mid(strManager, 8)
  End If
  objUser.Put "manager", strManager

  CancelButton
  On Error Resume Next
  objUser.SetInfo
  If Err.Number = 0 Then
    Output.InnerHTML = "<p>User information updated successfully.</p>"
  Else
    Output.InnerHTML = "<P>Error while setting user information: " & Err.Description & "</p>"
  End If
End Sub

Sub CancelButton
  Output.InnerHTML = ""

  ' Reset the staff picker to the Select... option
  bolSelected = True
  For Each objOption in StaffDropDown.Options
    objOption.Selected = bolSelected
    bolSelected = False
  Next
End Sub

Sub Window_Onload
  Const ADS_SCOPE_SUBTREE = 2

  self.ResizeTo 439,216

  Set objConnection = CreateObject("ADODB.Connection")
  Set objCommand =   CreateObject("ADODB.Command")
  objConnection.Provider = "ADsDSOObject"
  objConnection.Open "Active Directory Provider"
  Set objCommand.ActiveConnection = objConnection

  objCommand.Properties("Page Size") = 1000
  objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE 

  objCommand.CommandText = _
    "SELECT Name, ADsPath FROM 'LDAP://" & strDomainPath & "' WHERE objectCategory='user' ORDER BY Name"
  Set objRecordSet = objCommand.Execute

  objRecordSet.MoveFirst
  Do Until objRecordSet.EOF
    Set objOption = Document.createElement("OPTION")
    objOption.Text = objRecordSet.Fields("Name").Value
    objOption.Value = objRecordSet.Fields("ADsPath").Value
    StaffDropDown.Add(objOption)
    objRecordSet.MoveNext
  Loop
End Sub
</script>

<body>
Name: <select name="StaffDropDown" onChange="StaffSelected">
<option value="">Select ...</option>
</select>
<span id="Output"></span>
</body>

Exportar la información de usuario de Directorio Activo

A un ficherito csv separado por comas.

Visual Basic

'* description: export users from Active Directory to a comma separated text file.
'*  Use the text file to create users in a new AD with the accompanying import script.
'*              
'* author: Chris Pilling
'* date: 18 June 2008
'* edit the attributes exported to suit
'* after running it is probably best to delete lines from the text file for system generated accounts
 
Const ForAppending = 8
 
Set objRoot = GetObject("LDAP://RootDSE") 
strDNC = objRoot.Get("DefaultNamingContext") 
Set objDomain = GetObject("LDAP://" & strDNC)
 
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile("C:\AD_Users_Export.txt")
 
Call enummembers(objDomain) 
Sub enumMembers(objDomain) 
On Error Resume Next 
 
For Each objMember In objDomain  
 
If ObjMember.Class = "user" Then
 
'* edit the attributes you want to export here  
 
If Not (isempty(ObjMember.samAccountName)) Then 
    SamAccountName = ObjMember.samAccountName 
else 
    SamAccountName = "" 
End If
If Not (isempty(ObjMember.CN)) Then Cn = ObjMember.CN else Cn = "" End If
If Not (isempty(objMember.GivenName)) Then FirstName =objMember.GivenName else FirstName = "" End If
If Not (isempty(objMember.sn)) Then Lastname = ObjMember.sn else LastName = "" End If
If Not (isempty(objMember.UserPrincipalName)) Then 
    UserPrincipalName = objMember.UserPrincipalName 
    else 
    Name = "" 
End If
If Not (isempty(objMember.ProfilePath)) Then 
    ProfilePath = objMember.profilePath 
else 
    Profile = "" 
End If
If Not (isempty(ObjMember.homeDrive)) Then homeDrive = ObjMember.homeDrive else homeDrive = "" End If
If Not (isempty(ObjMember.homeDirectory)) Then 
    homeDirectory = ObjMember.homeDirectory 
else 
    homeDirectory = "" 
End If
If Not (isempty(ObjMember.Scriptpath)) Then 
    LoginScript = ObjMember.Scriptpath 
else 
    LoginScript = "" 
End If
 
set objFolder = nothing
set objFile = nothing
 
Set objTextFile = objFSO.OpenTextFile ("d:\AD_Users_Export.txt", ForAppending, True)
 
wscript.echo SamAccountName & "," & CN & "," & FirstName & "," & LastName & "," & UserPrincipalName & _
    "," & ProfilePath & ","  Homedrive & "," & Homedirectory & "," & LoginScript
 
strText1 = SamAccountName & "," & CN & "," & FirstName & "," & LastName & "," & UserPrincipalName & _
    "," & ProfilePath & "," & homedrive & "," & Homedirectory & "," & LoginScript

objTextFile.WriteLine(strText1) 
objTextFile.Close
 
End If 
  
If objMember.Class = "organizationalUnit" or OBjMember.Class = "container" Then 
enumMembers (objMember) 
End If 
Next 
End Sub

Crear cuentas de usuario

Vamos a ver como crear cuentas de usuario, incluyendo el buzón de correo, su directorio personal, su directorio de perfil. Necesitas 1) Exchange 2007 Management Shell Snapin; 2)Quest Active Roles management PS snapin; and, 3) xcacls.vbs en el mismo directorio que el script.  El script esta documentado en ingles, pero creo que esto no tiene que ser gran problema.

 

Write-Host "============ Create new domain user ============" -foregroundcolor Cyan
 
$username = Read-Host "Username "
## check if only letters were used
$regex = "^([a-zA-Z]+)$" ## only text, no spaces, no numbers
If ($username -notmatch $regex) {
      Write-Host "Invalid username specified. $username" -foregroundcolor Cyan
      break
}
 
## Check if there's already a user with this samAccountName
$dom = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$domainnb = "DOMAIN"
$root = $dom.GetDirectoryEntry()
 
$search = [System.DirectoryServices.DirectorySearcher]$root
$search.Filter = "(samAccountName=$username)"
$result = $search.FindOne()
 
if ($result -ne $null) {
      $user = $result.GetDirectoryEntry()
      Write-Host "There is already a useraccount $username." -foregroundcolor Cyan
      Write-Host "User found: " $user.distinguishedName -foregroundcolor Cyan
      break
}
 
$surname = read-host "User's last name (surname) "
$regex = "^([a-zA-Z'-]+)$" ## allows characters and dashes only
If ($surname -notmatch $regex) {
      Write-Host "Invalid surname specified. $surname" -foregroundcolor Cyan
      break
}
 
$tussenvoegsel = read-host "Infix. I.e. van den "
 
$name = Read-Host "User's first name "
 
$tel = Read-Host "Extension number "
$regex = "^(7|8)\d{3}$" ## 4 digit extension numbers, starting with 7 or 8 only.
If ($tel -notmatch $regex) {
      Write-Host "Invalid extension number specified. $tel" -foregroundcolor Cyan
      break
}
 
$passwd = Read-Host "Specify user's password "
## Password must be at least 6 characters, 
## no more than 15 characters, 
## and must include at least one upper case letter, 
## one lower case letter, and one numeric digit.
$regex = "^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,15}$"
If ($password -notmatch $regex) {
      Write-Host "Invalid password specified. $password" -foregroundcolor Cyan
      break
}
 
$DisplayName = "$surname, $name $tussenvoegsel"
$homeroot = "\\server1\mydocuments"
$profileroot = "\\server1\profiles"
 
Write-Host "================================================" -foregroundcolor Cyan
Write-Host "Creating user $DisplayName using New-Mailbox cmdlet.." -foregroundcolor Cyan
 
New-Mailbox -Name $DisplayName.Trim() `
      -Database "EXCHSRVR\Mailbox Store\Mailbox Database" `
      -Password (convertto-securestring $passwd -asplaintext -force) `
      -UserPrincipalName $username@DOMAIN.LOCAL `
      -ActiveSyncMailboxPolicy "Default" `
      -Alias $username `
      -Confirm `
      -DisplayName ($DisplayName.Trim()) `
      -FirstName "$name $tussenvoegsel" `
      -LastName $surname `
      -OrganizationalUnit "DOMAIN.LOCAL/OU Users " `
      -ResetPasswordOnNextLogon $true `
      -SamAccountName $username
 
## Wait for DC's to pick up change
Start-Sleep -s 10
 
## Modify user properties
Get-QADUser $username | Set-QADUser -PhoneNumber $tel `
                                   -UserPassword $passwd
 
Write-Host "================================================" -foregroundcolor Cyan
 
## Create home directory with permissions
If ( !(Test-Path -Path "$homeroot\$username" -PathType Container) ) {
      ## Doesn't exist so create it.
      Write-Host "home directory doesn't exist. Creating home directory." -ForegroundColor Cyan
      
      ## Create the directory
      New-Item -path $homeroot -Name $username -ItemType Directory
      $homedir = "$homeroot\$username"
      
      ## Modify  Permissions on homedir
 
      ## Instead of using the .NET approach of setting NTFS permissions, using xcacls is quicker:
      cscript xcacls.vbs $homedir /E /G `"$nbdomain\$username`":M
      
      ## The .NET approach - remmed out
      ## To list available rights options, run: [system.enum]::getnames([System.Security.AccessControl.FileSystemRights])
      ## To list available inheritance flags, run: [system.enum]::getnames([System.Security.AccessControl.InheritanceFlags])
      ## Idem for Propagation flags.
      #$newrights = [System.Security.AccessControl.FileSystemRights]"Modify"
      #$InheritanceFlag = [System.Security.AccessControl.InheritanceFlags]::"ObjectInherit"
      #$PropagationFlag = [System.Security.AccessControl.PropagationFlags]::"InheritOnly"
      #$Typ = [System.Security.AccessControl.AccessControlType]::Allow
      #$ID = new-object System.Security.Principal.NTAccount($domainnb + "\" + $username)
      #$SecRule = new-object System.Security.AccessControl.FileSystemAccessRule($ID, $newrights, $InheritanceFlag, PropagationFlag, $Typ)
      
      #$myACL = Get-Acl -Path $homedir
      #$myACL.AddAccessRule($SecRule) 
      #Set-ACL -AclObject $myACL $homedir
}
Else {
      Write-Host "home directory already exists. Script end." -ForegroundColor Cyan
      Break
}
 
## Create Profile directory with permissions
If ( !(Test-Path -Path "$profileroot\$username" -PathType Container) ) {
      ## Doesn't exist so create it.
      Write-Host "profile directory doesn't exist. Creating profile directory." -ForegroundColor Cyan
      
      ## Create the directory
      New-Item -path $profileroot -Name $username -ItemType Directory
      $profiledir = "$profileroot\$username"
 
      ## Modify Permissions on profile dir
 
      ## Instead of using the .NET approach of setting NTFS permissions, using cacls is quicker:
      cscript xcacls.vbs $profiledir /E /G `"$nbdomain\$username`":M
      
      ## The .NET approach - remmed out
      ## To list available rights options, run: [system.enum]::getnames([System.Security.AccessControl.FileSystemRights])
      ## To list available inheritance flags, run: [system.enum]::getnames([System.Security.AccessControl.InheritanceFlags])
      ## Idem for Propagation flags.
      #$newrights = [System.Security.AccessControl.FileSystemRights]"Modify"
      #$InheritanceFlag = [System.Security.AccessControl.InheritanceFlags]::"None"
      #$PropagationFlag = [System.Security.AccessControl.PropagationFlags]::"None"
      #$Typ = [System.Security.AccessControl.AccessControlType]::Allow
      #$ID = new-object System.Security.Principal.NTAccount($domainnb + "\" + $username)
      #$SecRule = new-object System.Security.AccessControl.FileSystemAccessRule($ID, $newrights, $InheritanceFlag, PropagationFlag, $Typ)
      #$myACL = Get-Acl -Path $profiledir
      #$myACL.AddAccessRule($SecRule) 
      #Set-ACL -AclObject $myACL $profiledir
}
Else {
      Write-Host "profile directory already exists. Script end." -ForegroundColor Cyan
      Break
}
 
## Modify user properties
Get-QADUser $username | Set-QADUser -ObjectAttributes @{homeDrive='H:';homeDirectory=$homedir;profilePath=$profiledir}
 
## User created. Listing properties
$info = Get-QADUser $username -IncludeAllProperties | fl DN,Name,DisplayName,userPrincipalName, `
      samAccountName,givenName,sn,homeDrive,homeDirectory, `
      ProfilePath,telephoneNumber,email
 
Write-Host "User created with the following properties: " -ForegroundColor Cyan
$info
 
Write-Host "================= Script End =================" -foregroundcolor Cyan

Utilizar WIFI con Windows Server 2008 R2 e Hyper-v

Seguro que a los que se atreven a llevar Windows Server 2008 R2 instalado en su portátil, con el rol de Hyper-V activado, seguro que echareis de menos la posibilidad de poder crear una red virtual con el adaptador wifi de nuestro equipo. Pues bien esta sería una manera de hacerlo:

Iniciemos la consola de Hyper-V

Administrador de Redes Virtuales

Seleccionemos el Administrador de Redes Virtuales, en el panel de acciones de la derecha

Seleccionamos Nueva Red Virtual, seleccionamos la opción de Interna y pulsamos en Añadir

Redes Virtuales

Le ponemos el nombre a la nueva red virtual y aceptamos

Nueva Red Virtual

Ahora llegamos al punto de compartir nuestra conexión a internet a través de esta red

Abrimos el Centro de Redes y Recursos Compartidos

Centro de Redes y Recursos Compartidos

Seleccionamos Cambiar la configuración del adaptador

Localizamos nuestro adaptador wifi, pulsamos el botón derecho del ratón encima de él y seleccionamos opciones

Cambiar la Configuración del Adaptador

Cambiamos a la pestaña de Uso Compartido

Marcamos la opción de Permitir que los usuarios de otras redes se ….

Especificamos el adaptador de red

Conexión Compartida a Internet

y aceptamos

Ahora ya podemos añadir a nuestra máquinas virtuales, la opción de tener red interna que hemos definido y a través de la cual podremos usar el adaptador wifi.

BBT2+