Compartir a través de


Capítulo 3: Detección de objetos, propiedades y métodos

PowerShell es un lenguaje de scripting orientado a objetos. Representa los estados de datos y del sistema mediante objetos estructurados derivados de clases de .NET definidas en .NET Framework. Al aprovechar .NET Framework, PowerShell ofrece acceso a diversas funcionalidades del sistema, incluidas las clases sistema de archivos, registro y Instrumental de administración de Windows (WMI). PowerShell también tiene acceso a la biblioteca de clases de .NET Framework, que contiene una amplia colección de clases que puede usar para desarrollar scripts sólidos de PowerShell.

En PowerShell, cada elemento o estado es una instancia de un objeto que se puede explorar y manipular. El Get-Member cmdlet es una de las herramientas principales proporcionadas por PowerShell para la detección de objetos, que revela las características de un objeto. En este capítulo se explora cómo PowerShell aprovecha los objetos y cómo puede detectar y manipular estos objetos para simplificar los scripts y administrar los sistemas de forma más eficaz.

Requisitos previos

Para seguir los ejemplos específicos de este capítulo, asegúrese de que el equipo del entorno de laboratorio forme parte del dominio de Active Directory del entorno de laboratorio. También debe instalar el módulo de PowerShell de Active Directory incluido con las Herramientas de administración remota de Windows Server (RSAT). Si usa la compilación 1809 o posterior de Windows 10, incluido Windows 11, puede instalar RSAT como una característica de Windows.

Nota:

Active Directory no es compatible con las ediciones de Windows Home.

  • Para obtener información sobre cómo instalar RSAT, consulte Módulos de administración de Windows.
  • Para versiones anteriores de Windows, consulte RSAT para Windows.

Get-Member

Get-Member proporciona información sobre los objetos, las propiedades y los métodos asociados a los comandos de PowerShell. Puede canalizar cualquier comando de PowerShell que genere una salida basada en objetos a Get-Member. Cuando canaliza la salida de un comando a Get-Member, revela la estructura del objeto devuelto por el comando, detallando sus propiedades y métodos.

  • Propiedades: los atributos de un objeto .
  • Métodos: las acciones que puede realizar en un objeto .

Para ilustrar este concepto, considere la licencia de conducir como analogía. Al igual que cualquier objeto, la licencia de conducir tiene propiedades, como el color del ojo, que normalmente incluye blue y brown valores. En cambio, los métodos representan acciones que puede realizar en el objeto . Por ejemplo, Revoke es un método que el Departamento de Vehículos Motor puede realizar en una licencia de conducir.

Propiedades

Para recuperar detalles sobre el servicio hora de Windows en el sistema mediante PowerShell, use el Get-Service cmdlet .

Get-Service -Name w32time

Los resultados incluyen las propiedades Status, Name y DisplayName . La propiedad Status indica que el servicio es Running. El valor de la propiedad Name es w32timey el valor de la propiedad DisplayName es Windows Time.

Status   Name               DisplayName
------   ----               -----------
Running  w32time            Windows Time

Para enumerar todas las propiedades y métodos disponibles para Get-Service, canalice a Get-Member.

Get-Service -Name w32time | Get-Member

Los resultados muestran que la primera línea contiene un fragmento de información significativa. TypeName identifica el tipo de objeto devuelto, que en este ejemplo es un objeto System.ServiceProcess.ServiceController . Este nombre suele abreviarse en la última parte de TypeName, como ServiceController, en este ejemplo.

   TypeName: System.ServiceProcess.ServiceController

