共用方式為


第 3 章 - 探索對象、屬性和方法

PowerShell 是面向物件的腳本語言。 它會使用衍生自 .NET Framework 中所定義之 .NET 類別的結構化物件來表示數據和系統狀態。 藉由利用 .NET Framework,PowerShell 提供各種系統功能的存取權,包括文件系統、登錄和 Windows Management Instrumentation (WMI) 類別。 PowerShell 也可以存取 .NET Framework 類別庫,其中包含大量類別集合,可供您用來開發強固的 PowerShell 腳本。

在 PowerShell 中,每個項目或狀態都是可以探索和操作的物件實例。 Cmdlet Get-Member 是 PowerShell 為物件探索提供的主要工具之一,可顯示物件的特性。 本章探討 PowerShell 如何利用物件,以及如何探索及操作這些物件,以更有效率地簡化腳本及管理系統。

必要條件

若要遵循本章中的特定範例,請確定您的實驗室環境計算機是實驗室環境 Active Directory 網域的一部分。 您也必須安裝隨附於 Windows 遠端伺服器管理工具 (RSAT) 的 Active Directory PowerShell 模組。 如果您使用 Windows 10 組建 1809 或更新版本,包括 Windows 11,您可以將 RSAT 安裝為 Windows 功能。

注意

Windows 家用版不支援 Active Directory。

Get-Member (取得成員)

Get-Member 提供與 PowerShell 命令相關聯之物件、屬性和方法的深入解析。 您可以將任何產生物件型輸出的 PowerShell 命令透過管線傳送至 Get-Member。 當您使用管線將命令的輸出傳送至 Get-Member時,它會顯示命令傳回的對象結構,並詳細說明其屬性和方法。

  • 屬性:對象的屬性。
  • 方法:您可以在 物件上執行的動作。

為了說明這個概念,請考慮駕駛執照作為類比。 和任何對象一樣,駕駛執照具有屬性,例如 眼睛色彩,通常包含 bluebrown 值。 相反地,方法代表您可以在 對象上執行的動作。 例如, Revoke 是機動車輛部可以在駕駛執照上執行的方法。

屬性

若要使用PowerShell擷取系統上 Windows Time 服務的詳細數據,請使用 Get-Service Cmdlet。

Get-Service -Name w32time

結果包括 StatusNameDisplayName 屬性。 Status 屬性表示服務為 Running。 Name 屬性的值是 ,而 DisplayName 屬性的值是 w32time

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-Service 傳送至 Get-Member 時,屬性比預設顯示的更多。 雖然預設不會顯示這些額外的屬性,但您可以透過管線傳送至 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開頭的所有屬性。 其中包括 CanPauseAndContinueCanShutdownCanStop

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

請注意,列出的屬性會比預設顯示更多。

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

方法

方法是您可以在 物件上執行的動作。 使用MemberType參數來縮小Get-Member的結果範圍,以僅顯示Get-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 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 Time 服務的狀態,以確認它已停止。

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 來執行某個動作,請使用該專用的 cmdlet。 例如,使用 Start-Service Cmdlet 啟動 Windows Time 服務。

根據預設,Start-Service就像的 StartGet-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;}

Cmdlet Get-ADUser 包含 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 *

您可以將 $Users 變數通過管線傳送至 Get-Member 來探索可用的屬性。

$Users | Get-Member -MemberType Properties

若要檢視 Name。 這個方法會根據變數的內容 $Users 顯示所需的屬性及其值,而不需要對 Active Directory 進行多個查詢。 這是比重複執行 Get-ADUser 命令更有資源效率的方法。

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

當您查詢 Active Directory 時,請使用 參數篩選來源的數據,只傳回必要的屬性。

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. Cmdlet 會產生何種類型的物件 Get-Process
  2. 如何判斷命令可用的屬性為何?
  3. 您應該檢查是否存在一個命令來取得某個專案,卻沒有相同的命令來設置這個專案?
  4. 某些預設不會傳回輸出的命令如何產生輸出?
  5. 在建立產生大量輸出的命令原型時,您應該考慮怎麼做?

參考資料

下一步

第四 ,你會學到關於單行程式碼和管道命令。