Búsqueda de sitios web

Administrar usuarios de Active Directory a través de Set-ADUser


Introducción

Los administradores tienen varias opciones para administrar las propiedades de los usuarios de Active Directory. La consola Usuarios y computadoras de Active Directory (ADUC) es conveniente para realizar algunos cambios básicos, como modificar la descripción de un usuario o la ubicación de la oficina.

Sin embargo, para obtener más funciones, considere usar PowerShell. Este artículo ilustra cómo abordar muchos casos de uso comunes con el cmdlet de PowerShell Set-ADUser.

Cmdlet Set-ADUser

Con el cmdlet Set-ADUser, puede modificar muchas propiedades de los usuarios de Active Directory.

Tenga en cuenta que para ejecutar cmdlets de PowerShell desde una computadora con Windows que no sea un controlador de dominio, primero debe importar el módulo de Active Directory para Windows PowerShell.

Establecer parámetros de usuario AD

La siguiente tabla describe los parámetros del cmdlet Set-ADUser que puede usar para cambiar las propiedades de un usuario.

Para ver la lista completa de parámetros para el cmdlet Set-ADUser, ejecute el siguiente cmdlet:

Get-help Set-ADUser
ParameterDescription
(A)
-AccountExpirationDateSets the account expiration date of the user object.
-AccountNotDelegatedSpecifies whether the user’s security context is delegated to a service.
-AddAdds one or more values to a property that cannot be changed using a cmdlet parameter (i.e., properties for which no parameter is available).
-AllowReversiblePasswordEncryptionSpecifies whether the account is allowed to use reversible password encryption.
-AuthenticationPolicySpecifies an authentication policy object for Active Directory Domain Services.
-AuthenticationPolicySiloSets the authentication policy silo object for Active Directory Domain Services.
-AuthTypeSpecifies the authentication method to use: Negotiate (or 0) or Basic (or 1).
(C)
-CannotChangePasswordSpecifies whether the user can change the account’s password.
-CertificatesSpecifies the account’s DER-encoded X.509v3 certificates, such as the public-key certificates issued to this account by the Microsoft Certificate Service.
-ChangePasswordAtLogonSpecifies whether the user must change their password at the next login.
-CitySpecifies the city or town of the user.
-ClearClears one or more values of an attribute that cannot be changed using a cmdlet parameter (i.e., attributes for which no parameter is available).
-CompanySets the company attribute of the user account.
-CompoundIdentitySupportedSpecifies whether a user’s account supports Kerberos service tickets, which include the user’s device’s authorization data.
-ConfirmPrompts you for confirmation before running the cmdlet.
-CountrySets the country or region code for the user account.
-CredentialSpecifies the user account credentials to use to run the cmdlet. Unless the cmdlet is launched from an Active Directory PowerShell provider drive, the default credentials are those of the logged-on user.
(D)
-DepartmentSpecifies the department of the user.
-DescriptionSpecifies the description of the user account.
-DisplayNameSpecifies the display name of the user.
-DivisionSpecifies the division of the user.
(E)
-EmailAddressSpecifies the email address of the user.
-EmployeeIDSpecifies the employee ID of the user.
-EmployeeNumberSpecifies the employee number of the user.
-EnabledSpecifies whether the user account is enabled or disabled.
(F)
–FaxSpecifies the fax number of the user.
(G)
-GivenNameSpecifies the first name of the user.
(H)
-HomeDirectorySpecifies the home directory of the user account.
-HomeDriveSets the UNC path of the home directory of the user account.
(I)
-IdentitySpecifies the user account whose properties need to be changed.
A user can be identified by its:

• Distinguished Name (DN)
• GUID
• Security Identifier (SID)
• Security Account Manager (SAM) account name