Name                      MemberType    Definition
----                      ----------    ----------
Name                      AliasProperty Name = ServiceName
RequiredServices          AliasProperty RequiredServices = ServicesDepend...
Disposed                  Event         System.EventHandler Disposed(Syst...
Close                     Method        void Close()
Continue                  Method        void Continue()
CreateObjRef              Method        System.Runtime.Remoting.ObjRef Cr...
Dispose                   Method        void Dispose(), void IDisposable....
Equals                    Method        bool Equals(System.Object obj)
ExecuteCommand            Method        void ExecuteCommand(int command)
GetHashCode               Method        int GetHashCode()
GetLifetimeService        Method        System.Object GetLifetimeService()
GetType                   Method        type GetType()
InitializeLifetimeService Method        System.Object InitializeLifetimeS...
Pause                     Method        void Pause()
Refresh                   Method        void Refresh()
Start                     Method        void Start(), void Start(string[]...
Stop                      Method        void Stop()
WaitForStatus             Method        void WaitForStatus(System.Service...
CanPauseAndContinue       Property      bool CanPauseAndContinue {get;}
CanShutdown               Property      bool CanShutdown {get;}
CanStop                   Property      bool CanStop {get;}
Container                 Property      System.ComponentModel.IContainer ...
DependentServices         Property      System.ServiceProcess.ServiceCont...
DisplayName               Property      string DisplayName {get;set;}
MachineName               Property      string MachineName {get;set;}
ServiceHandle             Property      System.Runtime.InteropServices.Sa...
ServiceName               Property      string ServiceName {get;set;}
ServicesDependedOn        Property      System.ServiceProcess.ServiceCont...
ServiceType               Property      System.ServiceProcess.ServiceType...
Site                      Property      System.ComponentModel.ISite Site ...
StartType                 Property      System.ServiceProcess.ServiceStar...
Status                    Property      System.ServiceProcess.ServiceCont...
ToString                  ScriptMethod  System.Object ToString();

Observe que al canalizar Get-Service a Get-Member, hay más propiedades de las que se muestran de forma predeterminada. Aunque estas propiedades adicionales no se muestran de forma predeterminada, puede seleccionarlas canalizando y Select-Object usando el parámetro Property . En el ejemplo siguiente se seleccionan todas las propiedades canalizando los resultados de Get-Service a Select-Object y especificando el * carácter comodín como valor para el parámetro Property .

Get-Service -Name w32time | Select-Object -Property *

De forma predeterminada, PowerShell devuelve cuatro propiedades como una tabla y cinco o más como una lista. Sin embargo, algunos comandos aplican formato personalizado para invalidar el número predeterminado de propiedades que se muestran en una tabla. Puede usar Format-Table y Format-List invalidar estos valores predeterminados manualmente.

Name                : w32time
RequiredServices    : {}
CanPauseAndContinue : False
CanShutdown         : True
CanStop             : True
DisplayName         : Windows Time
DependentServices   : {}
MachineName         : .
ServiceName         : w32time
ServicesDependedOn  : {}
ServiceHandle       :
Status              : Running
ServiceType         : Win32OwnProcess, Win32ShareProcess
StartType           : Manual
Site                :
Container           :

También se pueden seleccionar propiedades específicas mediante una lista separada por comas como valor del parámetro Property .

Get-Service -Name w32time |
    Select-Object -Property Status, Name, DisplayName, ServiceType
 Status Name    DisplayName                         ServiceType
 ------ ----    -----------                         -----------
Running w32time Windows Time Win32OwnProcess, Win32ShareProcess

Puede usar caracteres comodín al especificar nombres de propiedad con Select-Object.

En el ejemplo siguiente, use Can* como uno de los valores del parámetro Property para devolver todas las propiedades que comienzan por Can. Entre ellas se incluyen CanPauseAndContinue, CanShutdown y CanStop.

Get-Service -Name w32time |
    Select-Object -Property Status, DisplayName, Can*

Observe que hay más propiedades enumeradas de las que se muestran de forma predeterminada.

Status              : Running
DisplayName         : Windows Time
CanPauseAndContinue : False
CanShutdown         : True
CanStop             : True

Métodos

Los métodos son acciones que puede realizar en un objeto . Use el parámetro MemberType para restringir los resultados de Get-Member para mostrar solo los métodos de Get-Service.

Get-Service -Name w32time | Get-Member -MemberType Method

Como puede ver, hay varios métodos.

   TypeName: System.ServiceProcess.ServiceController

Name                      MemberType Definition
----                      ---------- ----------
Close                     Method     void Close()
Continue                  Method     void Continue()
CreateObjRef              Method     System.Runtime.Remoting.ObjRef Creat...
Dispose                   Method     void Dispose(), void IDisposable.Dis...
Equals                    Method     bool Equals(System.Object obj)
ExecuteCommand            Method     void ExecuteCommand(int command)
GetHashCode               Method     int GetHashCode()
GetLifetimeService        Method     System.Object GetLifetimeService()
GetType                   Method     type GetType()
InitializeLifetimeService Method     System.Object InitializeLifetimeServ...
Pause                     Method     void Pause()
Refresh                   Method     void Refresh()
Start                     Method     void Start(), void Start(string[] args)
Stop                      Method     void Stop()
WaitForStatus             Method     void WaitForStatus(System.ServicePro...

Puede usar el método Stop para detener un servicio de Windows. Debe ejecutar este comando desde una sesión de PowerShell con privilegios elevados.

(Get-Service -Name w32time).Stop()

Consulte el estado del servicio hora de Windows para confirmar que está detenido.

Get-Service -Name w32time
Status   Name               DisplayName
------   ----               -----------
Stopped  w32time            Windows Time

Puede usar métodos con moderación, pero debe conocerlos. A veces, encontrará Get-* comandos sin un comando correspondiente Set-* . A menudo, puede encontrar un método para realizar una Set-* acción en este escenario. El Get-SqlAgentJob cmdlet del módulo sqlServer de PowerShell es un ejemplo excelente. No existe ningún cmdlet correspondiente Set-* , pero puede usar un método para completar la misma tarea. Para obtener más información sobre el módulo de PowerShell sqlServer e instrucciones de instalación, consulte la introducción a SQL Server PowerShell.

Otro motivo para tener en cuenta los métodos es que algunos usuarios de PowerShell asumen que no puede realizar cambios destructivos con Get-* comandos, pero en realidad pueden causar problemas graves si se usan incorrectamente.

Una mejor opción es usar un cmdlet dedicado si existe para realizar una acción. Por ejemplo, use el Start-Service cmdlet para iniciar el servicio hora de Windows.

De forma predeterminada, , Start-Servicecomo el método Start de Get-Service, no devuelve ningún resultado. Sin embargo, una de las ventajas de usar un cmdlet es que a menudo proporciona funcionalidades adicionales que no están disponibles con un método.

En el ejemplo siguiente, use el parámetro PassThru , que hace que un cmdlet que normalmente no genere la salida para generar la salida.

Dado que PowerShell no participa en el Control de acceso de usuario (UAC), debe ejecutar comandos que requieran elevación, como Start-Service, desde una sesión de PowerShell con privilegios elevados.

Get-Service -Name w32time | Start-Service -PassThru
Status   Name               DisplayName
------   ----               -----------
Running  w32time            Windows Time

Nota:

Al trabajar con cmdlets de PowerShell, es importante evitar realizar suposiciones sobre su salida.

Para recuperar información sobre el proceso de PowerShell que se ejecuta en el equipo del entorno de laboratorio, use el Get-Process cmdlet .

Get-Process -Name powershell
Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
-------  ------    -----      -----     ------     --  -- -----------
    710      31    55692      70580       0.72   9436   2 powershell

Para determinar las propiedades disponibles, canalice Get-Process a Get-Member.

Get-Process -Name powershell | Get-Member

Al usar el Get-Process comando , es posible que observe que faltan algunas propiedades mostradas de forma predeterminada al ver los resultados de Get-Member. Este comportamiento se debe a que varios de los valores mostrados de forma predeterminada, como NPM(K), PM(K), WS(K)y CPU(s), son propiedades calculadas. Debe canalizar comandos para Get-Member determinar sus nombres de propiedad reales.

   TypeName: System.Diagnostics.Process

Name                       MemberType     Definition
----                       ----------     ----------
Handles                    AliasProperty  Handles = Handlecount
Name                       AliasProperty  Name = ProcessName
NPM                        AliasProperty  NPM = NonpagedSystemMemorySize64
PM                         AliasProperty  PM = PagedMemorySize64
SI                         AliasProperty  SI = SessionId
VM                         AliasProperty  VM = VirtualMemorySize64
WS                         AliasProperty  WS = WorkingSet64
Disposed                   Event          System.EventHandler Disposed(Sy...
ErrorDataReceived          Event          System.Diagnostics.DataReceived...
Exited                     Event          System.EventHandler Exited(Syst...
OutputDataReceived         Event          System.Diagnostics.DataReceived...
BeginErrorReadLine         Method         void BeginErrorReadLine()
BeginOutputReadLine        Method         void BeginOutputReadLine()
CancelErrorRead            Method         void CancelErrorRead()
CancelOutputRead           Method         void CancelOutputRead()
Close                      Method         void Close()
CloseMainWindow            Method         bool CloseMainWindow()
CreateObjRef               Method         System.Runtime.Remoting.ObjRef ...
Dispose                    Method         void Dispose(), void IDisposabl...
Equals                     Method         bool Equals(System.Object obj)
GetHashCode                Method         int GetHashCode()
GetLifetimeService         Method         System.Object GetLifetimeService()
GetType                    Method         type GetType()
InitializeLifetimeService  Method         System.Object InitializeLifetim...
Kill                       Method         void Kill()
Refresh                    Method         void Refresh()
Start                      Method         bool Start()
ToString                   Method         string ToString()
WaitForExit                Method         bool WaitForExit(int millisecon...
WaitForInputIdle           Method         bool WaitForInputIdle(int milli...
__NounName                 NoteProperty   string __NounName=Process
BasePriority               Property       int BasePriority {get;}
Container                  Property       System.ComponentModel.IContaine...
EnableRaisingEvents        Property       bool EnableRaisingEvents {get;s...
ExitCode                   Property       int ExitCode {get;}
ExitTime                   Property       datetime ExitTime {get;}
Handle                     Property       System.IntPtr Handle {get;}
HandleCount                Property       int HandleCount {get;}
HasExited                  Property       bool HasExited {get;}
Id                         Property       int Id {get;}
MachineName                Property       string MachineName {get;}
MainModule                 Property       System.Diagnostics.ProcessModul...
MainWindowHandle           Property       System.IntPtr MainWindowHandle ...
MainWindowTitle            Property       string MainWindowTitle {get;}
MaxWorkingSet              Property       System.IntPtr MaxWorkingSet {ge...
MinWorkingSet              Property       System.IntPtr MinWorkingSet {ge...
Modules                    Property       System.Diagnostics.ProcessModul...
NonpagedSystemMemorySize   Property       int NonpagedSystemMemorySize {g...
NonpagedSystemMemorySize64 Property       long NonpagedSystemMemorySize64...
PagedMemorySize            Property       int PagedMemorySize {get;}
PagedMemorySize64          Property       long PagedMemorySize64 {get;}
PagedSystemMemorySize      Property       int PagedSystemMemorySize {get;}
PagedSystemMemorySize64    Property       long PagedSystemMemorySize64 {g...
PeakPagedMemorySize        Property       int PeakPagedMemorySize {get;}
PeakPagedMemorySize64      Property       long PeakPagedMemorySize64 {get;}
PeakVirtualMemorySize      Property       int PeakVirtualMemorySize {get;}
PeakVirtualMemorySize64    Property       long PeakVirtualMemorySize64 {g...
PeakWorkingSet             Property       int PeakWorkingSet {get;}
PeakWorkingSet64           Property       long PeakWorkingSet64 {get;}
PriorityBoostEnabled       Property       bool PriorityBoostEnabled {get;...
PriorityClass              Property       System.Diagnostics.ProcessPrior...
PrivateMemorySize          Property       int PrivateMemorySize {get;}
PrivateMemorySize64        Property       long PrivateMemorySize64 {get;}
PrivilegedProcessorTime    Property       timespan PrivilegedProcessorTim...
ProcessName                Property       string ProcessName {get;}
ProcessorAffinity          Property       System.IntPtr ProcessorAffinity...
Responding                 Property       bool Responding {get;}
SafeHandle                 Property       Microsoft.Win32.SafeHandles.Saf...
SessionId                  Property       int SessionId {get;}
Site                       Property       System.ComponentModel.ISite Sit...
StandardError              Property       System.IO.StreamReader Standard...
StandardInput              Property       System.IO.StreamWriter Standard...
StandardOutput             Property       System.IO.StreamReader Standard...
StartInfo                  Property       System.Diagnostics.ProcessStart...
StartTime                  Property       datetime StartTime {get;}
SynchronizingObject        Property       System.ComponentModel.ISynchron...
Threads                    Property       System.Diagnostics.ProcessThrea...
TotalProcessorTime         Property       timespan TotalProcessorTime {get;}
UserProcessorTime          Property       timespan UserProcessorTime {get;}
VirtualMemorySize          Property       int VirtualMemorySize {get;}
VirtualMemorySize64        Property       long VirtualMemorySize64 {get;}
WorkingSet                 Property       int WorkingSet {get;}
WorkingSet64               Property       long WorkingSet64 {get;}
PSConfiguration            PropertySet    PSConfiguration {Name, Id, Prio...
PSResources                PropertySet    PSResources {Name, Id, Handleco...
Company                    ScriptProperty System.Object Company {get=$thi...
CPU                        ScriptProperty System.Object CPU {get=$this.To...
Description                ScriptProperty System.Object Description {get=...
FileVersion                ScriptProperty System.Object FileVersion {get=...
Path                       ScriptProperty System.Object Path {get=$this.M...
Product                    ScriptProperty System.Object Product {get=$thi...
ProductVersion             ScriptProperty System.Object ProductVersion {g...

No se puede canalizar un comando a Get-Member que no genere la salida. Como Start-Service no genera la salida de forma predeterminada, al intentar canalizarla para Get-Member producir un error.

Start-Service -Name w32time | Get-Member

Nota:

Para que se canalice a Get-Member, un comando debe producir una salida basada en objetos.

Get-Member : You must specify an object for the Get-Member cmdlet.
At line:1 char:31
+ Start-Service -Name w32time | Get-Member
+                               ~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Get-Member], InvalidOperation
   Exception
    + FullyQualifiedErrorId : NoObjectInGetMember,Microsoft.PowerShell.Comma
   nds.GetMemberCommand

Para evitar este error, especifique el parámetro PassThru con Start-Service. Como se mencionó anteriormente, agregar el parámetro PassThru provoca un cmdlet que normalmente no genera la salida para generar la salida.

Start-Service -Name w32time -PassThru | Get-Member
   TypeName: System.ServiceProcess.ServiceController

Name                      MemberType    Definition
----                      ----------    ----------
Name                      AliasProperty Name = ServiceName
RequiredServices          AliasProperty RequiredServices = ServicesDepend...
Disposed                  Event         System.EventHandler Disposed(Syst...
Close                     Method        void Close()
Continue                  Method        void Continue()
CreateObjRef              Method        System.Runtime.Remoting.ObjRef Cr...
Dispose                   Method        void Dispose(), void IDisposable....
Equals                    Method        bool Equals(System.Object obj)
ExecuteCommand            Method        void ExecuteCommand(int command)
GetHashCode               Method        int GetHashCode()
GetLifetimeService        Method        System.Object GetLifetimeService()
GetType                   Method        type GetType()
InitializeLifetimeService Method        System.Object InitializeLifetimeS...
Pause                     Method        void Pause()
Refresh                   Method        void Refresh()
Start                     Method        void Start(), void Start(string[]...
Stop                      Method        void Stop()
WaitForStatus             Method        void WaitForStatus(System.Service...
CanPauseAndContinue       Property      bool CanPauseAndContinue {get;}
CanShutdown               Property      bool CanShutdown {get;}
CanStop                   Property      bool CanStop {get;}
Container                 Property      System.ComponentModel.IContainer ...
DependentServices         Property      System.ServiceProcess.ServiceCont...
DisplayName               Property      string DisplayName {get;set;}
MachineName               Property      string MachineName {get;set;}
ServiceHandle             Property      System.Runtime.InteropServices.Sa...
ServiceName               Property      string ServiceName {get;set;}
ServicesDependedOn        Property      System.ServiceProcess.ServiceCont...
ServiceType               Property      System.ServiceProcess.ServiceType...
Site                      Property      System.ComponentModel.ISite Site ...
StartType                 Property      System.ServiceProcess.ServiceStar...
Status                    Property      System.ServiceProcess.ServiceCont...
ToString                  ScriptMethod  System.Object ToString();

Out-Host está diseñado para mostrar la salida directamente en el host de PowerShell y no genera resultados basados en objetos. Como resultado, no se puede canalizar su salida a Get-Member, lo que requiere la entrada basada en objetos.

Get-Service -Name w32time | Out-Host | Get-Member
Status   Name               DisplayName
------   ----               -----------
Running  w32time            Windows Time

Get-Member : You must specify an object for the Get-Member cmdlet.
At line:1 char:40
+ Get-Service -Name w32time | Out-Host | Get-Member
+                                        ~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Get-Member], InvalidOperation
   Exception
    + FullyQualifiedErrorId : NoObjectInGetMember,Microsoft.PowerShell.Comma
   nds.GetMemberCommand

Get-Command

Saber el tipo de objeto que genera un comando permite buscar comandos que acepten ese tipo de objeto como entrada.

Get-Command -ParameterType ServiceController

Los comandos siguientes aceptan un objeto ServiceController a través de la canalización o la entrada de parámetros.

CommandType     Name                                               Version
-----------     ----                                               -------
Cmdlet          Get-Service                                        3.1.0.0
Cmdlet          Restart-Service                                    3.1.0.0
Cmdlet          Resume-Service                                     3.1.0.0
Cmdlet          Set-Service                                        3.1.0.0
Cmdlet          Start-Service                                      3.1.0.0
Cmdlet          Stop-Service                                       3.1.0.0
Cmdlet          Suspend-Service                                    3.1.0.0

Active Directory

Nota:

Como se mencionó en los requisitos previos del capítulo, asegúrese de que tiene RSAT instalado para esta sección. Además, el equipo del entorno de laboratorio debe ser miembro del dominio de Active Directory del entorno de laboratorio.

Para identificar los comandos agregados al módulo activeDirectory de PowerShell después de instalar RSAT, use Get-Command combinado con el parámetro Module . En el ejemplo siguiente se enumeran todos los comandos disponibles en el módulo ActiveDirectory .

Get-Command -Module ActiveDirectory

El módulo activeDirectory de PowerShell agregó un total de 147 comandos.

¿Ha observado la convención de nomenclatura de estos comandos? Los nombres de los nombres de comando tienen el prefijo AD para evitar posibles conflictos de nomenclatura con comandos en otros módulos. Este prefijo es una práctica común entre los módulos de PowerShell.

CommandType     Name                                               Version
-----------     ----                                               -------
Cmdlet          Add-ADCentralAccessPolicyMember                    1.0.1.0
Cmdlet          Add-ADComputerServiceAccount                       1.0.1.0
Cmdlet          Add-ADDomainControllerPasswordReplicationPolicy    1.0.1.0
Cmdlet          Add-ADFineGrainedPasswordPolicySubject             1.0.1.0
Cmdlet          Add-ADGroupMember                                  1.0.1.0
Cmdlet          Add-ADPrincipalGroupMembership                     1.0.1.0
Cmdlet          Add-ADResourcePropertyListMember                   1.0.1.0
Cmdlet          Clear-ADAccountExpiration                          1.0.1.0
Cmdlet          Clear-ADClaimTransformLink                         1.0.1.0
Cmdlet          Disable-ADAccount                                  1.0.1.0
...

De forma predeterminada, el Get-ADUser cmdlet recupera un conjunto limitado de propiedades para objetos de usuario y limita su salida a los primeros 1000 usuarios. Esta restricción es una optimización del rendimiento diseñada para evitar sobrecargar Active Directory con una recuperación excesiva de datos.

Get-ADUser -Identity mike | Get-Member -MemberType Properties

Incluso si solo tiene conocimientos básicos de Active Directory, es posible que reconozca que una cuenta de usuario tiene más propiedades que las que se muestran en el ejemplo.

   TypeName: Microsoft.ActiveDirectory.Management.ADUser

Name              MemberType Definition                                     
----              ---------- ----------                                     
DistinguishedName Property   System.String DistinguishedName {get;set;}     
Enabled           Property   System.Boolean Enabled {get;set;}              
GivenName         Property   System.String GivenName {get;set;}             
Name              Property   System.String Name {get;}                      
ObjectClass       Property   System.String ObjectClass {get;set;}           
ObjectGUID        Property   System.Nullable`1[[System.Guid, mscorlib, Ve...
SamAccountName    Property   System.String SamAccountName {get;set;}        
SID               Property   System.Security.Principal.SecurityIdentifier...
Surname           Property   System.String Surname {get;set;}               
UserPrincipalName Property   System.String UserPrincipalName {get;set;}

El Get-ADUser cmdlet incluye un parámetro Properties para especificar propiedades adicionales más allá de los valores predeterminados que desea recuperar. Para devolver todas las propiedades, use el * carácter comodín como valor de parámetro.

Get-ADUser -Identity mike -Properties * | Get-Member -MemberType Properties
   TypeName: Microsoft.ActiveDirectory.Management.ADUser

Name                                 MemberType Definition                  
----                                 ---------- ----------                  
AccountExpirationDate                Property   System.DateTime AccountEx...
accountExpires                       Property   System.Int64 accountExpir...
AccountLockoutTime                   Property   System.DateTime AccountLo...
AccountNotDelegated                  Property   System.Boolean AccountNot...
AllowReversiblePasswordEncryption    Property   System.Boolean AllowRever...
AuthenticationPolicy                 Property   Microsoft.ActiveDirectory...
AuthenticationPolicySilo             Property   Microsoft.ActiveDirectory...
BadLogonCount                        Property   System.Int32 BadLogonCoun...
badPasswordTime                      Property   System.Int64 badPasswordT...
badPwdCount                          Property   System.Int32 badPwdCount ...
CannotChangePassword                 Property   System.Boolean CannotChan...
CanonicalName                        Property   System.String CanonicalNa...
Certificates                         Property   Microsoft.ActiveDirectory...
City                                 Property   System.String City {get;s...
CN                                   Property   System.String CN {get;}     
codePage                             Property   System.Int32 codePage {ge...
Company                              Property   System.String Company {ge...
CompoundIdentitySupported            Property   Microsoft.ActiveDirectory...
Country                              Property   System.String Country {ge...
countryCode                          Property   System.Int32 countryCode ...
Created                              Property   System.DateTime Created {...
createTimeStamp                      Property   System.DateTime createTim...
Deleted                              Property   System.Boolean Deleted {g...
Department                           Property   System.String Department ...
Description                          Property   System.String Description...
DisplayName                          Property   System.String DisplayName...
DistinguishedName                    Property   System.String Distinguish...
Division                             Property   System.String Division {g...
DoesNotRequirePreAuth                Property   System.Boolean DoesNotReq...
dSCorePropagationData                Property   Microsoft.ActiveDirectory...
EmailAddress                         Property   System.String EmailAddres...
EmployeeID                           Property   System.String EmployeeID ...
EmployeeNumber                       Property   System.String EmployeeNum...
Enabled                              Property   System.Boolean Enabled {g...
Fax                                  Property   System.String Fax {get;set;}
GivenName                            Property   System.String GivenName {...
HomeDirectory                        Property   System.String HomeDirecto...
HomedirRequired                      Property   System.Boolean HomedirReq...
HomeDrive                            Property   System.String HomeDrive {...
HomePage                             Property   System.String HomePage {g...
HomePhone                            Property   System.String HomePhone {...
Initials                             Property   System.String Initials {g...
instanceType                         Property   System.Int32 instanceType...
isDeleted                            Property   System.Boolean isDeleted ...
KerberosEncryptionType               Property   Microsoft.ActiveDirectory...
LastBadPasswordAttempt               Property   System.DateTime LastBadPa...
LastKnownParent                      Property   System.String LastKnownPa...
lastLogoff                           Property   System.Int64 lastLogoff {...
lastLogon                            Property   System.Int64 lastLogon {g...
LastLogonDate                        Property   System.DateTime LastLogon...
lastLogonTimestamp                   Property   System.Int64 lastLogonTim...
LockedOut                            Property   System.Boolean LockedOut ...
logonCount                           Property   System.Int32 logonCount {...
LogonWorkstations                    Property   System.String LogonWorkst...
Manager                              Property   System.String Manager {ge...
MemberOf                             Property   Microsoft.ActiveDirectory...
MNSLogonAccount                      Property   System.Boolean MNSLogonAc...
MobilePhone                          Property   System.String MobilePhone...
Modified                             Property   System.DateTime Modified ...
modifyTimeStamp                      Property   System.DateTime modifyTim...
msDS-User-Account-Control-Computed   Property   System.Int32 msDS-User-Ac...
Name                                 Property   System.String Name {get;}   
nTSecurityDescriptor                 Property   System.DirectoryServices....
ObjectCategory                       Property   System.String ObjectCateg...
ObjectClass                          Property   System.String ObjectClass...
ObjectGUID                           Property   System.Nullable`1[[System...
objectSid                            Property   System.Security.Principal...
Office                               Property   System.String Office {get...
OfficePhone                          Property   System.String OfficePhone...
Organization                         Property   System.String Organizatio...
OtherName                            Property   System.String OtherName {...
PasswordExpired                      Property   System.Boolean PasswordEx...
PasswordLastSet                      Property   System.DateTime PasswordL...
PasswordNeverExpires                 Property   System.Boolean PasswordNe...
PasswordNotRequired                  Property   System.Boolean PasswordNo...
POBox                                Property   System.String POBox {get;...
PostalCode                           Property   System.String PostalCode ...
PrimaryGroup                         Property   System.String PrimaryGrou...
primaryGroupID                       Property   System.Int32 primaryGroup...
PrincipalsAllowedToDelegateToAccount Property   Microsoft.ActiveDirectory...
ProfilePath                          Property   System.String ProfilePath...
ProtectedFromAccidentalDeletion      Property   System.Boolean ProtectedF...
pwdLastSet                           Property   System.Int64 pwdLastSet {...
SamAccountName                       Property   System.String SamAccountN...
sAMAccountType                       Property   System.Int32 sAMAccountTy...
ScriptPath                           Property   System.String ScriptPath ...
sDRightsEffective                    Property   System.Int32 sDRightsEffe...
ServicePrincipalNames                Property   Microsoft.ActiveDirectory...
SID                                  Property   System.Security.Principal...
SIDHistory                           Property   Microsoft.ActiveDirectory...
SmartcardLogonRequired               Property   System.Boolean SmartcardL...
sn                                   Property   System.String sn {get;set;} 
State                                Property   System.String State {get;...
StreetAddress                        Property   System.String StreetAddre...
Surname                              Property   System.String Surname {ge...
Title                                Property   System.String Title {get;...
TrustedForDelegation                 Property   System.Boolean TrustedFor...
TrustedToAuthForDelegation           Property   System.Boolean TrustedToA...
UseDESKeyOnly                        Property   System.Boolean UseDESKeyO...
userAccountControl                   Property   System.Int32 userAccountC...
userCertificate                      Property   Microsoft.ActiveDirectory...
UserPrincipalName                    Property   System.String UserPrincip...
uSNChanged                           Property   System.Int64 uSNChanged {...
uSNCreated                           Property   System.Int64 uSNCreated {...
whenChanged                          Property   System.DateTime whenChang...
whenCreated                          Property   System.DateTime whenCreat...

La configuración predeterminada para recuperar las propiedades de la cuenta de usuario de Active Directory se limita intencionadamente para evitar problemas de rendimiento. Intentar devolver todas las propiedades de cada cuenta de usuario del entorno de Producción de Active Directory podría degradar gravemente el rendimiento de los controladores de dominio y la red. Normalmente, solo necesita propiedades específicas para determinados usuarios. Sin embargo, devolver todas las propiedades de un solo usuario es razonable al identificar las propiedades disponibles.

No es raro ejecutar un comando varias veces al crear prototipos. Si prevé ejecutar una consulta que consume muchos recursos al crear prototipos de un comando, considere la posibilidad de ejecutarla una vez y almacenar los resultados en una variable. A continuación, puede trabajar con el contenido de la variable de forma más eficaz que ejecutar repetidamente una consulta que consume muchos recursos.

Por ejemplo, el siguiente comando recupera todas las propiedades de una cuenta de usuario y almacena los resultados en una variable denominada $Users. Trabaje con el contenido de la $Users variable en lugar de ejecutar el Get-ADUser comando varias veces. Recuerde que el contenido de la variable no se actualiza automáticamente cuando cambia la información de un usuario en Active Directory.

$Users = Get-ADUser -Identity mike -Properties *

Puede explorar las propiedades disponibles canalizando la $Users variable a Get-Member.

$Users | Get-Member -MemberType Properties

Para ver propiedades específicas como Name, LastLogonDate Este método muestra las propiedades deseadas y sus valores en función del contenido de la $Users variable, lo que elimina la necesidad de realizar varias consultas en Active Directory. Es un enfoque más eficaz para los recursos que ejecutar repetidamente el Get-ADUser comando.

$Users | Select-Object -Property Name, LastLogonDate, LastBadPasswordAttempt

Al consultar Active Directory, filtre los datos en el origen mediante el parámetro Properties de Get-ADUser para devolver solo las propiedades necesarias.

Get-ADUser -Identity mike -Properties LastLogonDate, LastBadPasswordAttempt
DistinguishedName      : CN=Mike F. Robbins,CN=Users,DC=mikefrobbins,DC=com
Enabled                : True
GivenName              : Mike
LastBadPasswordAttempt :
LastLogonDate          : 11/14/2023 5:10:16 AM
Name                   : Mike F. Robbins
ObjectClass            : user
ObjectGUID             : 11c7b61f-46c3-4399-9ed0-ff4e453bc2a2
SamAccountName         : mike
SID                    : S-1-5-21-611971124-518002951-3581791498-1105
Surname                : Robbins
UserPrincipalName      : μ@mikefrobbins.com

Resumen

En este capítulo, ha aprendido a determinar qué tipo de objeto genera un comando, qué propiedades y métodos están disponibles para un comando y cómo trabajar con comandos que limitan las propiedades devueltas de forma predeterminada.

Revisar

  1. ¿Qué tipo de objeto produce el cmdlet Get-Process?
  2. ¿Cómo se determinan las propiedades disponibles para un comando?
  3. ¿Qué debe comprobar si existe un comando para obtener algo, pero no para establecer lo mismo?
  4. ¿Cómo se pueden realizar algunos comandos que no devuelven la salida de forma predeterminada para generar la salida?
  5. ¿Qué debe considerar al crear prototipos de un comando que genere una gran cantidad de salida?

Referencias

Pasos siguientes

En el siguiente capítulo, obtendrá información sobre las líneas únicas y la canalización.