第 3 章 - 发现对象、属性和方法

PowerShell 是面向对象的脚本语言。 它使用从 .NET Framework 中定义的 .NET 类派生的结构化对象来表示数据和系统状态。 通过利用 .NET Framework,PowerShell 提供对各种系统功能的访问权限,包括文件系统、注册表和 Windows Management Instrumentation (WMI) 类。 PowerShell 还可以访问 .NET Framework 类库,该库包含大量可用于开发可靠 PowerShell 脚本的类集合。

在 PowerShell 中,每个项或状态都是可以浏览和操作的对象实例。 该 Get-Member cmdlet 是 PowerShell 为对象发现提供的主要工具之一,它揭示了对象的特征。 本章探讨 PowerShell 如何利用对象以及如何发现和操作这些对象,以更高效地简化脚本和管理系统。

先决条件

若要遵循本章中的特定示例,请确保实验室环境计算机是实验室环境 Active Directory 域的一部分。 还必须安装与 Windows 远程服务器管理工具(RSAT)捆绑的 Active Directory PowerShell 模块。 如果使用 Windows 10 内部版本 1809 或更高版本(包括 Windows 11),则可以将 RSAT 安装为 Windows 功能。

注意

Windows 家庭版不支持 Active Directory。

Get-Member

Get-Member 提供有关与 PowerShell 命令关联的对象、属性和方法的见解。 可以通过管道将生成基于对象的输出的任何 Get-MemberPowerShell 命令传递给 。 通过管道将命令的输出传递给该命令 Get-Member时,它会显示命令返回的对象的结构,并详细说明其属性和方法。

  • 属性:对象的属性。
  • 方法:可以对对象执行的操作。

为了说明这一概念,请考虑驾驶执照作为类比。 与任何对象一样,驱动程序许可证具有属性,例如 眼睛颜色,通常包括 bluebrown 值。 相比之下,方法表示可以对对象执行的操作。 例如, Revoke 是一种机动车部可以在驾驶执照上执行的方法。

属性

若要使用 PowerShell 检索有关系统上 Windows 时间服务的详细信息,请使用 Get-Service cmdlet。

Get-Service -Name w32time

结果包括 StatusNameDisplayName 属性。 Status 属性指示服务为 Running. Name 属性的值w32time,DisplayName 属性的值Windows Time

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

若要列出所有可用的属性和方法 Get-Service,请通过管道将其传递给 Get-Member

Get-Service -Name w32time | Get-Member

结果显示第一行包含一条重要信息。 TypeName 标识返回的对象类型,在本示例中为 System.ServiceProcess.ServiceController 对象。 此示例中,此名称通常缩写为 TypeName 的最后一部分,例如 ServiceController

   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();

请注意,通过管道传递给Get-Member管道Get-Service时,属性比默认显示的属性多。 虽然默认情况下不显示这些附加属性,但可以通过管道传递给 Select-Object 和使用 Property 参数来选择它们。 以下示例通过将通配符的结果Get-Service Select-Object *指定为 Property 参数的值来选择所有属性。

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

默认情况下,PowerShell 以表的形式返回四个属性,并将五个或更多属性作为列表返回。 但是,某些命令应用自定义格式来替代表中显示的默认属性数。 可以使用 Format-TableFormat-List 手动替代这些默认值。

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           :

还可以使用逗号分隔的列表作为 Property 参数的值来选择特定属性。

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

使用 .. 指定属性名称 Select-Object时,可以使用通配符。

在下面的示例中,用作 Can* Property 参数的值之一,以返回以Can开头的所有属性。 其中包括 CanPauseAndContinue、CanShutdown 和 CanStop

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

请注意,列出的属性比默认显示的属性多。

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

方法

方法是可以对对象执行的操作。 使用 MemberType 参数缩小以仅显示方法Get-Service的结果Get-Member范围。

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 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...

可以使用 Stop 方法停止 Windows 服务。 必须从提升的 PowerShell 会话运行此命令。

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

查询 Windows 时间服务的状态以确认它已停止。

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

可以谨慎使用方法,但应注意它们。 有时,你会发现 Get-* 没有相应 Set-* 命令的命令。 通常,可以在此方案中找到执行操作的方法 Set-*Get-SqlAgentJob SqlServer PowerShell 模块中的 cmdlet 是一个很好的示例。 不存在相应的 Set-* cmdlet,但可以使用方法完成相同的任务。 有关 SqlServer PowerShell 模块和安装说明的详细信息,请参阅 SQL Server PowerShell 概述

另一个需要注意的方法的原因是一些 PowerShell 用户假设不能使用 Get-* 命令进行破坏性更改,但如果滥用,它们实际上可能会导致严重问题。

更好的选择是,如果存在用于执行操作的专用 cmdlet。 例如,使用 Start-Service cmdlet 启动 Windows 时间服务。

默认情况下,Start-Service与 Start 方法Get-Service一样,不会返回任何结果。 但是,使用 cmdlet 的好处之一是,它通常提供方法不可用的其他功能。