Alternatively, you can feed a user object through the pipeline to the Identity parameter, or set it to an object variable. For example, you can use the Get-ADUser cmdlet to retrieve a user object, which can be passed via the pipeline to the Set-ADUser cmdlet.
-InitialsSpecifies the initials of the user.
-InstanceSpecifies an ADUser object that identifies the Active Directory user object to be changed and the modifications to be made to that object. When this parameter is supplied, any changes made to the ADUser object are also propagated to the appropriate Active Directory object. Only the object properties that have changed are updated by the cmdlet.
This parameter is mainly used when you make changes to an object’s properties with a CSV or script using variables. You call the object, make changes to the desired properties, then use Set-ADUser with the -Instance parameter for those changes to take effect.
(K)
-KerberosEncryptionTypeSpecifies whether the user account is compatible with Kerberos encryption.
(L)
-LogonWorkstationsSpecifies the logon workstations of the user.
(M)
-ManagerSpecifies the manager of the user.
-MobilePhoneSpecifies the mobile phone number of the user.
(O)
-OfficeSpecifies the physical office location of the user.
-OfficePhoneSpecifies the office phone number of the user.
-OrganizationSpecifies the organization of the user.
-OtherNameSpecifies any other name property of the user.
(P)
-PartitionSpecifies the distinguished name of an Active Directory partition. The distinguished name must be one of the naming contexts on the current directory server.
-PassThruReturns an object that represents the object you are working with. By default, this cmdlet does not generate any output.
-PasswordNeverExpiresSpecifies whether the account password never needs to be updated.
-PasswordNotRequiredSpecifies that the user account does not need a password.
-POBoxSpecifies the PO box of the user.
-PostalCodeSpecifies the postal code of the user.
-ProfilePathSpecifies the profile path of the user.
(R)
-RemoveRemoves one or more values of the properties that cannot be modified using a cmdlet parameter (i.e., properties for which no parameter is available).
-ReplaceReplaces one or more values of the properties that cannot be modified using a cmdlet parameter (i.e., properties for which no parameter is available).
This parameter is mostly used for more than one property value, or multiline attributes, particularly those for which there is no parameter available, but you can also use it for properties for which a specific parameter is available.
(S)
-SamAccountNameProvides the security account manager (SAM) account name of the user on creation.
-ScriptPathSpecifies a path to the user’s log on script.
-ServerSpecifies the AD DS instance to connect to.
-ServicePrincipalNamesSpecifies the service principal name of the user.
-SmartcardLogonRequiredSpecifies whether smart card logon is required for the user.
-StateSpecifies the state of the user.
-StreetAddressSpecifies the street address of the user.
(T)
-TitleSpecifies the user’s job title.
-TrustedForDelegationSpecifies whether the account is trusted for Kerberos delegation. A service running under a trusted Kerberos delegation account can take on the identity of the client requesting the service.
(U)
-UserPrincipalNameSpecifies the user principal name (UPN) property of a user in the format testuser@testdomain.com.
(W)
-WhatIfShows the output that would result from running the cmdlet, without actually running it.

Comando detallado

De forma predeterminada, el cmdlet Set-ADUser no produce ningún resultado. Para obtener información sobre lo que hace el cmdlet, utilice el modificador /verbose.

Verbose se usa principalmente con variables y scripts, aunque a veces también se usa con cmdlets.

Ejemplos de usuario de Set-AD

Los siguientes son ejemplos de uso del cmdlet Set-ADUser.

  • Cambiar los atributos de estado y oficina de un usuario
  • Cambiar el título de un usuario
  • Especificar el administrador de un usuario
  • Reemplazar propiedades de usuario
  • Modificar múltiples atributos para múltiples usuarios, ejemplo 1
  • Modificar múltiples atributos para múltiples usuarios, ejemplo 2
  • Modificar múltiples atributos para múltiples usuarios, ejemplo 3
  • Modificar múltiples atributos para múltiples usuarios usando un archivo CSV
  • Utilice credenciales alternativas
  • Borrar un valor de atributo
  • Deshabilitar cuentas de usuario de AD
  • Forzar un cambio de contraseña en el próximo inicio de sesión
  • Modificar atributos que pueden tener múltiples valores

Cambiar los atributos de estado y oficina de un usuario

El siguiente cmdlet establecerá los valores de los atributos Oficina y Estado del objeto AbbeyCrawford:

Set-ADUser -Identity AbbeyCrawford -Office 'Atlanta' -State 'GA'

Aquí puede ver que los atributos de Oficina y Estado del usuario se han configurado según lo especificado:

Cambiar el título de un usuario

El siguiente cmdlet actualizará la propiedad Título del objeto de usuario AbbeyCrawford:

Set-ADUser -Identity AbbeyCrawford -Title 'CIO'

Para verificar que la actualización fue exitosa, use el siguiente comando:

Get-ADUser -Identity AbbeyCrawford -Properties Name,Department,title | Select-Object -Property Name,Department,title

Especificar el administrador de un usuario

El siguiente comando usa Get-ADUser para obtener el objeto de usuario de AD AbbeyCrawford, que se pasa al cmdlet Set-ADUser, que actualiza su atributo Manager:

Get-ADUser -Identity "AbbeyCrawford" | Set-ADUser -Manager "AbbeyEckels"

Puede confirmar el cambio utilizando el siguiente cmdlet:

Get-ADUser -Identity AbbeyCrawford -Properties manager | Select-Object -Property manager

Reemplazar propiedades de usuario

Para reemplazar el valor actual de una propiedad con un nuevo valor, use el parámetro Reemplazar. Utilice el nombre para mostrar LDAP para identificar el objeto que se va a modificar.

Este comando actualiza el título y la dirección de correo electrónico del usuario AbbeyCrawford:

Set-ADUser -Identity Abbey.Crawford -Replace @{title="manager";mail="AbbeyCrawford@corp.net"}

Puede verificar los cambios usando este cmdlet:

Get-ADUser -Identity AbbeyCrawford -Properties title,mail | Select-Object -Property title,mail

Modificar múltiples atributos para múltiples usuarios, ejemplo 1

El siguiente script actualiza varias propiedades para un conjunto particular de usuarios:

  • El primer comando busca usuarios de AD de la unidad organizativa de ingeniería.
  • La salida se canaliza al segundo comando, que reemplaza tres atributos para todos esos usuarios.
Get-ADUser -SearchBase " OU=Engineering,OU=Versacorp,DC=corp,DC=com" -filter * -Properties Department,Company,l,st | Set-ADUser -Replace @{Department=”Engineering”;Company="VersaCorp";l=”San Francisco”;St=”CA”}

Puede comprobar los resultados utilizando el siguiente script:

Get-ADUser -SearchBase "OU=Engineering,OU=Versacorp,DC=corp,DC=com" -Filter * -Properties DisplayName,Department,Company,l,st | select-object -property DisplayName,Department,Company,l,St

Modificar múltiples atributos para múltiples usuarios, ejemplo 2

De manera similar, el siguiente script actualiza el atributo DisplayName de los usuarios en la unidad organizativa de ingeniería:

Get-ADUser -Filter 'Name -like "*"' -SearchBase ”OU=Engineering,OU=Versacorp,DC=corp,DC=com”  -Properties DisplayName | % {Set-ADUser $_ -DisplayName ($_.GivenName + ' ' + $_.SurName)}

Para inspeccionar el resultado de este cmdlet, ejecute el siguiente script:

Get-ADUser -SearchBase "OU=Engineering,OU=Versacorp,DC=corp,DC=com" -Filter * -Properties DisplayName | select-object -property DisplayName

Modificar múltiples atributos para múltiples usuarios, ejemplo 3

Supongamos que todos los usuarios de su oficina de Boston están siendo reubicados en la oficina de Worcester, por lo que necesita actualizar el atributo de Office para todos ellos.

Primero, creamos una variable con los usuarios apropiados:

$BostonUsers = Get-ADUser -Filter "physicalDeliveryOfficeName -eq 'Boston'" -Property *

Para consultar esta lista de usuarios y sus oficinas, podemos usar este cmdlet:

$BostonUsers | Select-Object Name, Office

El siguiente paso es actualizar la ubicación de la oficina de cada usuario. Usaremos nuevamente un bucle ForEach:

ForEach ($User in $BostonUsers){Set-ADUser -Identity $User -Office ‘Worcester’}

Finalmente, para verificar que la actualización fue exitosa, podemos usar el cmdlet Get-ADUser para mostrar una lista de los usuarios en la oficina de Worcester:

Get-ADUser -Filter "physicalDeliveryOfficeName -eq 'Worcester'" -Property * | Select-Object Name,Office

Modificar múltiples atributos para múltiples usuarios usando un archivo CSV

Alternativamente, puede usar un archivo CSV para proporcionar la lista de usuarios de AD cuyas propiedades desea modificar. Digamos que tiene el siguiente archivo CSV:

Podemos crear la variable “$Users” para recuperar la información sobre los usuarios del archivo CSV:

$users = Import-csv -Path c:\hr.csv

Luego podemos usar el siguiente script para realizar los cambios deseados; el bucle "ForEach" recorre en iteración todos los objetos de usuario y actualiza sus propiedades de departamento y título:

foreach ($user in $users) {
Get-ADUser -Filter "employeeID -eq '$($user.employeeID)'" -Properties * -SearchBase " OU=Engineering,OU=Versacorp,DC=corp,DC=com" |Set-ADUser -department $($user.department) -title $($user.title) 
}

Aunque puede ejecutar un script línea por línea en Windows PowerShell, se recomienda utilizar Windows PowerShell ISE para scripts más grandes, como se muestra a continuación:

Windows PowerShell ISE tiene dos secciones:

  • Editor de guiones
  • Consola PowerShell

La siguiente imagen muestra cómo se ejecuta el cmdlet o script. Hay un botón en la barra de herramientas para reproducir y detener el script.

Utilice credenciales alternativas

De forma predeterminada, Set-ADUser se ejecuta en el contexto del usuario que ha iniciado sesión actualmente. Para especificar diferentes credenciales, utilice el parámetro -Credential.

El siguiente comando utiliza Get-Credential para generar un objeto de credencial:

$credential = Get-Credential

Luego podemos pasar ese objeto de credencial al cmdlet Set-ADUser usando el parámetro -Credential:

Set-ADUser -Identity AbbeyCrawford -Title “Senior Software Developer” -Credential $credential

