Capítulo 3 - Descobrindo objetos, propriedades e métodos

Minha primeira introdução aos computadores foi um Commodore 64, mas meu primeiro computador moderno foi um clone IBM de 286 12 Mhz com 1 megabyte de memória, um disco rígido de 40 megabytes e uma unidade de disquete de 5-1/4 polegadas com um monitor CGA executando o Microsoft DOS 3.3.

Muitos profissionais de TI, como eu, não são estranhos à linha de comando, mas quando o assunto de objetos, propriedades e métodos aparece, eles pegam o cervo nos faróis e dizem: "Eu não sou um desenvolvedor". Adivinha? Você não precisa ser um desenvolvedor para ter sucesso com o PowerShell. Não fique atolado na terminologia. Nem tudo pode fazer sentido inicialmente, mas depois de uma pequena experiência prática você começará a ter aqueles momentos de "lâmpada". "Aha! Então era disso que o livro falava."

Certifique-se de experimentar os exemplos no seu computador para obter um pouco dessa experiência prática.

Requisitos

O módulo PowerShell do Ative Directory é exigido por alguns dos exemplos mostrados neste capítulo. O módulo faz parte das Ferramentas de Administração de Servidor Remoto (RSAT) para Windows. Para a compilação 1809 (ou superior) do Windows, as ferramentas RSAT são instaladas como um recurso do Windows. O suporte para o Ative Directory não está disponível no Windows Home.

  • Para obter informações sobre como instalar as ferramentas RSAT, consulte Módulos de gerenciamento do Windows.
  • Para versões mais antigas do Windows, consulte RSAT para Windows.

Get-Member

Get-Member Ajuda a descobrir quais objetos, propriedades e métodos estão disponíveis para comandos. Qualquer comando que produza saída baseada em objeto pode ser canalizado para Get-Member. Uma propriedade é uma característica sobre um item. Sua carteira de motorista tem uma propriedade chamada cor dos olhos e os valores mais comuns para essa propriedade são azul e marrom. Um método é uma ação que pode ser executada em um item. Ao ficar com o exemplo da carta de condução, um dos métodos é "Revogar" porque o departamento de veículos motorizados pode revogar a sua carta de condução.

Propriedades

No exemplo a seguir, recuperarei informações sobre o serviço de Tempo do Windows em execução no meu computador.

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

Status, Name e DisplayName são exemplos de propriedades conforme mostrado no conjunto anterior de resultados. O valor para a propriedade Status é Running, o valor para a propriedade Name é w32time, e o valor para DisplayName é Windows Time.

Agora vou canalizar esse mesmo comando para Get-Member:

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