在下面的示例中 ,使用 PassThru 参数,这会导致通常不生成输出的 cmdlet 来生成输出。

由于 PowerShell 不参与用户访问控制(UAC),因此必须从提升的 PowerShell 会话运行需要提升的命令,例如Start-Service

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

注意

使用 PowerShell cmdlet 时,请务必避免对其输出做出假设。

若要检索有关在实验室环境计算机上运行的 PowerShell 进程的信息,请使用 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

若要确定可用属性,请通过管道 Get-Process 传递给 Get-Member

Get-Process -Name PowerShell | Get-Member

使用 Get-Process 命令时,你可能会注意到,查看结果 Get-Member时,默认情况下显示的一些属性缺失。 此行为是因为默认情况下显示的几个值(例如 NPM(K)PM(K)WS(K)CPU(s)是计算属性。 必须通过管道命令来确定 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(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...

不能通过管道将命令传递给 Get-Member 该命令不会生成输出。 由于 Start-Service 默认情况下不生成输出,因此尝试通过管道来 Get-Member 生成错误。

Start-Service -Name w32time | Get-Member

注意

若要通过管道将命令传递到 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], InvalidOperation
   Exception
    + FullyQualifiedErrorId : NoObjectInGetMember,Microsoft.PowerShell.Comma
   nds.GetMemberCommand

若要避免此错误,请使用 .. 指定 PassThru 参数 Start-Service。 如前所述,添加 PassThru 参数会导致通常不生成输出的 cmdlet 来生成输出。

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 旨在直接在 PowerShell 主机中显示输出,并且不生成基于对象的输出。 因此,不能将其输出通过管道传递给 Get-Member,这需要基于对象的输入。

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

通过知道命令生成的对象类型,可以搜索接受该类型的对象作为输入的命令。

Get-Command -ParameterType ServiceController

以下命令通过管道或参数输入接受 ServiceController 对象。

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

注意

如本章先决条件中所述,请确保已为此部分安装 RSAT。 此外,实验室环境计算机必须是实验室环境 Active Directory 域的成员。

若要在安装 RSAT 后标识添加到 ActiveDirectory PowerShell 模块的命令,请使用 Get-CommandModule 参数结合使用。 以下示例列出了 ActiveDirectory 模块中提供的所有命令。

Get-Command -Module ActiveDirectory

ActiveDirectory PowerShell 模块总共添加了 147 个命令。

你是否观察到了这些命令的命名约定? 命令名称中的名词以 AD前缀,以避免与其他模块中的命令发生潜在的命名冲突。 此前缀是 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
...

默认情况下, Get-ADUser 该 cmdlet 检索一组有限的用户对象属性,并将其输出限制为前 1,000 个用户。 此约束是一种性能优化,旨在避免使用过多数据检索的压倒性 Active Directory。

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

即使你只对 Active Directory 有基本的了解,也可以识别到用户帐户的属性比示例中所示的属性多。

   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;}

Get-ADUser cmdlet 包含一个 Properties 参数,用于指定要检索的默认值之外的其他属性。 若要返回所有属性,请使用 * 通配符作为参数值。

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...

用于检索 Active Directory 用户帐户属性的默认配置是有意限制的,以避免性能问题。 尝试返回生产 Active Directory 环境中每个用户帐户的每个属性可能会严重降低域控制器和网络的性能。 通常,你只需要特定用户的特定属性。 但是,标识可用属性时,返回单个用户的所有属性是合理的。

在制作原型时多次运行命令并不少见。 如果在制作命令原型时预计运行资源密集型查询,请考虑执行一次,并将结果存储在变量中。 然后,可以更高效地处理变量的内容,而不是重复执行资源密集型查询。

例如,以下命令检索用户帐户的所有属性,并将结果存储在名为 $Users 的变量中。 使用变量的内容 $Users ,而不是多次运行 Get-ADUser 命令。 请记住,当用户的信息在 Active Directory 中更改时,变量的内容不会自动更新。

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

可以通过将变量管道传递给$UsersGet-Member此变量来浏览可用属性。

$Users | Get-Member -MemberType Properties

若要查看名称、LastLogonDate 和 LastBadPasswordAttempt特定属性,请通过管道将$Users变量传递给 Select-Object 此方法根据变量的内容 $Users 显示所需的属性及其值,无需对 Active Directory 进行多个查询。 与重复执行 Get-ADUser 命令相比,这是一种更具资源效率的方法。

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

查询 Active Directory 时,使用 属性 参数 Get-ADUser 筛选源中的数据,以便仅返回必要的属性。

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

总结

在本章中,你学习了如何确定命令生成的对象类型、哪些属性和方法可用于命令,以及如何处理限制默认返回的属性的命令。

审阅

  1. Get-Process cmdlet 生成哪种类型的对象?
  2. 如何确定命令的可用属性有哪些?
  3. 应检查命令是否存在以获取某些内容但不设置相同内容的情况?
  4. 默认情况下,某些不返回输出的命令如何生成输出?
  5. 在制作生成大量输出的命令时,应考虑做什么?

参考

后续步骤

在下一章中,你将了解单行器和管道。