Borrar un valor de atributo

Para borrar el valor de un atributo de usuario de Active Directory, utilice el parámetro -Clear. El siguiente script utiliza el cmdlet Get-ADUser para recuperar usuarios de la unidad organizativa especificada y pasa el resultado a Set-ADUser, que borra el atributo Departamento:

Get-ADUser -filter * -SearchBase " OU=Engineering,OU=Versacorp,DC=corp,DC=com" | Set-AdUser -clear department

Para comprobar los resultados, utilice el siguiente script:

Get-ADUser -SearchBase "OU=Engineering,OU=Versacorp,DC=corp,DC=com" -Filter * -Properties DisplayName | select-object -property DisplayName,Department

Deshabilitar cuentas de usuario de AD

Siempre que un usuario abandona la organización, es vital asegurarse de que su cuenta esté desactivada.

Primero, usaremos el cmdlet Get-ADUser para verificar si la cuenta del usuario saliente está habilitada:

Get-ADUser -Identity AbbeyCrawford -Properties Enabled | Select Enabled

El resultado muestra que la cuenta está activa (Get-ADUser Enabled es True), por lo que debemos desactivarla. Podemos utilizar el siguiente script; el primer comando obtiene la propiedad habilitada del usuario de AD y el segundo comando deshabilita la cuenta de usuario:

Get-ADUser -Identity AbbeyCrawford -Properties Enabled | Set-ADUser -Enabled $False

Podemos comprobar los resultados ejecutando el siguiente cmdlet:

Get-ADUser -Identity AbbeyCrawford -Properties DisplayName,Enabled | select-object -Property DisplayName,Enabled

Forzar un cambio de contraseña en el próximo inicio de sesión

El siguiente comando modificará el valor de la propiedad UserAccountControl para todos los usuarios en la unidad organizativa especificada, obligándolos a cambiar su contraseña en el siguiente inicio de sesión:

Get-ADUser -Filter *  -SearchBase "OU=Test,DC=corp,DC=com" | Set-ADUser -ChangePasswordAtLogon $true

La siguiente imagen muestra la casilla de verificación que acabamos de configurar:

Modificar atributos que pueden tener múltiples valores

Algunas propiedades, como ProxyAddress y OtherTelephone, pueden tener varios valores. Para modificarlos, utilice los parámetros -Agregar y -Eliminar de Set-ADUser.

Para eliminar un valor único, especifique la propiedad y el valor que desea eliminar:

Set-ADUser -Identity AbbeyCrawford -Remove @{proxyAddresses="AbbeyCrawford@hotmail.com"}

Para verificar el resultado, use el cmdlet Get-ADUser:

Get-ADUser -Identity AbbeyCrawford -Properties manager | Select-Object -Property manager

Observe que AbbeyCrawford@hotmail.com se ha eliminado de la lista ProxyAddresses.

Para agregar varios valores, use una lista separada por comas, como se muestra a continuación:

Set-ADUser -Identity AbbeyCrawford -Add @{proxyAddresses="AbbeyCrawford@corp.net","AbbeyCrawford@hotmail.com"}

Para comprobar los resultados, utilice el cmdlet Get-ADUser:

Get-ADUser -Identity AbbeyCrawford -Properties proxyaddresses | Select-Object -Property proxyaddresses

Alternativas a PowerShell para administrar usuarios de AD

Shell de administración de Netwrix GroupID

Netwrix GroupID Shell es una herramienta de línea de comandos que facilita la administración de objetos en Active Directory y almacenes de identidades basados en Azure, así como la realización de otras actividades administrativas que puede realizar con PowerShell.

Como puede ver aquí, los cmdlets de Netwrix GroupID Shell son similares a los cmdlets de PowerShell:

Aquí está el cmdlet Netwrix GroupID Shell que es similar a Set-ADUser:

Portal de autoservicio Netwrix GroupID

Con Netwrix GroupID, puede crear rápidamente portales basados en web que permitan a los técnicos del servicio de asistencia técnica y a los usuarios empresariales realizar determinadas tareas sin la ayuda del equipo de TI. Los usuarios pueden:

  • buscar en el directorio
  • Actualizar sus perfiles
  • Crear y actualizar objetos y grupos de directorio.

Cuando los usuarios administran su propia información, los datos son más precisos y confiables. Sin embargo, los administradores mantienen un control total sobre la integridad de los datos porque deciden qué pueden ver y modificar los usuarios a través del portal. Los administradores también pueden crear flujos de trabajo que actúen como un sistema de auditoría para garantizar que se ingresen los datos correctos antes de confirmar los cambios en el directorio.

Estos son algunos de los atributos de usuario que se pueden actualizar a través del portal de autoservicio:

Artículos relacionados