Name                      MemberType    Definition
----                      ----------    ----------
Name                      AliasProperty Name = ServiceName
RequiredServices          AliasProperty RequiredServices = ServicesDependedOn
Disposed                  Event         System.EventHandler Disposed(System.Object, Sy...
Close                     Method        void Close()
Continue                  Method        void Continue()
CreateObjRef              Method        System.Runtime.Remoting.ObjRef CreateObjRef(ty...
Dispose                   Method        void Dispose(), void IDisposable.Dispose()
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 InitializeLifetimeService()
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.ServiceProcess.Servi...
CanPauseAndContinue       Property      bool CanPauseAndContinue {get;}
CanShutdown               Property      bool CanShutdown {get;}
CanStop                   Property      bool CanStop {get;}
Container                 Property      System.ComponentModel.IContainer Container {get;}
DependentServices         Property      System.ServiceProcess.ServiceController[] Depe...
DisplayName               Property      string DisplayName {get;set;}
MachineName               Property      string MachineName {get;set;}
ServiceHandle             Property      System.Runtime.InteropServices.SafeHandle Serv...
ServiceName               Property      string ServiceName {get;set;}
ServicesDependedOn        Property      System.ServiceProcess.ServiceController[] Serv...
ServiceType               Property      System.ServiceProcess.ServiceType ServiceType ...
Site                      Property      System.ComponentModel.ISite Site {get;set;}
StartType                 Property      System.ServiceProcess.ServiceStartMode StartTy...
Status                    Property      System.ServiceProcess.ServiceControllerStatus ...
ToString                  ScriptMethod  System.Object ToString();

A primeira linha dos resultados do exemplo anterior contém uma informação muito importante. TypeName informa que tipo de objeto foi retornado. Neste exemplo, um objeto System.ServiceProcess.ServiceController foi retornado. Isto é muitas vezes abreviado como a parte do TypeName logo após o último período; ServiceController neste exemplo.

Depois de saber que tipo de objeto um comando produz, você pode usar essas informações para encontrar comandos que aceitam esse tipo de objeto como entrada.

Get-Command -ParameterType ServiceController
CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Cmdlet          Get-Service                                        3.1.0.0    Microsof...
Cmdlet          Restart-Service                                    3.1.0.0    Microsof...
Cmdlet          Resume-Service                                     3.1.0.0    Microsof...
Cmdlet          Set-Service                                        3.1.0.0    Microsof...
Cmdlet          Start-Service                                      3.1.0.0    Microsof...
Cmdlet          Stop-Service                                       3.1.0.0    Microsof...
Cmdlet          Suspend-Service                                    3.1.0.0    Microsof...

Todos esses comandos têm um parâmetro que aceita um tipo de objeto ServiceController por pipeline, entrada de parâmetro ou ambos.

Observe que há mais propriedades do que as exibidas por padrão. Embora essas propriedades adicionais não sejam exibidas por padrão, elas podem ser selecionadas no pipeline canalizando o comando para o Select-Object cmdlet e usando o parâmetro Property . O exemplo a seguir seleciona todas as propriedades canalizando os resultados de Get-Service para Select-Object e especificando o caractere curinga * como o valor para o parâmetro Property .

Get-Service -Name w32time | Select-Object -Property *
Name                : w32time
RequiredServices    : {}
CanPauseAndContinue : False
CanShutdown         : True
CanStop             : True
DisplayName         : Windows Time
DependentServices   : {}
MachineName         : .
ServiceName         : w32time
ServicesDependedOn  : {}
ServiceHandle       : SafeServiceHandle
Status              : Running
ServiceType         : Win32ShareProcess
StartType           : Manual
Site                :
Container           :

Propriedades específicas também podem ser selecionadas usando uma lista separada por vírgulas para o valor do parâmetro Property .

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

Por padrão, quatro propriedades são retornadas em uma tabela e cinco ou mais são retornadas em uma lista. Alguns comandos usam formatação personalizada para substituir quantas propriedades são exibidas por padrão em uma tabela. Há vários Format-* cmdlets que podem ser usados para substituir manualmente esses padrões. Os mais comuns são Format-Table e Format-List, ambos serão abordados em um próximo capítulo.

Caracteres curinga podem ser usados ao especificar os nomes de propriedade com Select-Object.

Get-Service -Name w32time | Select-Object -Property Status, DisplayName, Can*
Status              : Running
DisplayName         : Windows Time
CanPauseAndContinue : False
CanShutdown         : True
CanStop             : True

No exemplo anterior, Can* foi usado como um dos valores para o parâmetro Property para retornar todas as propriedades que começam com Can. Estes incluem CanPauseAndContinue, CanShutdown e CanStop.

Métodos

Os métodos são uma ação que pode ser tomada. Use o parâmetro MemberType para restringir os resultados de para mostrar apenas os métodos para Get-MemberGet-Service.

Get-Service -Name w32time | Get-Member -MemberType Method
   TypeName: System.ServiceProcess.ServiceController

Name                      MemberType Definition
----                      ---------- ----------
Close                     Method     void Close()
Continue                  Method     void Continue()
CreateObjRef              Method     System.Runtime.Remoting.ObjRef CreateObjRef(type ...
Dispose                   Method     void Dispose(), void IDisposable.Dispose()
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 InitializeLifetimeService()
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.ServiceProcess.ServiceC...

Como você pode ver, existem muitos métodos. O método Stop pode ser usado para parar um serviço do Windows.

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

Agora, para verificar se o serviço de tempo do Windows foi realmente interrompido.

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

Eu raramente me encontro usando métodos, mas eles são algo que você precisa estar ciente. Há momentos em que você se depara com um Get-* comando sem um comando correspondente para modificar esse item. Muitas vezes, um método pode ser usado para executar uma ação que o modifica. O Get-SqlAgentJob cmdlet no módulo SqlServer PowerShell é um bom exemplo disso. O módulo é instalado como parte do SQL Server Management Studio (SMSS). Não existe um cmdlet correspondente Set-* , mas um método pode ser usado para concluir a mesma tarefa.

Outra razão para estar ciente dos métodos é que muitos iniciantes assumem que mudanças destrutivas não podem ser feitas com Get-* comandos. Mas eles realmente podem causar sérios problemas se usados de forma inadequada.

Uma opção melhor é usar um cmdlet para executar a ação, se existir. Vá em frente e inicie o serviço de Tempo do Windows, exceto que desta vez use o cmdlet para iniciar serviços.

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

Por padrão, Start-Service não retorna nenhum resultado como o método inicial do Get-Service. Mas um dos benefícios de usar um cmdlet é que muitas vezes o cmdlet oferece funcionalidade adicional que não está disponível com um método. No exemplo anterior, o parâmetro PassThru foi usado. Isso faz com que um cmdlet que normalmente não produz saída, produza saída.

Tenha cuidado com suposições sobre a saída de um cmdlet. Todos sabemos o que acontece quando se assumem as coisas. Recuperarei informações sobre o processo do PowerShell em execução no meu computador com ambiente de laboratório do Windows 10.

Get-Process -Name PowerShell
Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
-------  ------    -----      -----     ------     --  -- -----------
    922      48   107984     140552       2.84   9020   1 powershell

Agora vou canalizar esse mesmo comando para Get-Member:

Get-Process -Name PowerShell | Get-Member
   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(System.Object, ...
ErrorDataReceived          Event          System.Diagnostics.DataReceivedEventHandler ...
Exited                     Event          System.EventHandler Exited(System.Object, Sy...
OutputDataReceived         Event          System.Diagnostics.DataReceivedEventHandler ...
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 CreateObjRef(...
Dispose                    Method         void Dispose(), void IDisposable.Dispose()
Equals                     Method         bool Equals(System.Object obj)
GetHashCode                Method         int GetHashCode()
GetLifetimeService         Method         System.Object GetLifetimeService()
GetType                    Method         type GetType()
InitializeLifetimeService  Method         System.Object InitializeLifetimeService()
Kill                       Method         void Kill()
Refresh                    Method         void Refresh()
Start                      Method         bool Start()
ToString                   Method         string ToString()
WaitForExit                Method         bool WaitForExit(int milliseconds), void Wai...
WaitForInputIdle           Method         bool WaitForInputIdle(int milliseconds), boo...
__NounName                 NoteProperty   string __NounName=Process
BasePriority               Property       int BasePriority {get;}
Container                  Property       System.ComponentModel.IContainer Container {...
EnableRaisingEvents        Property       bool EnableRaisingEvents {get;set;}
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.ProcessModule MainModule ...
MainWindowHandle           Property       System.IntPtr MainWindowHandle {get;}
MainWindowTitle            Property       string MainWindowTitle {get;}
MaxWorkingSet              Property       System.IntPtr MaxWorkingSet {get;set;}
MinWorkingSet              Property       System.IntPtr MinWorkingSet {get;set;}
Modules                    Property       System.Diagnostics.ProcessModuleCollection M...
NonpagedSystemMemorySize   Property       int NonpagedSystemMemorySize {get;}
NonpagedSystemMemorySize64 Property       long NonpagedSystemMemorySize64 {get;}
PagedMemorySize            Property       int PagedMemorySize {get;}
PagedMemorySize64          Property       long PagedMemorySize64 {get;}
PagedSystemMemorySize      Property       int PagedSystemMemorySize {get;}
PagedSystemMemorySize64    Property       long PagedSystemMemorySize64 {get;}
PeakPagedMemorySize        Property       int PeakPagedMemorySize {get;}
PeakPagedMemorySize64      Property       long PeakPagedMemorySize64 {get;}
PeakVirtualMemorySize      Property       int PeakVirtualMemorySize {get;}
PeakVirtualMemorySize64    Property       long PeakVirtualMemorySize64 {get;}
PeakWorkingSet             Property       int PeakWorkingSet {get;}
PeakWorkingSet64           Property       long PeakWorkingSet64 {get;}
PriorityBoostEnabled       Property       bool PriorityBoostEnabled {get;set;}
PriorityClass              Property       System.Diagnostics.ProcessPriorityClass Prio...
PrivateMemorySize          Property       int PrivateMemorySize {get;}
PrivateMemorySize64        Property       long PrivateMemorySize64 {get;}
PrivilegedProcessorTime    Property       timespan PrivilegedProcessorTime {get;}
ProcessName                Property       string ProcessName {get;}
ProcessorAffinity          Property       System.IntPtr ProcessorAffinity {get;set;}
Responding                 Property       bool Responding {get;}
SafeHandle                 Property       Microsoft.Win32.SafeHandles.SafeProcessHandl...
SessionId                  Property       int SessionId {get;}
Site                       Property       System.ComponentModel.ISite Site {get;set;}
StandardError              Property       System.IO.StreamReader StandardError {get;}
StandardInput              Property       System.IO.StreamWriter StandardInput {get;}
StandardOutput             Property       System.IO.StreamReader StandardOutput {get;}
StartInfo                  Property       System.Diagnostics.ProcessStartInfo StartInf...
StartTime                  Property       datetime StartTime {get;}
SynchronizingObject        Property       System.ComponentModel.ISynchronizeInvoke Syn...
Threads                    Property       System.Diagnostics.ProcessThreadCollection T...
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, PriorityClass, Fi...
PSResources                PropertySet    PSResources {Name, Id, Handlecount, WorkingS...
Company                    ScriptProperty System.Object Company {get=$this.Mainmodule....
CPU                        ScriptProperty System.Object CPU {get=$this.TotalProcessorT...
Description                ScriptProperty System.Object Description {get=$this.Mainmod...
FileVersion                ScriptProperty System.Object FileVersion {get=$this.Mainmod...
Path                       ScriptProperty System.Object Path {get=$this.Mainmodule.Fil...
Product                    ScriptProperty System.Object Product {get=$this.Mainmodule....
ProductVersion             ScriptProperty System.Object ProductVersion {get=$this.Main...

Observe que há mais propriedades listadas do que as exibidas por padrão. Algumas das propriedades padrão exibidas não aparecem como propriedades ao exibir os resultados do Get-Member. Isso ocorre porque muitos dos valores exibidos, como NPM(K), PM(K), WS(K), e CPU(s), são propriedades calculadas. Para determinar os nomes de propriedade reais, o comando deve ser canalizado para Get-Member.

Se um comando não produzir saída, ele não poderá ser canalizado para Get-Member. Como Start-Service não produz nenhuma saída por padrão, ele gera um erro quando você tenta canalizá-lo para Get-Member.

Start-Service -Name w32time | Get-Member
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], InvalidOperationException
    + FullyQualifiedErrorId : NoObjectInGetMember,Microsoft.PowerShell.Commands.GetMembe
   rCommand

O parâmetro PassThru pode ser especificado com o Start-Service cmdlet make it produce output, que é então canalizado para sem Get-Member erro.

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

Name                      MemberType    Definition
----                      ----------    ----------
Name                      AliasProperty Name = ServiceName
RequiredServices          AliasProperty RequiredServices = ServicesDependedOn
Disposed                  Event         System.EventHandler Disposed(System.Object, Sy...
Close                     Method        void Close()
Continue                  Method        void Continue()
CreateObjRef              Method        System.Runtime.Remoting.ObjRef CreateObjRef(ty...
Dispose                   Method        void Dispose(), void IDisposable.Dispose()
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 InitializeLifetimeService()
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.ServiceProcess.Servi...
CanPauseAndContinue       Property      bool CanPauseAndContinue {get;}
CanShutdown               Property      bool CanShutdown {get;}
CanStop                   Property      bool CanStop {get;}
Container                 Property      System.ComponentModel.IContainer Container {get;}
DependentServices         Property      System.ServiceProcess.ServiceController[] Depe...
DisplayName               Property      string DisplayName {get;set;}
MachineName               Property      string MachineName {get;set;}
ServiceHandle             Property      System.Runtime.InteropServices.SafeHandle Serv...
ServiceName               Property      string ServiceName {get;set;}
ServicesDependedOn        Property      System.ServiceProcess.ServiceController[] Serv...
ServiceType               Property      System.ServiceProcess.ServiceType ServiceType ...
Site                      Property      System.ComponentModel.ISite Site {get;set;}
StartType                 Property      System.ServiceProcess.ServiceStartMode StartTy...
Status                    Property      System.ServiceProcess.ServiceControllerStatus ...
ToString                  ScriptMethod  System.Object ToString();

Para ser canalizado para Get-Member, um comando deve produzir saída baseada em objeto.

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], InvalidOperationException
    + FullyQualifiedErrorId : NoObjectInGetMember,Microsoft.PowerShell.Commands.GetMemberCommand

Out-Host grava diretamente no host do PowerShell, mas não produz saída baseada em objeto para o pipeline. Portanto, não pode ser canalizado para Get-Member.

Active Directory

Nota

As Ferramentas de Administração de Servidor Remoto listadas na seção de requisitos deste capítulo são necessárias para concluir esta seção. Além disso, como mencionado na introdução deste livro, seu computador de ambiente de laboratório do Windows 10 deve ser um membro do domínio do ambiente de laboratório.

Use Get-Command com o parâmetro Module para determinar quais comandos foram adicionados como parte do módulo PowerShell do ActiveDirectory quando as ferramentas de administração do servidor remoto foram instaladas.

Get-Command -Module ActiveDirectory
CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Cmdlet          Add-ADCentralAccessPolicyMember                    1.0.0.0    ActiveDi...
Cmdlet          Add-ADComputerServiceAccount                       1.0.0.0    ActiveDi...
Cmdlet          Add-ADDomainControllerPasswordReplicationPolicy    1.0.0.0    ActiveDi...
Cmdlet          Add-ADFineGrainedPasswordPolicySubject             1.0.0.0    ActiveDi...
Cmdlet          Add-ADGroupMember                                  1.0.0.0    ActiveDi...
Cmdlet          Add-ADPrincipalGroupMembership                     1.0.0.0    ActiveDi...
Cmdlet          Add-ADResourcePropertyListMember                   1.0.0.0    ActiveDi...
Cmdlet          Clear-ADAccountExpiration                          1.0.0.0    ActiveDi...
Cmdlet          Clear-ADClaimTransformLink                         1.0.0.0    ActiveDi...
Cmdlet          Disable-ADAccount                                  1.0.0.0    ActiveDi...
...

Um total de 147 comandos foram adicionados como parte do módulo PowerShell do ActiveDirectory. Alguns comandos desses comandos retornam apenas uma parte das propriedades disponíveis por padrão.

Você notou algo diferente sobre os nomes dos comandos neste módulo? A parte nominal dos comandos tem um prefixo AD. Isso é comum de ver nos comandos da maioria dos módulos. O prefixo foi projetado para ajudar a evitar conflitos de nomenclatura.

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

Name              MemberType            Definition
----              ----------            ----------
Contains          Method                bool Contains(string propertyName)
Equals            Method                bool Equals(System.Object obj)
GetEnumerator     Method                System.Collections.IDictionaryEnumerator GetEn...
GetHashCode       Method                int GetHashCode()
GetType           Method                type GetType()
ToString          Method                string ToString()
Item              ParameterizedProperty Microsoft.ActiveDirectory.Management.ADPropert...
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, Vers...
SamAccountName    Property              System.String SamAccountName {get;set;}
SID               Property              System.Security.Principal.SecurityIdentifier S...
Surname           Property              System.String Surname {get;set;}
UserPrincipalName Property              System.String UserPrincipalName {get;set;}

Mesmo que você esteja vagamente familiarizado com o Ative Directory, provavelmente está ciente de que uma conta de usuário tem mais propriedades do que as mostradas neste exemplo.

O Get-ADUser cmdlet tem um parâmetro Properties que é usado para especificar as propriedades adicionais (não padrão) que você deseja retornar. Especificar o caractere curinga * retorna todos eles.

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

Name                                 MemberType            Definition
----                                 ----------            ----------
Contains                             Method                bool Contains(string proper...
Equals                               Method                bool Equals(System.Object obj)
GetEnumerator                        Method                System.Collections.IDiction...
GetHashCode                          Method                int GetHashCode()
GetType                              Method                type GetType()
ToString                             Method                string ToString()
Item                                 ParameterizedProperty Microsoft.ActiveDirectory.M...
AccountExpirationDate                Property              System.DateTime AccountExpi...
accountExpires                       Property              System.Int64 accountExpires...
AccountLockoutTime                   Property              System.DateTime AccountLock...
AccountNotDelegated                  Property              System.Boolean AccountNotDe...
AllowReversiblePasswordEncryption    Property              System.Boolean AllowReversi...
AuthenticationPolicy                 Property              Microsoft.ActiveDirectory.M...
AuthenticationPolicySilo             Property              Microsoft.ActiveDirectory.M...
BadLogonCount                        Property              System.Int32 BadLogonCount ...
badPasswordTime                      Property              System.Int64 badPasswordTim...
badPwdCount                          Property              System.Int32 badPwdCount {g...
CannotChangePassword                 Property              System.Boolean CannotChange...
CanonicalName                        Property              System.String CanonicalName...
Certificates                         Property              Microsoft.ActiveDirectory.M...
City                                 Property              System.String City {get;set;}
CN                                   Property              System.String CN {get;}
codePage                             Property              System.Int32 codePage {get;...
Company                              Property              System.String Company {get;...
CompoundIdentitySupported            Property              Microsoft.ActiveDirectory.M...
Country                              Property              System.String Country {get;...
countryCode                          Property              System.Int32 countryCode {g...
Created                              Property              System.DateTime Created {get;}
createTimeStamp                      Property              System.DateTime createTimeS...
Deleted                              Property              System.Boolean Deleted {get;}
Department                           Property              System.String Department {g...
Description                          Property              System.String Description {...
DisplayName                          Property              System.String DisplayName {...
DistinguishedName                    Property              System.String Distinguished...
Division                             Property              System.String Division {get...
DoesNotRequirePreAuth                Property              System.Boolean DoesNotRequi...
dSCorePropagationData                Property              Microsoft.ActiveDirectory.M...
EmailAddress                         Property              System.String EmailAddress ...
EmployeeID                           Property              System.String EmployeeID {g...
EmployeeNumber                       Property              System.String EmployeeNumbe...
Enabled                              Property              System.Boolean Enabled {get...
Fax                                  Property              System.String Fax {get;set;}
GivenName                            Property              System.String GivenName {ge...
HomeDirectory                        Property              System.String HomeDirectory...
HomedirRequired                      Property              System.Boolean HomedirRequi...
HomeDrive                            Property              System.String HomeDrive {ge...
HomePage                             Property              System.String HomePage {get...
HomePhone                            Property              System.String HomePhone {ge...
Initials                             Property              System.String Initials {get...
instanceType                         Property              System.Int32 instanceType {...
isDeleted                            Property              System.Boolean isDeleted {g...
KerberosEncryptionType               Property              Microsoft.ActiveDirectory.M...
LastBadPasswordAttempt               Property              System.DateTime LastBadPass...
LastKnownParent                      Property              System.String LastKnownPare...
lastLogoff                           Property              System.Int64 lastLogoff {ge...
lastLogon                            Property              System.Int64 lastLogon {get...
LastLogonDate                        Property              System.DateTime LastLogonDa...
lastLogonTimestamp                   Property              System.Int64 lastLogonTimes...
LockedOut                            Property              System.Boolean LockedOut {g...
logonCount                           Property              System.Int32 logonCount {ge...
LogonWorkstations                    Property              System.String LogonWorkstat...
Manager                              Property              System.String Manager {get;...
MemberOf                             Property              Microsoft.ActiveDirectory.M...
MNSLogonAccount                      Property              System.Boolean MNSLogonAcco...
MobilePhone                          Property              System.String MobilePhone {...
Modified                             Property              System.DateTime Modified {g...
modifyTimeStamp                      Property              System.DateTime modifyTimeS...
msDS-User-Account-Control-Computed   Property              System.Int32 msDS-User-Acco...
Name                                 Property              System.String Name {get;}
nTSecurityDescriptor                 Property              System.DirectoryServices.Ac...
ObjectCategory                       Property              System.String ObjectCategor...
ObjectClass                          Property              System.String ObjectClass {...
ObjectGUID                           Property              System.Nullable`1[[System.G...
objectSid                            Property              System.Security.Principal.S...
Office                               Property              System.String Office {get;s...
OfficePhone                          Property              System.String OfficePhone {...
Organization                         Property              System.String Organization ...
OtherName                            Property              System.String OtherName {ge...
PasswordExpired                      Property              System.Boolean PasswordExpi...
PasswordLastSet                      Property              System.DateTime PasswordLas...
PasswordNeverExpires                 Property              System.Boolean PasswordNeve...
PasswordNotRequired                  Property              System.Boolean PasswordNotR...
POBox                                Property              System.String POBox {get;set;}
PostalCode                           Property              System.String PostalCode {g...
PrimaryGroup                         Property              System.String PrimaryGroup ...
primaryGroupID                       Property              System.Int32 primaryGroupID...
PrincipalsAllowedToDelegateToAccount Property              Microsoft.ActiveDirectory.M...
ProfilePath                          Property              System.String ProfilePath {...
ProtectedFromAccidentalDeletion      Property              System.Boolean ProtectedFro...
pwdAnswer                            Property              System.String pwdAnswer {ge...
pwdLastSet                           Property              System.Int64 pwdLastSet {ge...
pwdQuestion                          Property              System.String pwdQuestion {...
SamAccountName                       Property              System.String SamAccountNam...
sAMAccountType                       Property              System.Int32 sAMAccountType...
ScriptPath                           Property              System.String ScriptPath {g...
sDRightsEffective                    Property              System.Int32 sDRightsEffect...
ServicePrincipalNames                Property              Microsoft.ActiveDirectory.M...
SID                                  Property              System.Security.Principal.S...
SIDHistory                           Property              Microsoft.ActiveDirectory.M...
SmartcardLogonRequired               Property              System.Boolean SmartcardLog...
sn                                   Property              System.String sn {get;set;}
State                                Property              System.String State {get;set;}
StreetAddress                        Property              System.String StreetAddress...
Surname                              Property              System.String Surname {get;...
Title                                Property              System.String Title {get;set;}
TrustedForDelegation                 Property              System.Boolean TrustedForDe...
TrustedToAuthForDelegation           Property              System.Boolean TrustedToAut...
UseDESKeyOnly                        Property              System.Boolean UseDESKeyOnl...
userAccountControl                   Property              System.Int32 userAccountCon...
userCertificate                      Property              Microsoft.ActiveDirectory.M...
UserPrincipalName                    Property              System.String UserPrincipal...
uSNChanged                           Property              System.Int64 uSNChanged {get;}
uSNCreated                           Property              System.Int64 uSNCreated {get;}
whenChanged                          Property              System.DateTime whenChanged...
whenCreated                          Property              System.DateTime whenCreated...

Agora isso parece mais com isso.

Você consegue pensar em uma razão pela qual as propriedades de uma conta de usuário do Ative Directory seriam tão limitadas por padrão? Imagine se você retornasse todas as propriedades de cada conta de usuário em seu ambiente de produção do Ative Directory. Pense na degradação de desempenho que você pode causar, não apenas para os próprios controladores de domínio, mas também para sua rede. É duvidoso que você realmente precise de todos os imóveis de qualquer maneira. Retornar todas as propriedades de uma única conta de usuário é perfeitamente aceitável quando você está tentando determinar quais propriedades existem.

Não é incomum executar um comando muitas vezes ao prototipá-lo. Se você vai executar alguma consulta enorme, consulte-a uma vez e armazene os resultados em uma variável. Em seguida, trabalhe com o conteúdo da variável em vez de usar repetidamente alguma consulta cara.

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

Use o conteúdo da $Users variável em vez de executar o comando anterior várias vezes. Lembre-se de que o conteúdo da variável não é atualizado quando são feitas alterações nesse usuário no Ative Directory.

Você pode canalizar a $Users variável para Get-Member descobrir as propriedades disponíveis.

$Users | Get-Member

Em seguida, selecione as propriedades individuais canalizando $Users para Select-Object, tudo sem nunca ter que consultar o Ative Directory mais de uma vez.

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

Se você for consultar o Ative Directory mais de uma vez, use o parâmetro Properties para especificar as propriedades não padrão desejadas.

Get-ADUser -Identity mike -Properties LastLogonDate, LastBadPasswordAttempt
DistinguishedName      : CN=Mike F. Robbins,OU=Sales,DC=mikefrobbins,DC=com
Enabled                : True
GivenName              : Mike
LastBadPasswordAttempt : 2/4/2017 10:46:15 AM
LastLogonDate          : 2/18/2017 12:45:14 AM
Name                   : Mike F. Robbins
ObjectClass            : user
ObjectGUID             : a82a8c58-1332-4a57-a6e2-68e0c750ea56
SamAccountName         : mike
SID                    : S-1-5-21-2989741381-570885089-3319121794-1108
Surname                : Robbins
UserPrincipalName      : miker@mikefrobbins.com

Resumo

Neste capítulo, você aprendeu como determinar que tipo de objeto um comando produz, como determinar quais propriedades e métodos estão disponíveis para um comando e como trabalhar com comandos que limitam as propriedades retornadas por padrão.

Rever

  1. Que tipo de objeto o Get-Process cmdlet produz?
  2. Como determinar quais são as propriedades disponíveis para um comando?
  3. Se existe um comando para obter algo, mas não para definir a mesma coisa, o que você deve verificar?
  4. Como certos comandos que não produzem saída por padrão podem ser feitos para produzir saída?
  5. Se você vai trabalhar com os resultados de um comando que produz uma enorme quantidade de saída, o que você deve considerar fazer?